Differentiate between Server Side and Client Side on fetch Sapper

Viewed 755

Sapper gives you the ability to preload that runs on both client and server side.

<script context="module">
    export async function preload(page, session) {
        const res = await this.fetch(`blog.json`);
        const article = await res.json();
        return { article };
    }
</script>

How would I distinguish between a server side call and a client side call?

In Nuxt the context provides isServer and isClient to differentiate. Is there one for sapper?

2 Answers

Have you tried to catch the error

let isServer;

try {
    let win = window;
    isServer = false;
} catch (e) {
    isServer = true;
}

PS: I actually found the solution in svelte kit Docs

import { browser } from '$app/env';

// browser is true or false depending on whether the app is running in the browser or on the server

I believe some variables such as process.browser or the global window variable are only available on the client side, so you should be able to use these to determine whether your code is running on the client or the server.

Within the regular <script>...</script> tags, you can also use Svelte's onMount lifecycle function to execute code that will only run on the client (i.e. when the component is actually mounted).

Related