Skip to content

Commit 8f8f95b

Browse files
committed
docs(node): document that mutating response headers preserves the raw body
1 parent 37ce4ce commit 8f8f95b

3 files changed

Lines changed: 85 additions & 0 deletions

File tree

‎docs/1.guide/04.middleware.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ serve({
3737
});
3838
```
3939

40+
## Modifying a response
41+
42+
A middleware that decorates a response — a `Set-Cookie`, a CORS or cache header — should mutate `res.headers` in place, as `xPoweredBy` does above. Rebuilding the response around its body (`new Response(res.body, { ... })`) reads `res.body`, which on Node.js discards the [`FastResponse`](/guide/node#fastresponse) fast path and costs roughly 2x the throughput on a small response.
43+
44+
Response headers are mutable on every runtime srvx supports, so this works regardless of which class the handler returned. The exception is a response from `fetch()`, `Response.error()` or `Response.redirect()`, whose headers the Fetch standard marks immutable — rebuild those instead.
45+
4046
## Order of execution
4147

4248
Middleware run in the order they appear in the `middleware` array, each wrapping the next, with your `fetch` handler at the center. A middleware that returns a response **without** calling `next()` short-circuits the rest of the chain — nothing after it runs.

‎docs/1.guide/08.node.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,32 @@ console.log(`Server running at ${server.url}`);
118118

119119
You can locally run benchmarks by cloning [srvx repository](https://github.com/h3js/srvx) and running `npm run bench:node [--all]` script. Speedup in v22.8.0 was roughly **%94**!
120120

121+
### Adding headers to a response
122+
123+
`FastResponse` keeps the body you passed in exactly as you passed it — a string stays a string all the way to `res.write()`, and its `Content-Type` and `Content-Length` are derived from it at send time. Reading `response.body` gives up that fast path: it forces the full [Response][Response] internals to be built and turns the body into a [ReadableStream][ReadableStream].
124+
125+
So to add a header — a `Set-Cookie`, a CORS or cache header, anything a middleware wants to attach to a response it did not create — **mutate `response.headers` in place** rather than rebuilding the response around its body:
126+
127+
```ts
128+
// ✅ Fast: the body is never touched
129+
res.headers.append("set-cookie", "session=abc; HttpOnly");
130+
res.headers.set("cache-control", "no-store");
131+
return res;
132+
133+
// ❌ Slow: reading `res.body` materializes the response
134+
return new FastResponse(res.body, {
135+
status: res.status,
136+
headers: { ...Object.fromEntries(res.headers), "set-cookie": "session=abc; HttpOnly" },
137+
});
138+
```
139+
140+
Rebuilding costs roughly **2x** the throughput of mutating on a small response, because the raw body is replaced by a stream that has to be pumped chunk by chunk instead of written once with a known length.
141+
142+
`response.headers` on a `FastResponse` is mutable, whether or not the body has already been materialized, and mutations are guaranteed to reach the wire. This also holds for a plain `new Response()` on Node.js, Deno and Bun, so a middleware can mutate without knowing which class it was handed. The exceptions are responses whose headers the [Fetch standard](https://fetch.spec.whatwg.org/#concept-headers-guard) marks immutable — those returned by `fetch()`, `Response.error()` and `Response.redirect()`. For those, rebuilding is the only option, and it costs nothing: their bodies are already streams.
143+
144+
> [!NOTE]
145+
> A `FastResponse` may only be sent once. Its body and headers are released as it is written to the socket, so a cached instance replayed across requests sends an empty body the second time. Build a new response per request, or cache the body and construct around it.
146+
121147
## Fetching Node.js Handlers
122148

123149
srvx server converts a [fetch][fetch]-like [Request][Request] => [Response][Response] handler to [node:IncomingMessage][IncomingMessage] => [node:ServerResponse][ServerResponse] handler that is compatible with Node.js built-in server.

‎test/node-adapters.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -914,6 +914,59 @@ describe("FastResponse copies init Headers", () => {
914914
});
915915
});
916916

917+
// Documented in docs/1.guide/08.node.md#adding-headers-to-a-response: a middleware
918+
// decorating a response must be able to mutate `res.headers` without paying for
919+
// materialization. Frameworks build on this instead of `new FastResponse(res.body, ...)`,
920+
// which is ~2x slower because it replaces the raw body with a ReadableStream.
921+
describe("FastResponse header mutation preserves the raw body", () => {
922+
test("mutating headers keeps a string body raw", () => {
923+
const res = new FastResponse("hello world", { headers: { "x-a": "1" } });
924+
res.headers.append("set-cookie", "session=abc");
925+
926+
const prepared = res._toNodeResponse();
927+
928+
expect(prepared.body).toBe("hello world");
929+
expect(prepared.headers).toContain("session=abc");
930+
// Implicit content-type/length are still derived from the raw body.
931+
expect(prepared.headers).toContain("text/plain; charset=UTF-8");
932+
expect(prepared.headers).toContain("11");
933+
});
934+
935+
test("mutating headers keeps a Uint8Array body raw", () => {
936+
const body = new TextEncoder().encode("hello world");
937+
const res = new FastResponse(body);
938+
res.headers.set("x-a", "1");
939+
940+
expect(res._toNodeResponse().body).toBe(body);
941+
});
942+
943+
test("reading .body is what forfeits the fast path", () => {
944+
const res = new FastResponse("hello world");
945+
void res.body;
946+
947+
expect(res._toNodeResponse().body).toBeInstanceOf(ReadableStream);
948+
});
949+
950+
test("headers stay mutable after materialization", () => {
951+
const res = new FastResponse("hello world");
952+
void res.body; // materialize
953+
954+
expect(() => res.headers.append("set-cookie", "session=abc")).not.toThrow();
955+
expect(res._toNodeResponse().headers).toContain("session=abc");
956+
});
957+
958+
test("a plain Response is mutable too, so middleware need not branch", () => {
959+
// Only fetch()/Response.error()/Response.redirect() results are immutable.
960+
const res = new Response("hello world");
961+
962+
expect(() => {
963+
res.headers.set("cache-control", "no-store");
964+
res.headers.append("set-cookie", "session=abc");
965+
}).not.toThrow();
966+
expect(res.headers.getSetCookie()).toEqual(["session=abc"]);
967+
});
968+
});
969+
917970
// v1 stabilization: Node-adapter crash/corruption regressions.
918971
describe("node body crash regressions", () => {
919972
// F1: the non-middleware branch of callNodeHandler had no `.catch`, so an async

0 commit comments

Comments
 (0)