Skip to content
5 changes: 5 additions & 0 deletions .changeset/selfish-crews-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: Prerendered pages fail if they access session.
5 changes: 5 additions & 0 deletions packages/kit/src/runtime/server/page/load_node.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ export async function load_node({
props: shadow.body || {},
routeId: event.routeId,
get session() {
if (node.module.prerender ?? options.prerender.default) {
throw Error(
'Attempted to access session from a prerendered page. Session would never be populated.'
);
}
uses_credentials = true;
return $session;
},
Expand Down
11 changes: 11 additions & 0 deletions packages/kit/test/apps/basics/src/routes/prerendering/index.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<script context="module">
export const prerender = true;

export const load = ({ session }) => {
return {
props: session
};
};
</script>

<h1>You should never see me.</h1>
9 changes: 9 additions & 0 deletions packages/kit/test/apps/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,15 @@ test.describe.parallel('Errors', () => {
expect(await response.text()).toMatch('thisvariableisnotdefined is not defined');
});

test('prerendering a page whose load accesses session results in a catchable error', async ({
page
}) => {
await page.goto('/prerendering');
expect(await page.textContent('h1')).toBe(
'500: Attempted to access session from a prerendered page. Session would never be populated.'
);
});

test('prerendering a page with a mutative page endpoint results in a catchable error', async ({
page
}) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script context="module">
export const load = ({ session }) => {
return {
props: session
};
};
</script>

<h1>I should never be prerendered.</h1>
6 changes: 6 additions & 0 deletions packages/kit/test/prerendering/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ test('does not prerender page with shadow endpoint with non-GET handler', () =>
assert.ok(!fs.existsSync(`${build}/shadowed-post/__data.json`));
});

test('does not prerender page accessing session in load', () => {
// This should fail to prerender as session can never be populated
// for a prerendered page.
assert.ok(!fs.existsSync(`${build}/accesses-session.html`));
});

test('decodes paths when writing files', () => {
let content = read('encoding/path with spaces.html');
assert.ok(content.includes('<p id="a">path with spaces</p>'));
Expand Down