Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stale-dogs-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Return 404 when fetching missing data during prerender
4 changes: 4 additions & 0 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,10 @@ export async function respond(request, options, state = {}) {
});
}

if (state.prerender) {
return new Response('not found', { status: 404 });
}

// we can't load the endpoint from our own manifest,
// so we need to make an actual HTTP request
return await fetch(request);
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/src/runtime/server/page/load_node.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ export async function load_node({

response = await respond(new Request(new URL(requested, event.url).href, opts), options, {
fetched: requested,
initiator: route
initiator: route,
prerender: state.prerender
});

if (state.prerender) {
Expand Down
17 changes: 17 additions & 0 deletions packages/kit/test/prerendering/basics/src/routes/fetch-404.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<script context="module">
/** @type {import('./fetch-404').Load} */
export async function load({ fetch }) {
const { status } = await fetch('/missing.json');

return {
props: { status }
};
}
</script>

<script>
/** @type {number} */
export let status;
</script>

<h1>status: {status}</h1>
5 changes: 5 additions & 0 deletions packages/kit/test/prerendering/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,9 @@ test('prerendering is set to true in global code of hooks.js', () => {
assert.ok(content.includes('<h1>prerendering: true/true</h1>'), content);
});

test('fetching missing content results in a 404', () => {
const content = read('fetch-404.html');
assert.ok(content.includes('<h1>status: 404</h1>'), content);
});

test.run();