I need advice on how to properly redirect non-authenticated users to the login page when using JWT tokens for authentication. My current approach involves using the router.beforeEach()
method in my route configuration, but I'm encountering an issue with an infinite loop:
router.beforeEach((to, from, next) => {
if (to.matched.some(r => r.meta.requiresAuth)) {
alert('needs auth!'); // just for testing
if (localStorage.getItem('jwt') === null) {
next('/login'); // causes the infinite loop
} else {
next();
}
} else {
next();
}
});
Whenever I try to access a route that requires authentication, the next('/login')
call gets stuck in an infinite loop. One workaround is to check for the login route specifically:
if (to.path !== '/login') {
next('/login');
} else {
next();
}
However, this solution triggers the alert twice and feels inefficient. Is there a more elegant way to handle these route conditions? Any advice or suggestions would be greatly appreciated. Thank you!