HTTP headers
suggest changeHTTP headers are name/value pairs sent before the body of a request or response. They carry metadata: content type, length, caching rules, cookies, authentication credentials, and more.
Header names are case-insensitive (Content-Type and content-type are the same header) and a header can appear more than once in a message.
This article shows how to work with headers on both sides:
- on the server, with the built-in
node:httpmodule (req.headers,res.setHeader()etc.) - on the client, with the global
fetch()and theHeadersclass
Reading request headers on the server
In a node:http server, req.headers is a plain object with lower-cased header names as keys:
import http from 'node:http';
const server = http.createServer((req, res) => {
// names are always lower-case, no matter how the client sent them
const ua = req.headers['user-agent'];
const accept = req.headers.accept ?? '*/*';
const auth = req.headers.authorization; // undefined if not sent
console.log(req.method, req.url);
console.log('User-Agent:', ua);
console.log('Accept:', accept);
console.log('has Authorization:', auth !== undefined);
res.end('ok\n');
});
server.listen(8080, () => console.log('listening on http://localhost:8080'));
Test it with curl -H "Authorization: Bearer abc" http://localhost:8080/.
When a client sends the same header multiple times, Node.js merges the values into a single string in req.headers:
set-cookieis always an array of stringscookievalues are joined with;- for most other headers values are joined with
,(e.g.x-tag: a, b) - for headers that can only have one value (
content-type,content-length,user-agent,authorization,hostand a few others) duplicates are discarded and the first value wins
If you need every value separately, or the original casing and order, use req.headersDistinct or req.rawHeaders:
// request sent with "X-Tag: a" and "X-Tag: b"
console.log(req.headers['x-tag']); // 'a, b'
console.log(req.headersDistinct['x-tag']); // [ 'a', 'b' ]
// flat list: name, value, name, value, ... with original casing
console.log(req.rawHeaders);
// [ 'Host', 'localhost:8080', 'X-Tag', 'a', 'X-Tag', 'b', ... ]
headersDistinct (Node.js 18.3+) always maps a lower-case name to an array of values.
Setting response headers
There are two ways to set response headers: call res.setHeader() one header at a time, or pass them all to res.writeHead().
import http from 'node:http';
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
// multiple values for one header: pass an array
res.setHeader('Set-Cookie', ['session=abc123; HttpOnly; Path=/', 'theme=dark; Path=/']);
// appendHeader() adds a value instead of replacing (Node.js 18.3+)
res.appendHeader('Set-Cookie', 'lang=en; Path=/');
// inspect headers queued so far
console.log(res.getHeaderNames()); // [ 'content-type', 'cache-control', 'set-cookie' ]
console.log(res.getHeader('cache-control')); // 'no-store' (lookup is case-insensitive)
console.log(res.hasHeader('X-Powered-By')); // false
res.removeHeader('Cache-Control');
res.statusCode = 200;
res.end(JSON.stringify({ ok: true }));
});
server.listen(8080);
res.setHeader() replaces any existing value for that name. Values can be strings, numbers or arrays of strings.
res.writeHead() sets the status code and headers in one call. Headers passed to it are merged with those set earlier via setHeader(), and take precedence:
res.setHeader('X-Request-Id', '42');
res.writeHead(201, {
'Content-Type': 'text/plain; charset=utf-8',
'Location': '/items/42',
});
res.end('created\n');
Node.js adds some headers automatically: Date, Connection, Keep-Alive and either Content-Length (if it can be determined) or Transfer-Encoding: chunked. You can still set Content-Length yourself when you know the size of the body; use Buffer.byteLength(body), not body.length, because the header counts bytes, not characters.
Headers can only be sent once
Headers go on the wire before the body. Once you call res.writeHead(), res.write() or res.end(), headers are sent and can no longer be changed:
res.end('done');
console.log(res.headersSent); // true
try {
res.setHeader('X-Too-Late', '1');
} catch (err) {
console.log(err.code); // ERR_HTTP_HEADERS_SENT
}
This is the source of the common error Cannot set headers after they are sent to the client. It usually means a handler responded twice, e.g. a missing return after sending an error response. Check res.headersSent if you're not sure.
Invalid header names and values
Node.js validates headers and throws if a name contains illegal characters or a value contains control characters like \r\n. This protects against header injection (response splitting) when header values come from user input. You can validate ahead of time:
import { validateHeaderName, validateHeaderValue } from 'node:http';
try {
validateHeaderName('bad name');
} catch (err) {
console.log(err.code); // ERR_INVALID_HTTP_TOKEN
}
try {
validateHeaderValue('x-user', 'evil\r\nSet-Cookie: admin=1');
} catch (err) {
console.log(err.code); // ERR_INVALID_CHAR
}
Header values should be ASCII. To send non-ASCII text (e.g. a file name) encode it first, for example with encodeURIComponent():
const fileName = 'raport żółty.pdf';
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`);
Sending and reading headers with fetch
fetch() is available globally since Node.js 18. Pass request headers with the headers option, as a plain object, an array of pairs or a Headers instance:
const res = await fetch('https://api.github.com/repos/nodejs/node', {
headers: {
'Accept': 'application/vnd.github+json',
'User-Agent': 'my-app/1.0',
// 'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
},
});
console.log(res.status);
console.log(res.headers.get('content-type')); // application/json; charset=utf-8
console.log(res.headers.get('x-ratelimit-remaining')); // e.g. '59'
console.log(res.headers.get('x-does-not-exist')); // null
const repo = await res.json();
console.log(repo.full_name);
res.headers is a Headers object. get() is case-insensitive and returns null for missing headers. To list all response headers, iterate over it:
for (const [name, value] of res.headers) {
console.log(`${name}: ${value}`);
}
// or convert to a plain object
const obj = Object.fromEntries(res.headers);
Names returned by iteration are lower-case and sorted.
The Headers class
Headers is a case-insensitive multi-map, the same as in browsers. You can use it to build request headers:
const headers = new Headers({ 'Accept': 'application/json' });
headers.set('Content-Type', 'application/json'); // replace
headers.append('Accept', 'text/plain'); // add another value
headers.delete('X-Unused');
console.log(headers.get('accept')); // 'application/json, text/plain'
console.log(headers.has('CONTENT-TYPE')); // true
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
headers,
body: JSON.stringify({ hello: 'world' }),
});
console.log((await res.json()).headers);
get() joins multiple values with , . That breaks for Set-Cookie, because cookie values often contain commas (e.g. in Expires=Wed, 21 Oct 2026 ...). Use getSetCookie() (Node.js 19.7+) to get them as an array:
const res = await fetch('http://localhost:8080/');
console.log(res.headers.get('set-cookie'));
// session=abc123; HttpOnly; Path=/, theme=dark; Path=/, lang=en; Path=/
console.log(res.headers.getSetCookie());
// [ 'session=abc123; HttpOnly; Path=/', 'theme=dark; Path=/', 'lang=en; Path=/' ]
Like the server side, Headers rejects invalid values:
try {
new Headers().set('X-Bad', 'a\nb');
} catch (err) {
console.log(err.name); // TypeError
}
Note that fetch() adds some headers on its own (accept: */*, accept-encoding, accept-language, sec-fetch-mode, user-agent: node). Set them explicitly if a server requires specific values, e.g. many APIs reject requests without a meaningful User-Agent.
Example: content negotiation and conditional requests
Here's a small server that uses request headers to decide what to send, and response headers to enable caching with ETag:
import http from 'node:http';
import { createHash } from 'node:crypto';
const data = { name: 'Node.js', version: process.version };
const server = http.createServer((req, res) => {
const wantsJson = (req.headers.accept ?? '').includes('application/json');
const body = wantsJson ? JSON.stringify(data) : `${data.name} ${data.version}\n`;
const etag = `"${createHash('sha1').update(body).digest('base64url')}"`;
res.setHeader('ETag', etag);
res.setHeader('Cache-Control', 'max-age=60');
res.setHeader('Vary', 'Accept');
if (req.headers['if-none-match'] === etag) {
res.writeHead(304);
return res.end();
}
res.writeHead(200, {
'Content-Type': wantsJson ? 'application/json' : 'text/plain; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
});
res.end(body);
});
server.listen(8080, async () => {
const url = 'http://localhost:8080/';
const r1 = await fetch(url, { headers: { Accept: 'application/json' } });
console.log(r1.status, r1.headers.get('content-type'), await r1.text());
const etag = r1.headers.get('etag');
const r2 = await fetch(url, {
headers: { 'Accept': 'application/json', 'If-None-Match': etag },
});
console.log(r2.status); // 304: client can reuse its cached copy
server.close();
});
Headers in Express
Express wraps the same objects, so everything above applies. It adds a few conveniences:
req.get('Content-Type')reads a request header (case-insensitive)res.set('X-Name', 'value')orres.set({ ... })sets response headersres.append('Set-Cookie', '...')adds a valueres.type('json')setsContent-Typefrom a short name
Express also sends X-Powered-By: Express by default; disable it with app.disable('x-powered-by').
For cross-origin headers (Access-Control-Allow-Origin and friends) see Node.js with CORS.