|
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");
}
}); |
Answered by
biaocy
Jun 16, 2022
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> |
0 replies
|
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 |
0 replies
Answer selected by
HenrijsS
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
beforeNavigatetrigger.