Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 716
cambraca Avatar asked Jun 02 '21 16:06

cambraca


People also ask

Is SvelteKit a backend framework?

SvelteKit is an opinionated full stack framework that ties the frontend and backend together delivering the best developer and user experience.

What does SvelteKit add?

On the contrary, Sveltekit is a framework for building svelte apps of all sizes; it enables you to build more significant apps with a smaller footprint. It comes with a beautiful development experience, flexible filesystem-based routing, Server-Side Rendering(SSR), client-side hydration, and some other unique features.

What is Page svelte?

Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.


2 Answers

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

<script context="module">
    import { browser } from '$app/env'; 
    ...
    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

like image 137
phaleth Avatar answered Sep 21 '22 06:09

phaleth


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);
}
like image 23
Jacopo Pace Avatar answered Sep 19 '22 06:09

Jacopo Pace