Sub topic 7
Working with the Headers Interface
HTTP headers are name/value pairs that carry metadata about a request or a response, such as the content type, authentication tokens, caching rules, and rate-limit counters. The Fetch API represents them with the Headers interface. The same interface appears in three places: as response.headers, as request.headers, and as a standalone object you build yourself and pass to fetch().
This chapter assumes you know JavaScript objects and arrays, Promises and async/await, and basic HTTP headers. It also assumes you have read the earlier chapters on the Response object and on request options, because it builds on fetch(url, { headers }) without explaining it again. The code runs in a modern browser console or in Node.js 18 or later saved as an .mjs file. Where an example needs a response, it builds one locally with new Response(), so no network is required.
Why a dedicated interface instead of a plain object
A plain object such as { 'Content-Type': 'application/json' } works fine as the headers option, and you will see it everywhere. HTTP headers follow rules that a plain object cannot enforce, though:
- Header names are case-insensitive.
Content-Typeandcontent-typeare the same header. - A header can appear more than once.
Accept,Cache-Control, andSet-Cookieare common examples. - Names and values have a restricted character set. A newline inside a value would let an attacker inject extra headers, so the interface rejects it.
- Some headers belong to the browser and cannot be set by scripts.
Headers handles all of these rules. When you pass a plain object to fetch(), the browser converts it into a Headers object internally, so the same rules apply either way. Knowing that conversion explains most of the surprises later in this chapter.
Creating a Headers object
The constructor accepts three input shapes: a plain object, an array of [name, value] pairs, or another Headers instance. You can also call it with no argument and add entries afterwards.
const fromObject = new Headers({ Accept: 'application/json' });
const fromPairs = new Headers([
['Accept', 'application/json'],
['Accept', 'text/plain'], // repeated name: both values kept
['X-Request-Id', 'abc-123']
]);
const copy = new Headers(fromPairs); // independent copy
console.log(fromObject.get('accept')); // 'application/json'
console.log(fromPairs.get('ACCEPT')); // 'application/json, text/plain'
console.log(copy.get('x-request-id')); // 'abc-123'Use the array form when you need repeated names. An object literal cannot hold two Accept keys. Copying with new Headers(existing) gives you a separate object, so later changes to the copy do not affect the original. That matters when you start from a shared set of defaults.
The methods
| Method | What it does | Returns |
|---|---|---|
| `append(name, value)` | Adds a value. If the name exists, the new value is joined to the old one. | `undefined` |
| `set(name, value)` | Replaces every existing value for the name with one value. | `undefined` |
| `get(name)` | Reads the combined value of all entries with that name. | string or `null` |
| `has(name)` | Checks whether the name is present. | boolean |
| `delete(name)` | Removes every value for the name. | `undefined` |
| `getSetCookie()` | Returns each `Set-Cookie` value as a separate array element. | array of strings |
| `entries()`, `keys()`, `values()`, `forEach()` | Iterate over the headers. | iterator or `undefined` |
append versus set
The difference between append and set is the most common source of duplicated headers.
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Accept', 'text/plain');
console.log(headers.get('Accept')); // 'application/json, text/plain'
headers.set('Accept', 'text/html');
console.log(headers.get('Accept')); // 'text/html'
headers.set('Authorization', 'Bearer old');
headers.set('authorization', 'Bearer new'); // same header, different case
console.log(headers.get('Authorization')); // 'Bearer new'
headers.delete('ACCEPT');
console.log(headers.has('accept')); // false
console.log(headers.get('accept')); // nullUse set for headers that must have exactly one value, such as Authorization, Content-Type, and custom IDs. Use append only when the header is defined as a list and you want to add to it. If you call append('Authorization', ...) twice, the server receives Bearer a, Bearer b, and most servers will reject it.
get returns a combined string
get() does not return an array. All values for a name are joined with a comma and a space. For most list-valued headers this is exactly what HTTP allows, because the combined form means the same as separate lines. To work with individual values, split the string yourself:
const response = new Response('ok', {
headers: [
['Cache-Control', 'no-cache'],
['Cache-Control', 'max-age=0']
]
});
const directives = response.headers
.get('cache-control')
.split(',')
.map((part) => part.trim());
console.log(directives); // ['no-cache', 'max-age=0']Set-Cookie is the exception. Its values can contain commas, for example in an Expires=Wed, 21 Oct 2026 ... date, so joining them would corrupt them. getSetCookie() returns each cookie line separately. Browsers never show Set-Cookie to scripts, so this method is mainly useful in server runtimes such as Node.js (19.7 and later), Deno, and Bun.
Iterating and converting
A Headers object is iterable. Each entry is a [name, value] pair. Iteration has three properties you should know about:
- Names come out in lowercase, whatever case you used to set them.
- Entries are sorted by name, not kept in insertion order.
- Repeated names are combined into one entry.
Set-Cookieis the exception and is yielded once per value.
const headers = new Headers();
headers.set('X-Trace', 't-1');
headers.append('Accept', 'application/json');
headers.append('Accept', 'text/plain');
for (const [name, value] of headers) {
console.log(`${name}: ${value}`);
}
// accept: application/json, text/plain
// x-trace: t-1
headers.forEach((value, name) => console.log(name, '=>', value));
const plain = Object.fromEntries(headers);
console.log(plain); // { accept: 'application/json, text/plain', 'x-trace': 't-1' }Note the argument order in forEach: value first, then name, the same order as Map.prototype.forEach.
Validation and normalization
The constructor and every mutating method validate their input. Invalid input throws a TypeError at the point you build the headers, not later when the request is sent.
const headers = new Headers();
headers.set('X-Padded', ' value with spaces ');
console.log(JSON.stringify(headers.get('x-padded'))); // "value with spaces"
for (const [name, value] of [
['Bad Name', 'x'], // spaces are not allowed in names
['X-Inject', 'a\r\nEvil: 1'], // CR/LF would inject a new header
['X-Name', 'José✓'] // characters above U+00FF are not valid
]) {
try {
headers.set(name, value);
} catch (err) {
console.log(`${name}: ${err.name}`); // TypeError
}
}Leading and trailing whitespace in values is trimmed. Header values are byte strings, so any character above code point 255 throws. If you need to send non-Latin text, such as a user's display name, encode it first. encodeURIComponent() is the usual choice, and the server then decodes it. Plain é (U+00E9) is technically allowed, but different servers interpret those bytes differently, so encoding is the safer habit.
Guards: when headers cannot be changed
Every Headers object has an internal guard that decides which changes are allowed. You cannot read the guard directly, but you can see what it does.
| Where the object comes from | Guard | Effect |
|---|---|---|
| `new Headers()` | none | Anything valid can be set. |
| `request.headers` / the `headers` option in a browser | request | Forbidden request headers are silently ignored. |
| `response.headers` from `fetch()`, `Response.error()`, `Response.redirect()` | immutable | Any `set`, `append`, or `delete` throws `TypeError`. |
| `new Response(body, { headers })` | response | Mutable, except forbidden response headers such as `Set-Cookie`. |
Response headers from the network are read-only
const redirect = Response.redirect('https://example.com/', 302);
console.log(redirect.headers.get('location')); // 'https://example.com/'
try {
redirect.headers.set('X-Debug', '1');
} catch (err) {
console.log(err.name); // 'TypeError'
}
const editable = new Headers(redirect.headers); // copy to modify
editable.set('X-Debug', '1');
console.log(editable.get('x-debug')); // '1'A response returned by fetch() behaves the same as redirect here. To change headers on a response, for example inside a service worker, copy them into a new Headers object and build a new Response.
Forbidden request headers
Browsers reserve some request headers for themselves, including Host, Content-Length, Cookie, Origin, Referer, Connection, and any name starting with Proxy- or Sec-. If you set one of them, the browser does not throw. It drops the header, and the request goes out without it. A standalone new Headers() will appear to hold the value, which makes the problem easy to miss. The network panel shows what was actually sent.
Reading response headers across origins
On a cross-origin response, JavaScript sees only a small safelist of response headers: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, and Pragma. For any other header, get() returns null even though the network panel shows the header arriving. The server has to name the header in Access-Control-Expose-Headers before scripts can read it. This often trips people up with pagination headers such as Link, rate-limit headers, and custom request IDs. The CORS chapter explains the rest of that mechanism.
Gotcha: mixed-case keys in plain objects
Plain objects compare keys case-sensitively. Headers does not. When a plain object is converted, each key is appended, so two spellings of the same header become one combined value:
const defaults = { 'content-type': 'application/json' };
const overrides = { 'Content-Type': 'text/plain' };
const merged = new Headers({ ...defaults, ...overrides });
console.log(merged.get('content-type')); // 'application/json, text/plain'The spread kept both keys, because the object saw them as different keys, and the server received an invalid content type. The fix is to merge through Headers with set, so a later source replaces an earlier one regardless of case:
function mergeHeaders(...sources) {
const result = new Headers();
for (const source of sources) {
// new Headers(undefined) is valid, so missing sources are fine
new Headers(source).forEach((value, name) => result.set(name, value));
}
return result;
}
const headers = mergeHeaders(
{ 'content-type': 'application/json', Accept: 'application/json' },
[['Content-Type', 'text/plain']],
new Headers({ Authorization: 'Bearer TOKEN' })
);
console.log(Object.fromEntries(headers));
// {
// accept: 'application/json',
// authorization: 'Bearer TOKEN',
// 'content-type': 'text/plain'
// }mergeHeaders accepts all three input shapes. It is a good building block for the reusable fetch helper later in this tutorial, where caller headers have to override defaults reliably.
Choosing between a plain object and Headers
| Situation | Prefer |
|---|---|
| A fixed, small set of headers written inline | Plain object |
| Merging defaults with caller-supplied headers | `Headers` with `set` |
| Repeated header names | `Headers` with `append`, or an array of pairs |
| Checking whether a header exists in any case | `Headers.has()` |
| Logging or serializing | `Object.fromEntries(headers)` |
Exercise
A wrapper builds headers with new Headers({ ...defaultHeaders, ...options.headers }). A caller passes options.headers as a Headers instance containing Authorization: Bearer abc. The request goes out with no Authorization header. Why, and how do you fix it?
Show answer
Spreading a Headers instance yields {} because its entries are not own properties, so the caller's headers disappear. Convert each source through the Headers constructor instead, for example with mergeHeaders(defaultHeaders, options.headers), which iterates each source and calls set on the result. Converting first with Object.fromEntries(options.headers) before spreading also works, but it still has the mixed-case problem.
Exercise
What does this code log, and why? const h = new Headers([['X-Tag', 'a'], ['x-tag', 'b']]); h.append('X-TAG', 'c'); console.log(h.get('x-tag'), [...h.keys()]);
Show answer
It logs 'a, b, c' and ['x-tag']. All three names refer to the same case-insensitive header, so the values are combined with ", " in insertion order. Iteration returns one lowercase name per header, with the repeated values merged into one entry.
Exercise
Your browser code calls response.headers.get('X-RateLimit-Remaining') on a response from another origin and gets null, yet the network panel shows the header with the value 42. What is happening, and who has to change something?
Show answer
The header is not on the CORS-safelisted list, so the browser hides it from scripts on cross-origin responses. The server has to add Access-Control-Expose-Headers: X-RateLimit-Remaining to its response. Client code cannot work around this.