Sub topic 7
Working with the Headers Interface
This chapter assumes you know how to call fetch(), how to pass an options object with method, headers, and body, and how to read response.status and response.ok. In earlier chapters you passed headers as a plain object. Here you will use the Headers interface, the object the browser actually uses to store request and response headers.
Why a dedicated Headers object
HTTP header names are case-insensitive, a header can appear more than once, and some headers are controlled by the browser rather than by your code. A plain object handles none of these rules. Headers does: it normalizes names, merges repeated values, and refuses changes it is not allowed to make.
You can create one in three ways, and fetch accepts all three wherever it expects headers:
const fromObject = new Headers({ Accept: 'application/json' });
const fromPairs = new Headers([
['Accept', 'application/json'],
['X-Request-Id', 'abc123']
]);
const copy = new Headers(fromPairs); // copies another Headers instance
console.log(fromObject.get('accept')); // 'application/json'
console.log(copy.get('x-request-id')); // 'abc123'The array-of-pairs form is useful when you need the same header name twice, because an object literal cannot hold duplicate keys.
The core methods
| Method | What it does |
|---|---|
| `append(name, value)` | Adds a value, keeping any existing values for that name |
| `set(name, value)` | Replaces all existing values for that name |
| `get(name)` | Returns the value, multiple values joined by `", "`, or `null` |
| `has(name)` | Returns `true` if the header exists |
| `delete(name)` | Removes the header entirely |
| `entries()`, `keys()`, `values()`, `forEach()` | Iterate over the headers |
The difference between append and set is where most mistakes happen:
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', 'application/xml');
console.log(headers.get('Accept')); // 'application/xml'
headers.set('Authorization', 'Bearer TOKEN');
console.log(headers.has('authorization')); // true: names are case-insensitive
headers.delete('AUTHORIZATION');
console.log(headers.get('Authorization')); // null
for (const [name, value] of headers) {
console.log(name, value); // 'accept application/xml'
}When you iterate, names come out in lowercase and sorted alphabetically. Don't expect your original casing or insertion order.
Reading response headers
response.headers is a Headers object, so you read it with the same methods:
const response = await fetch('https://api.example.com/items');
const type = response.headers.get('content-type');
if (type?.includes('application/json')) {
const items = await response.json();
console.log(items);
}
for (const [name, value] of response.headers) {
console.log(`${name}: ${value}`);
}Response headers are read-only. Calling response.headers.set(...) throws a TypeError, because the browser gives these headers an immutable guard.
Common errors
Other common surprises:
- Missing response headers on cross-origin requests. By default JavaScript can read only a small safelist:
Cache-Control,Content-Language,Content-Length,Content-Type,Expires,Last-Modified, andPragma. For any other header,get()returnsnullunless the server lists it inAccess-Control-Expose-Headers. The CORS chapter covers this in more detail. - Invalid names or values. A name containing a space or colon, such as
new Headers({ 'My Header': 'x' }), throws aTypeErrorimmediately. Set-Cookieandget(). Merging with commas breaks cookie values, which can contain commas themselves. Where the server is allowed to expose them (mainly in Node.js and other server runtimes), useheaders.getSetCookie(), which returns an array.
Exercise
You run const h = new Headers(); h.append('X-Tag', 'a'); h.set('x-tag', 'b'); h.append('X-TAG', 'c');. What does h.get('X-Tag') return, and why?
Show answer
It returns 'b, c'. Header names are case-insensitive, so all three calls work on the same header. set replaces 'a' with 'b', and append then adds 'c', so get returns both values joined by ", ".
Exercise
A cross-origin API sends a custom header named X-Total-Count, but response.headers.get('X-Total-Count') returns null. The header is visible in the network panel. What is wrong, and who has to fix it?
Show answer
The header is not on the CORS safelist, so the browser hides it from JavaScript. The server must add Access-Control-Expose-Headers: X-Total-Count to its response. Client code cannot change this.