JavaScript Reference ยท Browser and Web APIs
The Headers interface
Reference for the Headers class: create it, append and set values, read case-insensitively, iterate entries, handle Set-Cookie and read-only guards.
Headers is a small map-like object for HTTP header fields. You meet it as response.headers after a fetch() and as the headers option when you send one. Names are case-insensitive, values are strings, and a name can hold several values that are joined with commas when you read them.
You can build one from an object, an array of pairs, or another Headers. Iterating always yields lowercase names, sorted alphabetically, which makes output predictable.
const headers = new Headers({ Accept: "application/json" }); headers.set("X-Token", "abc");
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
new Headers() new Headers(init) // object, array of [name, value] pairs, or Headers
| Method | Description |
|---|---|
append(name, value) |
Adds a value. Existing values for the same name are kept and joined with , . |
set(name, value) |
Replaces every existing value of that name. |
get(name) |
Returns the value as a string (several values joined with , ), or null if absent. |
has(name) |
Returns true if the name exists. |
delete(name) |
Removes the header. Does nothing if absent. |
forEach(callback) |
Calls callback(value, name, headers) for each entry. |
entries(), keys(), values() |
Iterators; the object itself is iterable like entries(). |
getSetCookie() |
Returns an array with each Set-Cookie value separately. |
Exceptions: TypeError if a name or value is not valid HTTP syntax, or if you modify a headers object whose guard is "immutable" (such as response.headers of a fetched response).
Usage notes
- Case does not matter for names, but iteration reports them in lowercase.
get()joins duplicates.Set-Cookieis the exception, because commas appear inside cookie values; usegetSetCookie().set()vsappend(). Useset()for single-value headers likeContent-Type, andappend()for list-like ones such asAccept.- Browsers hide some headers. Scripts cannot set forbidden request headers (
Cookie,Host,Originand others), and for cross-origin responses only CORS-safelisted headers are readable unless the server sendsAccess-Control-Expose-Headers. - Convert easily.
Object.fromEntries(headers)makes an object (repeated names collapse to their joined value), andnew Headers(object)goes back. - Values are trimmed of leading and trailing whitespace, and non-ASCII characters are best avoided.
Authorizationtokens belong in headers, never in URLs, which end up in logs and history.
Browser support
Headers is supported in every current browser and in Node.js. getSetCookie() is newer, so check a compatibility table before relying on it in older browsers.
Related
fetch(),RequestandResponseObject.fromEntries()- Lessons: Fetch, Cookies