Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SvelteKit: +page.js load() function causes "500 Internal Error" after refreshing the page

I am trying to use the load() function in the +page.js file to fetch data, which works fine after the initial load of the page. Though if I refresh the page (or change the code and it auto-refreshes) it gives me an error: "500 Internal Error".

I can navigate to another route on my page and go back to this page and it works again.

+page.js:

export async function load() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    const books = await res.json();

    return {
        books
    }
}

+page.svelte:

<script>
    export let data
    let id = parseInt(new URLSearchParams(window.location.search).get('id')) - 1
</script>

<h2>{data.books[id].title}</h2>
<p>{data.books[id].body}</p>

What am I doing wrong?

like image 459
Jon Jampen Avatar asked Oct 28 '25 01:10

Jon Jampen


1 Answers

You're calling window before initialization, this code is evaluated server-side, in a context where it does not exist. Import browser helper utility from sveltekit to deal with this, like so:

import { browser } from '$app/environment';
export let data;
let id = 0;
             
if (browser)
  id = parseInt(new URLSearchParams(window.location.search).get('id')) - 1
like image 186
Tonton-Blax Avatar answered Oct 30 '25 13:10

Tonton-Blax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!