Working with HTTP Headers in Express.js đŸ“Ŧ

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

Headers are always sent before the response body. Once the response is sent, response headers cannot be modified.

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.

Client Sends Request
Request Headers
Express Application
Response Headers
Response Body

Common HTTP Headers

HeaderPurposeDirection
Content-TypeSpecifies the format of the request or response body.Request & Response
AuthorizationProvides authentication credentials.Request
AcceptLists the content types accepted by the client.Request
User-AgentIdentifies the client application.Request
Cache-ControlControls caching behavior.Response
Set-CookieSends 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");

});
MethodDescription
req.headersReturns 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

Client Sends Request
Express Reads Request Headers
Route Handler Executes
Response Headers Set
Response Sent to Client

Frequently Used Content Types

Content TypeCommon Usage
text/plainPlain text responses.
text/htmlHTML web pages.
application/jsonREST API responses.
multipart/form-dataFile uploads.
application/xmlXML responses.

Express Header Methods

MethodPurpose
req.headersReturns 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

Use res.json() for JSON responses. Express automatically sets the Content-Type header to application/json, reducing boilerplate and improving code readability.

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.

Warning

Once a response has been sent using methods such as res.send(), res.json(), or res.end(), Express sends the response headers automatically. Any attempt to modify them afterward will result in an error.

Learning Roadmap 🚀

Express.js Basics
Routing
HTTP Headers
Middleware
Authentication
Cookies & Sessions
REST APIs

Official Resources

>>"HTTP headers carry the instructions that help clients and servers communicate effectively before the actual data is exchanged."

Summary

In this tutorial, you learned how to work with HTTP headers in Express.js by reading request headers with req.headers and req.get(), setting response headers using res.set() and res.header(), retrieving and removing headers, handling authorization headers, and following best practices for building reliable Express.js applications.