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

Viewed 4460

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?

2 Answers

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

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 (externalFetch) that's build to address resources differently if client or server:

https://kit.svelte.dev/docs/hooks#externalfetch

/** @type {import('@sveltejs/kit').ExternalFetch} */
export async function externalFetch(request) {
  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);
}
Related