is there something similar to Angular route guards in SvelteKit

Viewed 1855

I am trying to build an SPA with role based access using Svelte. Coming from Angular with its route guards, I want to setup something similar.

What would be the best way to do that?

EDIT:

I was indeed referring to SvelteKit, and I updated my question to reflect that.

4 Answers

I'm assuming you are referring to SvelteKit, which includes routing. Please confirm?

If you have subfolders for each route, you can create a __layout.svelte file in each route folder which will be run on every request to that route. You can put your guard logic in the layout file.

Example:

File location: /src/admin/__layout.svelte

<script context="module">
    import { goto } from '$app/navigation';
    import { browser } from '$app/env';
    // import your user store here.

    // if (browser && $user)

    // Add your specific guard logic here, you need to include the 'browser' 
    //check otherwise Vite tries to process it on the server side
    if (browser) {
        // Use Goto to redirect users if neccessary
        goto('login');
    }
</script>

<!--<slot> the same as router-outlet -->
<slot />

My user store doesn't work inside <script context="module"> so I have to do it client side...the drawback being you get a flash of rendered page:

<script>
    import { goto } from '$app/navigation';
    import { browser } from '$app/env';
    import { userStore } from '$stores/user.js';

    if (browser && !$userStore) {
        goto('/login');
    }
</script>

<slot />

My user store uses localStorage for token so it must be done in browser (not ssr)

You can hide the protected content with a conditional:

<script>
    import { goto } from '$app/navigation';
    import { browser } from '$app/env';
    import { userStore } from '$stores/user.js';

    if (browser && !$userStore) {
        goto('/login');
    }
</script>

{#if $userStore}
    <slot />
{/if}

EDIT:

The author has changed the question to sveltekit. The answer from @justintimeza is correct.

The below explanation is still valid for just svelte.

Svelte has no routing you can use packages like routify, tinro that gives you the utility for routes.

Also, take a look at svelte-routing regarding an approach.

Related