'is there something similar to Angular route guards in SvelteKit
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.
Solution 1:[1]
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 />
Solution 2:[2]
svelte-router-spa module offers good and practical features for routing, minimum configurations and simple usage. Guards are included.
Solution 3:[3]
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}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | justintimeza |
| Solution 2 | Shizon |
| Solution 3 |
