cambraca
cambraca

Reputation: 27835

How can I tell whether SvelteKit's "load" function is running on the server vs. client?

I'm trying to do API calls in a SvelteKit page from the load function, but I don't want to proxy these calls with local endpoints because I want to keep the web server as light as possible.

What I want to do specifically is, when the call is made from the server, the API's URL should be different than when it's called from the client (e.g. "http://localhost:1234" vs. "https://example.com:1234", respectively).

But, more generally than this, is there a way to differentiate whether the current code is running on the server vs. the client?

Upvotes: 20

Views: 16255

Answers (2)

Jacopo Pace
Jacopo Pace

Reputation: 492

Disclaimer: what I'm writing is not the real answer to the title, but it is the specific answer to the described problem.

There's a targeted hook function (handleFetch) that's build to address resources differently if client or server:

https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch

/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
    if (request.url.startsWith('https://api.yourapp.com/')) {
        // clone the original request, but change the URL
        request = new Request(
            request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),
            request
        );
    }

    return fetch(request);
}

Upvotes: 6

phaleth
phaleth

Reputation: 669

Within the load function there is the option to use the browser flag after it's imported from $app/environment.

<script context="module">
    import { browser } from '$app/environment'; 
    ...
    export async function load({ fetch }) {
        if (!browser) {
            // code here runs only on the server
        }
        return {
           ...
        }
    }
    ...
<script>

Following comes from SvelteKit's docs:

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

Upvotes: 42

Related Questions