Skip to content

Commit

Permalink
fix: adjust fetch error message on the server (#8551)
Browse files Browse the repository at this point in the history
* fix: adjust fetch error message on the server

closes #8536

* make it possible to still use them in #await blocks

* undo #await dance

* put additional dev time check inside render.js instead

* Create five-pumpkins-join.md

* prevent corrupted state

* Delete nice-mayflies-compete.md

---------

Co-authored-by: Rich Harris <richard.a.harris@gmail.com>
Co-authored-by: Rich Harris <hello@rich-harris.dev>
  • Loading branch information
3 people authored Feb 9, 2023
1 parent eb94356 commit 930c8e4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/five-pumpkins-join.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/kit": patch
---

fix: provide helpful error/warning when calling `fetch` during render
27 changes: 26 additions & 1 deletion packages/kit/src/runtime/server/page/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,32 @@ export async function render_response({
form: form_value
};

rendered = options.root.render(props);
if (__SVELTEKIT_DEV__) {
const fetch = globalThis.fetch;
let warned = false;
globalThis.fetch = (info, init) => {
if (typeof info === 'string' && !/^\w+:\/\//.test(info)) {
throw new Error(
`Cannot call \`fetch\` eagerly during server side rendering with relative URL (${info}) — put your \`fetch\` calls inside \`onMount\` or a \`load\` function instead`
);
} else if (!warned) {
console.warn(
`Avoid calling \`fetch\` eagerly during server side rendering — put your \`fetch\` calls inside \`onMount\` or a \`load\` function instead`
);
warned = true;
}

return fetch(info, init);
};

try {
rendered = options.root.render(props);
} finally {
globalThis.fetch = fetch;
}
} else {
rendered = options.root.render(props);
}

for (const { node } of branch) {
if (node.imports) {
Expand Down

0 comments on commit 930c8e4

Please sign in to comment.