Skip to content

Commit 5001721

Browse files
committed
fix: handle immutable headers returned by native fetch in middleware
GitOrigin-RevId: 5b52f855d2a996eb1c568229de675f8b67f2cb2a
1 parent 471d705 commit 5001721

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

packages/nextjs/src/middleware/middleware.test.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,15 @@ const createMockRequest = (
4343
}
4444

4545
const mockFetch = (responseInit: Partial<Response>) => {
46-
global.fetch = jest.fn().mockResolvedValue(
47-
new Response(responseInit.body || "", {
48-
headers: new Headers(responseInit.headers || {}),
49-
status: responseInit.status || 200,
50-
}),
51-
)
46+
const response = new Response(responseInit.body || "", {
47+
headers: new Headers(responseInit.headers || {}),
48+
status: responseInit.status || 200,
49+
})
50+
// simulate immutable headers like those returned by undici's fetch
51+
Object.defineProperty(response.headers, "append", { value: null })
52+
Object.defineProperty(response.headers, "set", { value: null })
53+
Object.defineProperty(response.headers, "delete", { value: null })
54+
global.fetch = jest.fn().mockResolvedValue(response)
5255
}
5356

5457
const createOptions = (): OryMiddlewareOptions => ({

packages/nextjs/src/middleware/middleware.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ export async function proxyRequest(
8484
upstreamRequestHeaders.set("Ory-No-Custom-Domain-Redirect", "true")
8585

8686
// Fetch the upstream response
87-
const upstreamResponse = await fetch(upstreamUrl.toString(), {
87+
let upstreamResponse = await fetch(upstreamUrl.toString(), {
8888
method: request.method,
8989
headers: upstreamRequestHeaders,
9090
body:
@@ -93,6 +93,12 @@ export async function proxyRequest(
9393
: null,
9494
redirect: "manual",
9595
})
96+
upstreamResponse = new Response(upstreamResponse.body, {
97+
status: upstreamResponse.status,
98+
statusText: upstreamResponse.statusText,
99+
// response may have immutable headers
100+
headers: new Headers(upstreamResponse.headers),
101+
})
96102

97103
// Delete headers that should not be forwarded
98104
defaultOmitHeaders.forEach((header) => {

0 commit comments

Comments
 (0)