❯ehsan.blog
~/blog/spreading-a-headers-object-gives-you-an-empty-object — zsh
❯cat spreading-a-headers-object-gives-you-an-empty-object.md

Spreading a Headers object gives you an empty object

·7 min read

Spreading a Headers object gives you an empty object — article card for a post by Ehsan Shahid

Here is a function that appears in almost every fetch wrapper ever written. It takes whatever headers the caller passed, adds an auth token, and hands the result to fetch.

js
const withAuth = (headers) => ({ ...headers, Authorization: 'Bearer t' })

It works. It has worked for months. Then one day your tracing stops working for some requests and not others, and nothing in your logs says why.

The reason is that headers is not always the same kind of thing. When it is a plain object, that line is correct. When it is a Headers object, that line throws away every header the caller gave you — quietly, with no error, no warning, and a 200 OK at the end.

The one line that proves it

js
const h = new Headers({ 'X-Trace': 'abc' })

console.log({ ...h })        // {}
console.log(Object.keys(h))  // []

Not “mostly empty”. Empty. The spread operator found nothing to copy.

Why it is empty

This part is simpler than it sounds, so stay with me.

When you write const user = { name: 'Sam' }, the name really is inside that object. You can point at it. The spread operator copies things like that — it walks the object’s own properties and copies each one.

A Headers object does not store your headers that way. There is no X-Trace property sitting on it. The headers live in private internal storage, and the only way in or out is through the methods: get, set, has, append, entries.

So when the spread operator looks for properties to copy, it looks at the object and finds… nothing. No properties. It copies all zero of them and returns an empty object. It is not broken. It did exactly what it was told. It was told to copy properties, and there were none.

flowchart LR
  A["plain object<br/>X-Trace lives on the object"] -->|spread| B["copy keeps X-Trace"]
  C["Headers object<br/>X-Trace lives in private storage"] -->|spread| D["copy is empty"]
  D --> E["Authorization added after<br/>so the result is not empty<br/>it just lost everything else"]

That last box is why this bug survives code review. The result is not empty. It has your Authorization in it, because you added that one yourself, after the spread. So it looks like a working headers object. It is a working headers object. It is just missing everything that was there before.

Watching a real request lose a header

Talk is cheap, so here is the whole thing against a real HTTP server, printing what actually arrived on the other side.

js
const http = require('http')

const seen = []
const server = http.createServer((req, res) => {
  seen.push({ trace: req.headers['x-trace'] ?? null, auth: req.headers['authorization'] ?? null })
  res.writeHead(200, { 'content-type': 'application/json' })
  res.end('{"ok":true}')
})

await new Promise(r => server.listen(0, r))
const url = `http://127.0.0.1:${server.address().port}/`

// the hook every wrapper has
const withAuth = (headers) => ({ ...headers, Authorization: 'Bearer t' })

// caller A passes a plain object
const a = await fetch(url, { headers: withAuth({ 'X-Trace': 'abc' }) })

// caller B passes a Headers object - same hook, same code path
const b = await fetch(url, { headers: withAuth(new Headers({ 'X-Trace': 'abc' })) })

console.log('plain object caller :', seen[0])
console.log('Headers caller      :', seen[1])
console.log('both responses ok   :', a.ok, b.ok)

What the server actually received, on Node v24.3.0:

text
plain object caller : { trace: 'abc', auth: 'Bearer t' }
Headers caller      : { trace: null,  auth: 'Bearer t' }
both responses ok   : true true

Read the second line again. The trace header is gone. The auth header is fine. Both requests returned 200 OK. fetch did not complain, because from its point of view nothing is wrong — you handed it an object with one header in it, and it faithfully sent one header.

Nobody gets an error. You find out weeks later, when someone asks why half the requests have no trace ID.

The part that genuinely caught me out

I tried to debug this the obvious way. I printed the headers.

js
const h = new Headers({ 'X-Trace': 'abc' })
console.log(JSON.stringify(h))

In Node, that prints:

text
{"x-trace":"abc"}

There it is. The header is clearly there. So the spread must be fine, right?

