diff --git a/src/utils/proxy.ts b/src/utils/proxy.ts index ba5489d2..05762679 100644 --- a/src/utils/proxy.ts +++ b/src/utils/proxy.ts @@ -51,22 +51,20 @@ export async function proxyRequest( } // Headers - const headers = getProxyRequestHeaders(event); - if (opts.fetchOptions?.headers) { - Object.assign(headers, opts.fetchOptions.headers); - } - if (opts.headers) { - Object.assign(headers, opts.headers); - } + const fetchHeaders = mergeHeaders( + getProxyRequestHeaders(event), + opts.fetchOptions?.headers, + opts.headers + ); return sendProxy(event, target, { ...opts, fetchOptions: { - headers, method, body, duplex, ...opts.fetchOptions, + headers: fetchHeaders, }, }); } @@ -222,3 +220,22 @@ function rewriteCookieProperty( } ); } + +function mergeHeaders( + defaults: HeadersInit, + ...inputs: (HeadersInit | RequestHeaders | undefined)[] +) { + 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!)) { + if (value !== undefined) { + merged.set(key, value); + } + } + } + return merged; +} diff --git a/test/proxy.test.ts b/test/proxy.test.ts index d683a984..536694b9 100644 --- a/test/proxy.test.ts +++ b/test/proxy.test.ts @@ -87,7 +87,13 @@ describe("", () => { app.use( "/", eventHandler((event) => { - return proxyRequest(event, url + "/debug", { fetch }); + return proxyRequest(event, url + "/debug", { + fetch, + headers: { "x-custom1": "overriden" }, + fetchOptions: { + headers: { "x-custom2": "overriden" }, + }, + }); }) ); @@ -96,13 +102,19 @@ describe("", () => { body: "hello", headers: { "content-type": "text/custom", - "x-custom": "hello", + "X-Custom1": "user", + "X-Custom2": "user", + "X-Custom3": "user", }, }).then((r) => r.json()); const { headers, ...data } = result; expect(headers["content-type"]).toEqual("text/custom"); - expect(headers["x-custom"]).toEqual("hello"); + + expect(headers["x-custom1"]).toEqual("overriden"); + expect(headers["x-custom2"]).toEqual("overriden"); + expect(headers["x-custom3"]).toEqual("user"); + expect(data).toMatchInlineSnapshot(` { "body": "hello",