How to Get Request Headers in Express: Simple Guide
In Express, you get request headers using the
req.headers object inside your route handler. This object contains all headers sent by the client as key-value pairs.Syntax
Use req.headers inside your route handler to access all request headers as an object. Each header name is a key, and its value is the header's value.
Example parts:
req: The request object provided by Express.headers: Property holding all headers.
javascript
app.get('/path', (req, res) => { const headers = req.headers; // Use headers object here res.send(headers); });
Example
This example shows a simple Express server that reads and returns the request headers sent by the client.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { const headers = req.headers; res.json(headers); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
{"host":"localhost:3000","user-agent":"curl/7.68.0","accept":"*/*"}
Common Pitfalls
Common mistakes when accessing headers in Express include:
- Trying to access headers with incorrect casing (header names are lowercase in
req.headers). - Using
req.get()without knowing it returns a single header value, not all headers. - Expecting headers to be in a different format (they are always strings).
Always use lowercase header names when accessing req.headers directly.
javascript
app.get('/wrong', (req, res) => { // Wrong: header names are case-sensitive keys in req.headers const contentType = req.headers['Content-Type']; // undefined // Right: const contentTypeCorrect = req.headers['content-type']; res.send(contentTypeCorrect || 'No content-type header'); });
Quick Reference
Summary tips for getting request headers in Express:
- Use
req.headersto get all headers as an object. - Header names are always lowercase keys in
req.headers. - Use
req.get('Header-Name')to get a single header value case-insensitively. - Headers values are strings; parse if needed.
Key Takeaways
Access all request headers in Express using the req.headers object.
Header names in req.headers are lowercase strings.
Use req.get('Header-Name') to retrieve a single header value case-insensitively.
Headers values are strings; convert them if you need other types.
Always check for header existence to avoid undefined errors.