express
express copied to clipboard
Express 4 and 5 `req.get` doesnt return header if not set in lowercase
In the documentation, it's stated that req.get
is intended to be case-insensitive. However, it appears that when you set a custom header in a middleware, this case-insensitivity breaks if the header is not in lowercase. Should this behavior be corrected, or should the guidance be to always set headers in lowercase? Perhaps, adding a setHeader
function in the request object could be a solution to this issue.
The problem seems to originate from this part of the code: https://github.com/expressjs/express/blob/master/lib/request.js#L82, where the headers are not being converted to lowercase, while the input is.
Example code
const express = require('express');
const app = express();
app.use((req, res, next) => {
req.headers['X-filipe'] = 'filipe';
next();
});
app.get('/', (req, res) => {
res.json({ header: req.get('x-filipe') });
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
Expected output:
{"header": "filipe"}
This adjustment ensures that the headers are consistently in lowercase, aligning with the case-insensitive nature of req.get
.
Yes, you need to set req.headers
in lower case only. That is part of Node.js itself, not express specific:
https://nodejs.org/dist/latest-v21.x/docs/api/http.html#messageheaders
Key-value pairs of header names and values. Header names are lower-cased.
When middleware start working, all headers alredy parsed and transformed if neede. All middleware changes goes on top of this updates. So be sure to controll it yourself or with String.prototype.toLowerCase
method.