routesaccess-tokensveltesveltekit

SvelteKit: Run function at route change (for access token, without doing it at a layout file)


I just started with SvelteKit and I have a question regarding functions, that should run on every route change. I did not find much, helpful information about it.

Just to run it at the layout files (which I do not prefer, because I might probably use multiple layout files and prefer one global place.)

In Vue.js, I do something like that, to check at every route change, if there is an access token (at the end of the router file):

// src/router/index.ts
router.beforeEach((to, from, next) => {
  AUTHENTICATION.default.fetchAccessToken();
  if (to.options.protected && !AUTHENTICATION.default.tokenData) {
    next("/");
  } else next();
});

How would I achive that in SvelteKit?

Would that work with svelte-routing in SvelteKit? ... and is that in general a good idea, to check an access token?

Thank you in advance


Solution

  • You can use the navigating store.

    navigating is a readable store. When navigating starts, its value is { from, to, type }, where from and to both mirror the page store value. When navigating finishes, its value reverts to null.

    import { navigating } from '$app/stores';
    

    in the <script> tag, should $: marks a statement as reactive. Therefore it will be executed every time when navigating happened.

    $: if($navigating) myFunction();
    

    Of course you can use it in the HTML template.

    {#if $navigating}
        <LoadingIndicator />
    {/if}
    

    More info about navigation: https://svelte.dev/docs/kit/$app-state#navigating