Skip to content

Commit

Permalink
Return 404s from fetch in load during prerender (#4324)
Browse files Browse the repository at this point in the history
* return 404 for missing fetched content during prerendering

* changeset
  • Loading branch information
Rich-Harris authored Mar 14, 2022
1 parent 8adec6f commit c3c700f
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 1 deletion.
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();

0 comments on commit c3c700f

Please sign in to comment.