diff --git a/src/utils/internal/proxy.ts b/src/utils/internal/proxy.ts index 0ba530a3..caa71e80 100644 --- a/src/utils/internal/proxy.ts +++ b/src/utils/internal/proxy.ts @@ -49,14 +49,17 @@ export function rewriteCookieProperty( export function mergeHeaders( defaults: HeadersInit, ...inputs: (HeadersInit | RequestHeaders | undefined)[] -) { +): HeadersInit | Headers { const _inputs = inputs.filter(Boolean) as HeadersInit[]; if (_inputs.length === 0) { return defaults; } + const merged = new Headers(defaults); for (const input of _inputs) { - for (const [key, value] of Object.entries(input!)) { + const entries = + input instanceof Headers ? input.entries() : Object.entries(input!); + for (const [key, value] of entries) { if (value !== undefined) { merged.set(key, value); } diff --git a/test/proxy.test.ts b/test/proxy.test.ts index 341675e6..e91851cc 100644 --- a/test/proxy.test.ts +++ b/test/proxy.test.ts @@ -3,6 +3,7 @@ import { vi, beforeEach } from "vitest"; import { setCookie } from "../src"; import { proxy, proxyRequest } from "../src/utils/proxy"; import { describeMatrix } from "./_setup"; +import { mergeHeaders } from "../src/utils/internal/proxy"; describeMatrix("proxy", (t, { it, expect, describe }) => { const spy = vi.spyOn(console, "error"); @@ -187,6 +188,29 @@ describeMatrix("proxy", (t, { it, expect, describe }) => { }, 60 * 1000, ); + + it("can merge input headers into the default", async () => { + t.app.all("/test-headers", async (event) => { + const headers = new Headers(); + + headers.set("Authorization", "Bearer 1234"); + headers.set("X-Domain", "abcd"); + + const mergedHeaders = mergeHeaders(event.request.headers, headers); + + return { + headers: + mergedHeaders instanceof Headers + ? Object.fromEntries(mergedHeaders.entries()) + : Object.entries(mergedHeaders), + }; + }); + + const result = await t.fetch("/test-headers").then((r) => r.json()); + + expect(result.headers["authorization"]).toEqual("Bearer 1234"); + expect(result.headers["x-domain"]).toEqual("abcd"); + }); }); describe("multipleCookies", () => {