Skip to content

Commit

Permalink
fix: clone Headers before mutating them during prerendering (#10030)
Browse files Browse the repository at this point in the history
* clone request and headers before setting x-sveltekit-prerender

* add changeset

* add test
  • Loading branch information
Conduitry authored May 25, 2023
1 parent 4aa976e commit c1d3458
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/curly-onions-compare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: gracefully handle server endpoints that return `Response`s with immutable `Headers` when prerendering
9 changes: 8 additions & 1 deletion packages/kit/src/runtime/server/endpoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function render_endpoint(event, mod, state) {
}

try {
const response = await handler(
let response = await handler(
/** @type {import('@sveltejs/kit').RequestEvent<Record<string, any>>} */ (event)
);

Expand All @@ -50,6 +50,13 @@ export async function render_endpoint(event, mod, state) {
}

if (state.prerendering) {
// the returned Response might have immutable Headers
// so we should clone them before trying to mutate them
response = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: new Headers(response.headers)
});
response.headers.set('x-sveltekit-prerender', String(prerender));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const prerender = true;

export const GET = () => {
const response = new Response('foo');
// this simulates immutable Response Headers, like those returned by undici
Object.defineProperty(response.headers, 'set', { value: null });
return response;
};
5 changes: 5 additions & 0 deletions packages/kit/test/prerendering/basics/test/tests.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,8 @@ test('prerendered.paths omits trailing slashes for endpoints', () => {
expect(content, `Missing ${path}`).toMatch(`"${path}"`);
}
});

test('prerenders responses with immutable Headers', () => {
const content = read('immutable-headers');
expect(content).toMatch('foo');
});

0 comments on commit c1d3458

Please sign in to comment.