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 <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-27 22:35:03 -05:00
1 parent 9648a9d1ed
commit 5b2143fcb7
2 files changed
+22 -2

No files matched your search

+7 -1
View File
@@ -70,8 +70,14 @@ export function joinListHeaders<T extends Record<string, unknown>>(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<string, unknown>): Headers {
export function toWebHeaders(headers: Record<string, unknown>): Headers | Record<string, string> {
if (Object.values(headers).every((value) => typeof value === 'string')) return headers as Record<string, string>;
const out = new Headers();
for (const key of Object.keys(headers)) {
+15 -1
View File
@@ -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');
});