Search code examples
sveltesveltekitsvelte-3svelte-store

SvelteKit readable store initialize on client-side only


I have an authToken readable store that can only be initialized from the client side. It's shared between many components, so it exists in it's own .ts file:

// auth.ts

export const authToken = readable("", (set) => {
  const updateToken = async () => {
    const token = await fetchToken() // ... fetch API token
    set(token)
  };
  setTimeout(fetchToken, 0);
});

With SvelteKit/Vite, this code is being run on the server side and failing during compile. How can I force this to only initialize for the first time onMount (without it being in a .svelte component)?


Solution

  • You should be able to use the browser flag, e.g.:

    import { browser } from '$app/environment';
    
    export const authToken = readable("", (set) => {
      const updateToken = async () => {
        // ...
      };
    
      if (browser)
        updateToken();
    });