Skip to content

Commit

Permalink
[fix] prevent caching of __data.js files (#6904)
Browse files Browse the repository at this point in the history
Closes #6458
  • Loading branch information
Rich-Harris committed Sep 20, 2022
1 parent cea8998 commit 315b643
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-years-live.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Prevent caching of `__data.js` files
17 changes: 7 additions & 10 deletions packages/kit/src/runtime/server/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,21 +70,18 @@ export function allowed_methods(mod) {

/** @param {any} data */
export function data_response(data) {
const headers = {
'content-type': 'application/javascript',
'cache-control': 'private, no-store'
};

try {
return new Response(`window.__sveltekit_data = ${devalue(data)}`, {
headers: {
'content-type': 'application/javascript'
}
});
return new Response(`window.__sveltekit_data = ${devalue(data)}`, { headers });
} catch (e) {
const error = /** @type {any} */ (e);
const match = /\[(\d+)\]\.data\.(.+)/.exec(error.path);
const message = match ? `${error.message} (data.${match[2]})` : error.message;
return new Response(`throw new Error(${JSON.stringify(message)})`, {
headers: {
'content-type': 'application/javascript'
}
});
return new Response(`throw new Error(${JSON.stringify(message)})`, { headers });
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('./$types').PageServerLoad} */
export function load({ url }) {
return {
x: url.searchParams.get('x')
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
/** @type {import('./$types').PageData} */
export let data;
</script>

<h1>x: {data.x}</h1>
<a href="/load/server-data-nostore?x=2">2</a>
11 changes: 11 additions & 0 deletions packages/kit/test/apps/basics/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,17 @@ test.describe('Load', () => {
await expect(page.locator('p')).toHaveText('Count is 2');
});

test('__data.js has cache-control: private, no-store', async ({ page, clicknav }) => {
await page.goto('/load/server-data-nostore?x=1');

const [response] = await Promise.all([
page.waitForResponse((response) => /__data\.js/.test(response.url())),
clicknav('[href="/load/server-data-nostore?x=2"]')
]);

expect(response.headers()['cache-control']).toBe('private, no-store');
});

if (process.env.DEV) {
test('using window.fetch causes a warning', async ({ page }) => {
const port = 5173;
Expand Down

0 comments on commit 315b643

Please sign in to comment.