Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Express 4 and 5 req.get doesnt return header if not set in lowercase #5288

Open
fbritoferreira opened this issue Oct 18, 2023 · 2 comments
Open

Comments

@fbritoferreira
Copy link

fbritoferreira commented Oct 18, 2023

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.

@dougwilson
Copy link
Contributor

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.

@ArtemNikolaev
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants