Introduction
Now that we understand different ways to use middleware, let’s learn how to access request headers. This knowledge will be essential for our authentication middleware in the next section.
What are headers?
Headers are pieces of information sent with every HTTP request and response. They contain metadata about the request, like:
- What type of data is being sent
- What type of response the client expects
- Authentication information
- Browser information
Where to find headers in browser devtools
- Go to the Network tab in devtools
- Make a request to your API
- Click on the request in the Network tab
- Look at the Headers section - you’ll see:
- Request Headers - Headers sent by the browser
- Response Headers - Headers sent by the server
Common request headers you’ll see
User-Agent- Browser and operating system infoAccept- What type of response the client wants (JSON, HTML, etc.)Content-Type- Type of data being sentAuthorization- Authentication tokensOrigin- Where the request came from (important for CORS)
How to access headers in your code
You can access all request headers using req.headers. This is an object containing all the headers sent by the client.
app.get("/example", (req, res) => {
// Access headers
const userAgent = req.headers["user-agent"];
const authorization = req.headers.authorization;
const contentType = req.headers["content-type"];
console.log("User Agent:", userAgent);
console.log("Authorization:", authorization);
console.log("contentType:", contentType);
});
Important: Headers are always strings, and Express converts all header names to lowercase in req.headers. So use req.headers.authorization (lowercase), not req.headers.Authorization.