SvelteKit SSR - how to block server-side render until data has been fetched?

Viewed 2509

I am using SvelteKit and, for SEO reasons, I would like to use full SSR and to ensure that all data is fetched and rendered server-side before being delivered to the browser. In other words, all calls to the back-end API should have completed before the initial page response is delivered.

However, it is unclear to me from the documentation how to achieve this. (I may have missed something.)

I have tried the following, but this just delivers a completely empty body:

<script>
    let promise = fetch('https://swapi.dev/api/people/1/')
        .then((response) => response.json());
</script>

{#await promise then character}
<main>
    <h1>Your character</h1>
    Name is {character.name}
</main>
{/await}

Does anyone know how to block server-side render using SvelteKit until data has been fetched?

2 Answers

As noted above, the answer is to export a load function (as described here), but just to add a working example of this:

<script context="module">
    /**
     * @type {import('@sveltejs/kit').Load}
     */
    export async function load({ page, fetch, session, context }) {
        const url = `https://swapi.dev/api/people/1/`;
        const res = await fetch(url);

        if (res.ok) {
            return {
                props: {
                    character: await res.json()
                }
            };
        }

        return {
            status: res.status,
            error: new Error(`Could not load ${url}`)
        };
    }
</script>

<script lang="typescript">
    export let character: any;
</script>

<main>
    <h1>Your character:</h1>
    <p>Name is {character.name}</p>
    <p>Hair color is {character.hair_color}</p>
</main>
Related