Headers.append Combines Duplicate Values

Headers.append joins repeated values with a comma while set replaces them, and getSetCookie returns Set-Cookie entries individually because joining corrupts.

JavascriptData Fetching

Code

javascriptsnippet
21 lines
// Headers.append joins repeated values; set replaces them wholesale.
const headers = new Headers({ accept: 'application/json' });
headers.append('x-trace-id', 'trace-a');
headers.append('x-trace-id', 'trace-b');
console.log('append joins:', JSON.stringify(headers.get('x-trace-id')));

headers.set('x-trace-id', 'trace-c');
console.log('set replaces:', JSON.stringify(headers.get('x-trace-id')));

// Iteration yields one combined entry per header name
console.log('entries:', JSON.stringify([...headers.entries()]));

// Set-Cookie must never be joined, so getSetCookie exposes the real list
const response = new Response();
response.headers.append('set-cookie', 'session=abc');
response.headers.append('set-cookie', 'theme=dark');
console.log('set-cookie get:', JSON.stringify(response.headers.get('set-cookie')));
console.log('set-cookie list:', JSON.stringify(response.headers.getSetCookie()));

// has() reports presence without reading the value
console.log('has accept:', headers.has('accept'), '| has x-missing:', headers.has('x-missing'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

append joins: "trace-a, trace-b"
set replaces: "trace-c"
entries: [["accept","application/json"],["x-trace-id","trace-c"]]
set-cookie get: "session=abc, theme=dark"
set-cookie list: ["session=abc","theme=dark"]
has accept: true | has x-missing: false

How the snippet works

Everything operates on top-level bindings: headers, response.

Watch out for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Applying it

The run emits 6 labeled sections — append joins:, set replaces:, entries:, set-cookie get:, set-cookie list:, has accept: — one per step.

Statements that carry the weight

const headers = new Headers({ accept: 'application/json' });
response.headers.append('set-cookie', 'session=abc');
response.headers.append('set-cookie', 'theme=dark');

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `headers`, `response`.