Skip to content

Commit

Permalink
fix: correctly serialize request url when using load fetch (#8876)
Browse files Browse the repository at this point in the history
fixes #8852

Slices the origin from any client fetch request URLs so that they're always similar in format to fetches done on the server, which is important to find cached responses

---------

Co-authored-by: Simon H <[email protected]>
  • Loading branch information
eltigerchino and dummdidumm authored Feb 3, 2023
1 parent e56a13c commit 2ef9b7d
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/silent-icons-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: correctly serialize request url when using load `fetch`
11 changes: 8 additions & 3 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -594,12 +594,17 @@ export function create_client({ target }) {
}

// we must fixup relative urls so they are resolved from the target page
const resolved = new URL(requested, url).href;
depends(resolved);
const resolved = new URL(requested, url);
depends(resolved.href);

// match ssr serialized data url, which is important to find cached responses
if (resolved.origin === url.origin) {
requested = resolved.href.slice(url.origin.length);
}

// prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be resolved
return started
? subsequent_fetch(requested, resolved, init)
? subsequent_fetch(requested, resolved.href, init)
: initial_fetch(requested, init);
},
setHeaders: () => {}, // noop
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/** @type {import('./$types').PageLoad} */
export async function load({ fetch, data }) {
export async function load({ fetch, data, url }) {
const { a } = data;

const res = await fetch('/load/serialization/fetched-from-shared.json');
const res = await fetch(new URL('/load/serialization/fetched-from-shared.json', url.origin));
const { b } = await res.json();

return { a, b, c: a + b };
Expand Down
4 changes: 3 additions & 1 deletion packages/kit/test/apps/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ test.describe('Load', () => {

if (!javaScriptEnabled) {
// by the time JS has run, hydration will have nuked these scripts
const script_contents = await page.innerHTML('script[data-sveltekit-fetched]');
const script_contents = await page.innerHTML(
'script[data-sveltekit-fetched][data-url="/load/serialization/fetched-from-shared.json"]'
);

const payload = '{"status":200,"statusText":"","headers":{},"body":"{\\"b\\":2}"}';

Expand Down

0 comments on commit 2ef9b7d

Please sign in to comment.