skip to content

In Cloudflare Workers, why does calling headers.set() on a Response returned by fetch() throw, and how do you change its headers?

level: juniorimportance: must knowfreq 60%

answer

  1. a guard on received messages
  2. copy instead of mutate
  3. the constructor's init argument
  4. hand the body stream over unread

basics

~20 s

A Response returned by fetch(), like the incoming Request, has immutable headers, so set() throws a TypeError. Build a copy with new Response(upstream.body, upstream), which keeps status and headers and streams the body unread, then edit the copy.

solid answer

~40 s

In Workers the incoming `request` and every `Response` that `fetch()` returns are immutable: `headers.set()`, `append()` or `delete()` on them throws `TypeError: Can't modify immutable headers.` The fix is to copy rather than mutate. `new Response(upstream.body, upstream)` uses the original as the init, so status, status text and headers carry over, and it takes the body stream without reading it, so nothing is buffered. The copy's headers are yours to edit. For a request, `new Request(url, request)` does the same. Objects you build with a constructor, such as `new Response("ok")`, and the result of `HTMLRewriter.transform()` are mutable from the start. One trap: `upstream.clone()` is still immutable, and copying after you have read the body fails because the stream is already disturbed.

code

javascript · 13 lines
javascript
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const upstream = await fetch(`https://legacy.example.com${url.pathname}${url.search}`);

    // upstream.headers.set(...) here would throw:
    // TypeError: Can't modify immutable headers.
    const response = new Response(upstream.body, upstream);
    response.headers.set("Cache-Control", "private, no-store");
    response.headers.delete("X-Powered-By");
    return response;
  },
};

go deeper

for a junior

Remember that the incoming request and fetched responses are read-only, the exact TypeError they throw, and the new Response(upstream.body, upstream) idiom that gives you an editable copy.

for a middle

Explain why the copy is cheap: it reuses the body stream, so nothing is buffered, and show that it must happen before any read of the body.

for a senior

Show the production traps around the copy: clone() keeps the guard and may buffer, Content-Length is computed by the runtime, and Set-Cookie needs append() and getAll().

for a principal

Frame immutability as a design choice: a received message stays a record of what crossed the wire, and every change becomes an explicit new message that review can see.

## The rule A Cloudflare Worker sits between a client and an origin, so most of what it handles are **messages it received** rather than messages it built: the `request` argument of the `fetch` handler, and the `Response` objects that its own `fetch()` subrequests return. The Workers runtime treats both as **immutable**. Their `headers` object rejects changes, and an attempt such as `upstream.headers.set("Cache-Control", "no-store")` throws: ```plaintext TypeError: Can't modify immutable headers. ``` This follows the Fetch standard's notion of a headers *guard*: headers attached to a message that came off the network are read-only, as are those of a few factory-made responses such as `Response.redirect()`, while headers of a message you build with a constructor are not. The point is that the object you were handed describes what actually crossed the wire. If you want to send something different, you build a new message and say so in code. | Object | Headers editable? | |---|---| | `request` passed to the `fetch` handler | No | | `Response` returned by `fetch()` | No | | `upstream.clone()` of that response | No, the clone keeps the guard | | `Response.redirect(url, status)` | No, it is created with immutable headers | | `new Response(body, init)` you construct | Yes | | `new Request(url, request)` you construct | Yes | | The `Response` returned by `HTMLRewriter.transform()` | Yes | ## The copy pattern The idiom is `new Response(upstream.body, upstream)`. The second argument is normally a `ResponseInit` object, and passing the original response there copies its `status`, `statusText` and `headers`. The first argument is the body **stream** itself, not its contents, so the runtime never reads the bytes into memory; it simply hands the same stream to the new object. The result has a fresh, editable `Headers` object: 1. Fetch from the origin. 2. Wrap: `const response = new Response(upstream.body, upstream);` 3. Edit `response.headers` with `set()`, `append()` or `delete()`. 4. Return the copy. Requests work the same way: `new Request(url, request)` makes an editable request with a new URL and the old method, headers and body, and `new Request(request, { headers })` swaps in a new header set. ## Traps around the copy - **Copy before you read.** Request and response bodies are one-use streams. If code calls `await upstream.text()` and then `new Response(upstream.body, upstream)`, the constructor throws because the stream is disturbed. Either copy first or build the new response from the text you already read. - **`clone()` is not a way out.** A clone of a fetched response is guarded too, and it also splits the body into two branches that the runtime may have to buffer. - **`Content-Length` is not yours to set.** The runtime computes it from the body source and ignores a value set by hand; a fixed-length body (a string, a typed array or a `FixedLengthStream`) gets a length, any other stream goes out chunked. - **Several values join with commas.** `headers.get()` returns one comma-separated string, so Workers keeps the non-standard `headers.getAll("Set-Cookie")` for cookies, and `append("Set-Cookie", ...)` adds a second header rather than folding the value in. `getAll()` throws for any other header name. - **`Response.redirect()` is guarded too.** To add a cookie or a cache header to a redirect, build it yourself: `new Response(null, { status: 302, headers: { Location: target } })`. - **Properties are read-only too.** `request.url`, `request.method` and the other properties of the incoming request cannot be assigned; construct a new `Request` to send a different URL or method. ## Why it matters in practice A Worker in front of a legacy origin typically strips headers that leak implementation details (`X-Powered-By`), adds security headers, rewrites `Cache-Control`, or sets cookies. All of those need the copy. Because the copy reuses the body stream, it costs almost nothing, and the response still streams to the client as the origin produces it, which is exactly what you want for large pages and downloads. The immutable guard therefore never forces buffering; it only forces you to make the new message explicit. ## Reading the example The code below fetches the same path from the legacy origin, then wraps the result. The comment marks the line that would fail if the Worker edited `upstream` directly. After the wrap, `set()` replaces whatever caching policy the origin sent with `private, no-store`, and `delete()` removes the `X-Powered-By` header that advertises the origin's software. Status, the remaining headers and the streaming body are exactly what the origin produced, and the client starts receiving bytes as soon as the origin sends them. The same three lines, fetch, wrap and edit, are the core of almost every header-rewriting Worker.

  • Does new Response(upstream.body, upstream) read or buffer the origin's body?
    No. It passes the `ReadableStream` itself to the new object, so bytes flow from the origin to the client as they arrive. The only cost is a new `Headers` object. Buffering starts only when code reads the body with `text()`, `json()` or `arrayBuffer()`, and after such a read the stream is disturbed, so the copy must be built before reading.
  • Why does setting Content-Length on the copy have no effect?
    The runtime sets `Content-Length` from the body source and ignores a value set by hand. A string or typed-array body gets its real length; a generic stream is sent with chunked encoding. To declare a length for a stream, write it through a `FixedLengthStream` of that exact size, which errors if too many or too few bytes pass.
  • How do you add two cookies to the copied response?
    Call `response.headers.append("Set-Cookie", ...)` once per cookie. In Workers, `append()` on `Set-Cookie` adds a separate header instead of joining values with a comma, because cookie dates contain commas. Read them back with the non-standard `headers.getAll("Set-Cookie")`, which throws a `TypeError` for any other header name.

  • Headers of a Response from fetch() can be edited in place with set().
  • Copying with new Response(res.body, res) buffers the whole body in memory.
  • res.clone() returns a response whose headers can be edited.
  • Setting Content-Length by hand overrides the length the runtime sends.
  • headers.get() returns an array when a header has several values.