-
I'm wondering, how can I check for a token and redirect the client? Here's my code now which triggers an infinite loop, because the beforeNavigate(({ cancel }) => {
if (!localStorage.getItem("token")) {
cancel();
goto("/panel/login");
}
}); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
You can do this in the <script context="module">
import { browser } from '$app/env';
export async function load() {
if (browser && !localStorage.getItem('token')) {
return {
status: 302,
redirect: '/'
};
}
return {};
}
</script> |
Beta Was this translation helpful? Give feedback.
-
You need to check whether the path is trying to access the protected pages, like beforeNavigate(({ to, cancel }) => {
if (to?.pathname.startsWith('/<protected url>') && !localStorage.getItem("token")) {
cancel();
goto("/panel/login");
}
}); So, the |
Beta Was this translation helpful? Give feedback.
You need to check whether the path is trying to access the protected pages, like
So, the
goto("/panel/login")
will not redirect again.But there's a short period of time the protected page will display before
beforeNavigate
trigger.