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

Introduction

HTTP headers are key-value pairs exchanged between a client and a server as part of every HTTP request and response. They carry important metadata such as content type, authentication information, caching rules, cookies, and more. In Node.js, the built-in http module provides easy access to both request and response headers.

Information

Headers are sent before the message body. Once the response body starts being sent, response headers can no longer be modified.

Prerequisites

  • Node.js installed
  • Basic understanding of the HTTP protocol
  • Knowledge of creating a basic server using the http module

What Are HTTP Headers?

Headers provide additional information about an HTTP request or response. They help clients and servers understand how to process data, negotiate content formats, manage caching, maintain authentication, and much more.

Client Sends Request
Request Headers
Server Processes Request
Response Headers
Response Body

Common HTTP Headers

HeaderPurposeDirection
Content-TypeSpecifies the format of the message body.Request & Response
Content-LengthSpecifies the size of the message body.Request & Response
AuthorizationProvides authentication credentials.Request
AcceptIndicates the content types the client accepts.Request
User-AgentIdentifies the client application.Request
Cache-ControlControls caching behavior.Response
Set-CookieSends cookies to the client.Response

Accessing Request Headers

Incoming request headers are available through the req.headers object. Header names are automatically converted to lowercase by Node.js.

Reading Request Headers

const http = require("http");

const server = http.createServer((req, res) => {

    console.log(req.headers);

    res.end("Headers received.");

});

server.listen(3000);

Reading a Specific Header

You can access an individual header using its lowercase name.

Accessing the User-Agent Header

const userAgent = req.headers["user-agent"];

console.log(userAgent);
Header NameExample Value
hostlocalhost:3000
user-agentMozilla/5.0 ...
accepttext/html, application/json

Setting Response Headers

Use the setHeader() method to add headers before sending the response.

Setting Response Headers

const http = require("http");

const server = http.createServer((req, res) => {

    res.setHeader("Content-Type", "text/plain");

    res.end("Hello, World!");

});

server.listen(3000);

Setting Multiple Headers

Multiple Response Headers

res.setHeader("Content-Type", "application/json");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("X-Powered-By", "Node.js");

res.end(JSON.stringify({
    message: "Success"
}));

Using writeHead()

The writeHead() method allows you to send the status code and multiple headers together in a single call.

Using writeHead()

res.writeHead(200, {
    "Content-Type": "application/json",
    "Cache-Control": "no-store"
});

res.end(JSON.stringify({
    success: true
}));

setHeader() vs writeHead()

FeaturesetHeader()writeHead()
Sets one header at a time✅ Yes❌ No
Can set multiple headersUsing multiple calls✅ Yes
Sets status code❌ No✅ Yes
Common usageFlexible updatesInitial response setup

Retrieving Response Headers

Node.js allows you to inspect response headers before they are sent.

Getting a Response Header

res.setHeader("Content-Type", "application/json");

console.log(res.getHeader("Content-Type"));

Removing Response Headers

If a header is no longer needed before the response is sent, it can be removed.

Removing a Header

res.setHeader("Cache-Control", "no-cache");

res.removeHeader("Cache-Control");

Example: Returning JSON

JSON API Response

const http = require("http");

const server = http.createServer((req, res) => {

    res.writeHead(200, {
        "Content-Type": "application/json"
    });

    res.end(JSON.stringify({
        id: 1,
        name: "Alice",
        role: "Developer"
    }));

});

server.listen(3000);

Example: Simple Authentication Header

The following example checks whether an Authorization header is present.

Checking Authorization Header

const auth = req.headers.authorization;

if (!auth) {

    res.writeHead(401, {
        "Content-Type": "text/plain"
    });

    res.end("Unauthorized");
}
else {

    res.end("Access Granted");
}

Request and Response Lifecycle

Client Sends Request
Request Headers
Server Reads Headers
Server Processes Request
Server Sets Response Headers
Response Body Sent

Frequently Used Response Content Types

Content TypeUsed For
text/plainPlain text responses.
text/htmlHTML documents.
application/jsonREST APIs and JSON data.
application/xmlXML documents.
image/pngPNG images.
text/cssCSS stylesheets.
application/javascriptJavaScript files.

Best Practices 💡

  • Always set the correct Content-Type for every response.
  • Read request headers in lowercase since Node.js normalizes header names.
  • Set all required headers before calling res.end().
  • Return appropriate HTTP status codes along with response headers.
  • Avoid exposing sensitive information through custom headers.

Best Practice

Use application/json when building APIs and text/html when serving web pages. Choosing the correct Content-Type ensures clients interpret the response correctly.

Common Mistakes âš ī¸

  • Trying to modify headers after calling res.end().
  • Using incorrect header names or values.
  • Forgetting to set the Content-Type header.
  • Assuming header names are case-sensitive in Node.js.
  • Sending confidential information in HTTP headers.

Warning

If headers have already been sent, attempting to modify them will result in an error such as Error [ERR_HTTP_HEADERS_SENT]. Always configure headers before writing or ending the response.

Learning Roadmap 🚀

HTTP Basics
HTTP Headers
Status Codes
Routing
Request Body Parsing
REST APIs
Authentication & Cookies

Official Resources

>>"HTTP headers are the conversation that happens before the actual message is delivered."

Summary

HTTP headers are an essential part of client-server communication. In this tutorial, you learned how to read request headers, set and remove response headers, use setHeader() and writeHead(), inspect response headers, work with common content types, and follow best practices for building reliable Node.js applications using the native http module.