Skip to content

Commit 570562b

Browse files
authored
fix: handle empty Headers when serialising Request passed to fetch (#13023)
1 parent 143dbf9 commit 570562b

File tree

5 files changed

+35
-1
lines changed

5 files changed

+35
-1
lines changed

.changeset/honest-hornets-doubt.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/kit': patch
3+
---
4+
5+
fix: prevent duplicate fetch request when using Request with load function's fetch

packages/kit/src/runtime/client/client.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,9 @@ async function load_node({ loader, parent, url, params, route, server_data_node
669669
: await resource.blob(),
670670
cache: resource.cache,
671671
credentials: resource.credentials,
672-
headers: resource.headers,
672+
// the headers are undefined on the server if the Headers object is empty
673+
// so we need to make sure they are also undefined here if there are no headers
674+
headers: [...resource.headers].length ? resource.headers : undefined,
673675
integrity: resource.integrity,
674676
keepalive: resource.keepalive,
675677
method: resource.method,
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/** @type {import('@sveltejs/kit').Load} */
2+
export async function load({ url, fetch }) {
3+
const res = await fetch(new Request(url.origin + '/load/fetch-request.json'));
4+
const { answer } = await res.json();
5+
return { answer };
6+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<script>
2+
/** @type {import('./$types').PageData} */
3+
export let data;
4+
</script>
5+
6+
<h1>the answer is {data.answer}</h1>

packages/kit/test/apps/basics/test/client.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,21 @@ test.describe('Load', () => {
252252
expect(logs).toContain('Called a patched window.fetch');
253253
});
254254

255+
test('does not repeat fetch on hydration when using Request object', async ({ page }) => {
256+
const requests = [];
257+
page.on('request', (request) => {
258+
if (request.url().includes('/load/fetch-request.json')) {
259+
requests.push(request);
260+
}
261+
});
262+
263+
await page.goto('/load/fetch-request-empty-headers');
264+
265+
console.log({ requests });
266+
267+
expect(requests).toEqual([]);
268+
});
269+
255270
if (process.env.DEV) {
256271
test('using window.fetch causes a warning', async ({ page, baseURL }) => {
257272
await Promise.all([

0 commit comments

Comments
 (0)