My question is very simple. How do you prevent, e.g. non authorized user, to enter specific routes in sapper?
user.svelte
<script>
import { onMount } from 'svelte';
onMount(() => {
if(!authenticated)
window.history.back()
});
</script>
Is there any option to run some code before mounting to the DOM?
How do you solve this kind of problem?
Thank you.
I can't say it's the right thing. It's what I do in my SPAs. If I want to protect all routes of my app. I create following in _layout.svelte
top file.
<script context="module">
import {ax} from './_parts/Helper.svelte'
import {admin, adminName} from './store'
import {goto} from '@sapper/app'
export async function preload(page) {
try {
const {data} = await ax.get('/admin/is-logged-in')
adminName.set(data)
admin.set(true)
} catch (e) {
admin.set(false)
}
}
</script>
<script>
import Login from './admin/login.svelte'
import {loading} from './store.js'
</script>
<main>
{#if $admin}
<slot></slot>
{:else}
<Login />
{/if}
</main>
ax
is nothing magic. It's just configured axios.
'/admin/is-logged-in'
is where you check session at backend.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With