0
0
Expressframework~5 mins

req.headers for HTTP headers in Express

Choose your learning style9 modes available
Introduction

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.

When you want to check what type of data the client can accept (like JSON or HTML).
When you need to read authorization tokens sent by the client to allow access.
When you want to know the client's language preference to show content in that language.
When you want to log or debug what headers the client sent for troubleshooting.
When you want to customize the response based on client device or browser info.
Syntax
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'].

Examples
Gets the host name from the headers.
Express
const host = req.headers['host'];
Reads the content type of the request body.
Express
const contentType = req.headers['content-type'];
Gets the authorization token sent by the client.
Express
const auth = req.headers['authorization'];
Sample Program

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.

Express
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');
});
OutputSuccess
Important Notes

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.

Summary

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.