Introduction
HTTP headers are key-value pairs exchanged between the client and the server to provide additional information about a request or response. In Express.js, working with headers is straightforward using built-in methods such as req.headers, req.get(), res.set(), and res.header().
Information
Prerequisites
- Node.js installed
- Basic knowledge of JavaScript
- Express.js installed using npm install express
- Understanding of basic Express.js routing
Setting Up an Express Application
Basic Express Server
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});What Are HTTP Headers?
Headers provide metadata about an HTTP request or response. They describe how data should be processed, the content format, authentication details, caching behavior, and many other aspects of communication between clients and servers.
Common HTTP Headers
| Header | Purpose | Direction |
|---|---|---|
| Content-Type | Specifies the format of the request or response body. | Request & Response |
| Authorization | Provides authentication credentials. | Request |
| Accept | Lists the content types accepted by the client. | Request |
| User-Agent | Identifies the client application. | Request |
| Cache-Control | Controls caching behavior. | Response |
| Set-Cookie | Sends cookies to the client. | Response |
Reading Request Headers
Express exposes all incoming request headers through the req.headers object.
Accessing Request Headers
app.get("/", (req, res) => {
console.log(req.headers);
res.send("Headers received.");
});Reading a Specific Header
Header names are case-insensitive. Express automatically normalizes them to lowercase.
Accessing a Header
app.get("/", (req, res) => {
const userAgent = req.headers["user-agent"];
res.send(userAgent);
});Using req.get()
Express provides the convenient req.get() method to retrieve a specific request header.
Using req.get()
app.get("/", (req, res) => {
const language = req.get("Accept-Language");
res.send(language || "Language header not provided");
});| Method | Description |
|---|---|
| req.headers | Returns all request headers. |
| req.get(name) | Returns the value of a specific header. |
Setting Response Headers
Use res.set() or res.header() to add response headers before sending a response.
Setting a Response Header
app.get("/", (req, res) => {
res.set("Content-Type", "text/plain");
res.send("Hello from Express!");
});Setting Multiple Headers
Setting Multiple Headers
app.get("/", (req, res) => {
res.set({
"Content-Type": "application/json",
"Cache-Control": "no-cache",
"X-App-Name": "Express Demo"
});
res.json({
success: true
});
});Using res.header()
The res.header() method is an alias of res.set(). Both methods behave the same way.
Using res.header()
app.get("/", (req, res) => {
res.header("X-Version", "1.0");
res.send("Header Added");
});Retrieving Response Headers
Before the response is sent, you can inspect the value of a response header.
Getting a Response Header
app.get("/", (req, res) => {
res.set("Content-Type", "application/json");
console.log(res.get("Content-Type"));
res.json({
message: "Success"
});
});Removing Response Headers
Express inherits Node.js response methods, allowing headers to be removed before they are sent.
Removing a Header
app.get("/", (req, res) => {
res.set("Cache-Control", "no-cache");
res.removeHeader("Cache-Control");
res.send("Done");
});Checking Authorization Headers
Authentication tokens are commonly sent using the Authorization header.
Authorization Header Example
app.get("/profile", (req, res) => {
const token = req.get("Authorization");
if (!token) {
return res.status(401).send("Unauthorized");
}
res.send("Access Granted");
});Returning JSON with Custom Headers
JSON Response with Headers
app.get("/api/users", (req, res) => {
res.set("Cache-Control", "no-store");
res.status(200).json({
id: 1,
name: "Alice",
role: "Developer"
});
});Request and Response Lifecycle
Frequently Used Content Types
| Content Type | Common Usage |
|---|---|
| text/plain | Plain text responses. |
| text/html | HTML web pages. |
| application/json | REST API responses. |
| multipart/form-data | File uploads. |
| application/xml | XML responses. |
Express Header Methods
| Method | Purpose |
|---|---|
| req.headers | Returns all request headers. |
| req.get(name) | Returns a specific request header. |
| res.set() | Sets one or more response headers. |
| res.header() | Alias for res.set(). |
| res.get() | Retrieves a response header. |
| res.removeHeader() | Removes a response header before sending the response. |
Best Practices đĄ
- Always set the correct Content-Type for responses.
- Use req.get() when reading individual request headers.
- Set all required headers before sending the response.
- Use appropriate HTTP status codes along with response headers.
- Do not expose sensitive information through custom headers.
Best Practice
Common Mistakes â ī¸
- Attempting to modify headers after calling res.send() or res.json().
- Using incorrect header names or values.
- Forgetting to validate the Authorization header.
- Manually setting the JSON content type before every res.json() response.
- Exposing confidential information in response headers.