Working With Headers

Read, Set, Remove — and Standard Headers Worth Knowing

Working With Headers

Headers carry metadata about the request/response. Get/set them correctly.

3 min read Level 1/5 #nodejs#http#headers
What you'll learn
  • Read request headers
  • Set response headers
  • Know the most important ones

Headers are case-insensitive metadata key-value pairs on HTTP messages. Node normalizes them to lowercase.

Reading

req.headers["user-agent"];          // 'curl/8.x'
req.headers["accept"];              // 'application/json'
req.headers["authorization"];       // 'Bearer eyJh...'
req.headers["x-forwarded-for"];     // client IP if behind proxy

req.headers is a plain object — lookup is case-insensitive in that all keys are already lowercase.

Setting

res.setHeader("content-type", "application/json");
res.setHeader("cache-control", "no-store");
res.setHeader("x-request-id", reqId);

Must be set before res.end() (or before the first res.write).

Removing

res.removeHeader("x-powered-by");

(Express adds X-Powered-By: Express by default — many people remove it for security-through-obscurity reasons.)

Multi-Value Headers

For headers like Set-Cookie that can appear multiple times, pass an array:

res.setHeader("set-cookie", ["a=1; HttpOnly", "b=2; HttpOnly"]);

Standard Response Headers Worth Knowing

HeaderPurpose
content-typeMIME type of the body
content-lengthBody size (often auto-set)
cache-controlHow long browsers/CDNs cache
etagCache validator
set-cookieSet a cookie
locationWhere to redirect (with 3xx status)
strict-transport-securityForce HTTPS (HSTS)
content-security-policyRestrict what scripts load
x-content-type-options: nosniffDisable MIME sniffing
referrer-policyControl the Referer header

The last four are security headers — most production apps set them all. Many proxies/CDNs can add them globally.

A Redirect

res.writeHead(302, { location: "/login" });
res.end();

301 = permanent, 302 / 307 = temporary, 308 = permanent with method preservation.

Streaming Responses →