Read, Set, Remove — and Standard Headers Worth Knowing
Working With Headers
Headers carry metadata about the request/response. Get/set them correctly.
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
| Header | Purpose |
|---|---|
content-type | MIME type of the body |
content-length | Body size (often auto-set) |
cache-control | How long browsers/CDNs cache |
etag | Cache validator |
set-cookie | Set a cookie |
location | Where to redirect (with 3xx status) |
strict-transport-security | Force HTTPS (HSTS) |
content-security-policy | Restrict what scripts load |
x-content-type-options: nosniff | Disable MIME sniffing |
referrer-policy | Control 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.