From 5b2143fcb7f2e0d55a1cc23c1d4d5bd284dee592 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 27 Oct 2026 22:35:03 -0500 Subject: [PATCH] perf(http): hand plain-string response headers to the fetch Response as a record toWebHeaders copied every response's headers into a Headers object one by one, so set-cookie arrays survive. Deno and Bun build native headers from a record directly, and the JS copy cost 5-8% on every Deno request (bisected to 50010da). A record holding only strings is now returned as it is; anything else still goes through Headers. Signed-off-by: Diego Resendez --- src/http/headers.ts | 8 +++++++- test/http-headers.test.ts | 16 +++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/http/headers.ts b/src/http/headers.ts index 8647e6e..d71c81b 100644 --- a/src/http/headers.ts +++ b/src/http/headers.ts @@ -70,8 +70,14 @@ export function joinListHeaders>(headers: T): * the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie. * `set-cookie` elements are appended one by one, so each reaches the client as its own line; * every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node. + * + * A record of plain strings, which is nearly every response, is returned untouched: Deno and Bun + * build their native headers from a record directly, and filling a `Headers` from JS instead measured + * 5–8% on every Deno request. */ -export function toWebHeaders(headers: Record): Headers { +export function toWebHeaders(headers: Record): Headers | Record { + if (Object.values(headers).every((value) => typeof value === 'string')) return headers as Record; + const out = new Headers(); for (const key of Object.keys(headers)) { diff --git a/test/http-headers.test.ts b/test/http-headers.test.ts index e7a6b51..a7f08e5 100644 --- a/test/http-headers.test.ts +++ b/test/http-headers.test.ts @@ -41,8 +41,22 @@ describe('array header values (D11)', () => { }); }); + it('toWebHeaders returns a record of plain strings untouched', () => { + const record = { 'content-type': 'application/json', vary: 'origin' }; + expect(toWebHeaders(record)).toBe(record); + }); + + it('toWebHeaders drops undefined values', () => { + const h = toWebHeaders({ 'content-type': 'text/plain', 'x-gone': undefined }) as Headers; + expect(h.has('x-gone')).toBe(false); + expect(h.get('content-type')).toBe('text/plain'); + }); + it('toWebHeaders appends one set-cookie per element', () => { - const h = toWebHeaders({ 'set-cookie': ['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2'], 'x-list': ['a', 'b'] }); + const h = toWebHeaders({ + 'set-cookie': ['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2'], + 'x-list': ['a', 'b'], + }) as Headers; expect(h.getSetCookie()).toEqual(['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2']); expect(h.get('x-list')).toBe('a, b'); });