Skip to content

Commit 315b643

Browse files
authored
[fix] prevent caching of __data.js files (#6904)
Closes #6458
1 parent cea8998 commit 315b643

File tree

5 files changed

+36
-10
lines changed

5 files changed

+36
-10
lines changed

.changeset/cyan-years-live.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+
Prevent caching of `__data.js` files

packages/kit/src/runtime/server/utils.js

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,21 +70,18 @@ export function allowed_methods(mod) {
7070

7171
/** @param {any} data */
7272
export function data_response(data) {
73+
const headers = {
74+
'content-type': 'application/javascript',
75+
'cache-control': 'private, no-store'
76+
};
77+
7378
try {
74-
return new Response(`window.__sveltekit_data = ${devalue(data)}`, {
75-
headers: {
76-
'content-type': 'application/javascript'
77-
}
78-
});
79+
return new Response(`window.__sveltekit_data = ${devalue(data)}`, { headers });
7980
} catch (e) {
8081
const error = /** @type {any} */ (e);
8182
const match = /\[(\d+)\]\.data\.(.+)/.exec(error.path);
8283
const message = match ? `${error.message} (data.${match[2]})` : error.message;
83-
return new Response(`throw new Error(${JSON.stringify(message)})`, {
84-
headers: {
85-
'content-type': 'application/javascript'
86-
}
87-
});
84+
return new Response(`throw new Error(${JSON.stringify(message)})`, { headers });
8885
}
8986
}
9087

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/** @type {import('./$types').PageServerLoad} */
2+
export function load({ url }) {
3+
return {
4+
x: url.searchParams.get('x')
5+
};
6+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<script>
2+
/** @type {import('./$types').PageData} */
3+
export let data;
4+
</script>
5+
6+
<h1>x: {data.x}</h1>
7+
<a href="/load/server-data-nostore?x=2">2</a>

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,17 @@ test.describe('Load', () => {
431431
await expect(page.locator('p')).toHaveText('Count is 2');
432432
});
433433

434+
test('__data.js has cache-control: private, no-store', async ({ page, clicknav }) => {
435+
await page.goto('/load/server-data-nostore?x=1');
436+
437+
const [response] = await Promise.all([
438+
page.waitForResponse((response) => /__data\.js/.test(response.url())),
439+
clicknav('[href="/load/server-data-nostore?x=2"]')
440+
]);
441+
442+
expect(response.headers()['cache-control']).toBe('private, no-store');
443+
});
444+
434445
if (process.env.DEV) {
435446
test('using window.fetch causes a warning', async ({ page }) => {
436447
const port = 5173;

0 commit comments

Comments
 (0)