We use req.headers to see extra information sent by the browser or client with a web request. This helps the server understand details like language, type of data, or authorization.
req.headers for HTTP headers in Express
const headers = req.headers; // headers is an object with all HTTP headers in lowercase keys const userAgent = req.headers['user-agent'];
req.headers is a plain JavaScript object where each key is a header name in lowercase.
You access headers using bracket notation with the header name as a string, for example req.headers['content-type'].
const host = req.headers['host'];const contentType = req.headers['content-type'];const auth = req.headers['authorization'];This Express app reads the User-Agent and Accept headers from the incoming request. It then sends back a message showing these values.
Try opening http://localhost:3000 in a browser to see your browser info and accepted content types.
import express from 'express'; const app = express(); app.get('/', (req, res) => { const userAgent = req.headers['user-agent']; const accept = req.headers['accept']; res.send(`Your browser info: ${userAgent}\nYou accept: ${accept}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Header names are always lowercase in req.headers, even if the client sent them with uppercase letters.
Some headers like cookie or authorization may contain sensitive info, so handle them carefully.
If a header is not sent by the client, accessing it returns undefined.
req.headers lets you read all HTTP headers sent by the client.
Headers are stored as lowercase keys in a JavaScript object.
You can use this info to customize responses or check client details.