No. Those are two different questions, and they have two different answers. Node’s Headers has an extra toJSON method that JSON.stringify calls to produce that nice output. The spread operator does not call toJSON. It only copies properties, and there are still none.

So JSON.stringify shows you the headers, and the spread drops them, in the same program, on the same object. Your debug line tells you everything is fine while the bug is happening right next to it.

And it gets one step stranger. That toJSON is a Node convenience, not part of the standard. I ran the same code in Chrome:

text
Node     JSON.stringify(h)  ->  {"x-trace":"abc"}     typeof h.toJSON -> function
Chrome   JSON.stringify(h)  ->  {}                    typeof h.toJSON -> undefined

Same object, same method, two different answers depending on where it runs. If you log headers to debug this in the browser you see an empty object and reasonably conclude the headers were never set at all — which sends you looking in completely the wrong place.

The one thing both runtimes agree on is the spread: empty, everywhere.

The fix is one constructor

Stop merging headers by hand. Let the Headers constructor do it, because it already knows how to read all three shapes people pass around.

js
const withAuth = (init) => {
  const h = new Headers(init)      // accepts Headers, plain object, or array of pairs
  h.set('Authorization', 'Bearer t')
  return h
}

Two lines. Same three callers, against the same real server:

text
fixed, Headers in : { trace: 'abc', auth: 'Bearer t' }
fixed, object in  : { trace: 'abc', auth: 'Bearer t' }
fixed, array in   : { trace: 'abc', auth: 'Bearer t' }

All three work, because new Headers(init) reads the input through the proper door instead of trying to copy properties that were never there. fetch accepts a Headers object directly, so you can return it as-is.

The rule worth remembering: to merge headers, build a Headers. Never spread one.

One trap in the obvious alternative

You may have spotted another way to turn a Headers into a plain object:

js
Object.fromEntries(h)   // { 'x-trace': 'abc' }

That does work, and for request headers you build yourself it is fine. But it quietly breaks on response headers, and this is worth knowing before you reach for it.

A plain object cannot hold the same key twice, and Set-Cookie is the one header servers legitimately send more than once. So the second cookie overwrites the first:

js
const h = new Headers()
h.append('Set-Cookie', 'a=1')
h.append('Set-Cookie', 'b=2')

h.getSetCookie()                                 // ['a=1', 'b=2']
Object.fromEntries(h)                            // { 'set-cookie': 'b=2' }
new Headers(Object.fromEntries(h)).getSetCookie() // ['b=2']   <- a=1 is gone

new Headers(h).getSetCookie()                    // ['a=1', 'b=2']  <- intact

Round-tripping a response through Object.fromEntries eats a cookie. The Headers constructor keeps both. That is one more reason to make new Headers(init) the habit: it is the only option here that is correct in every case.

(For reading a single cookie out, use h.getSetCookie(), which returns the proper array.)

How to check your own code in ten seconds

Search your project for a spread immediately followed by a header name:

bash
grep -rn '\.\.\..*[Hh]eaders' src/

Every hit is a place to look at. Ask one question: can the thing being spread ever be a Headers object? If the answer is yes, or even maybe, it is already dropping headers for some callers.

The riskiest spots, in my experience:

  • auth or tracing hooks in a fetch wrapper, where callers pass whatever they like
  • middleware that forwards an incoming request’s headers to another service
  • retry logic that rebuilds the request options from the previous attempt
  • anything copying response.headers into a log line

The short version

  • { ...headers } on a Headers object gives you an empty object, in Node and in the browser.
  • The headers are not properties, so the spread finds nothing to copy. No error is thrown.
  • Anything you add after the spread survives, so the result looks healthy and ships.
  • In Node, JSON.stringify prints the headers anyway, so your debug line lies to you. In Chrome it prints an empty object, so it lies to you differently.
  • Use new Headers(init) and then set. It reads every shape correctly and is the only approach that keeps repeated Set-Cookie values intact.

Every output above came from running the code, not from memory: Node v24.3.0 for the server test, Chrome for the browser comparison.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.