Hellop, I have a vue3 app consume laravel 11 api,
I want to develop a router guard to redirect unauthenticated users to the login page. When the Laravel server is not running, the code works and redirects to the login page, but when the server is running, it may cause an infinite loop of requests being sent to the server to check the authenticated user and nothing renders neither the login page nor others :
router.beforeEach(async (to, from, next) => {
const store = useAppStore();
const authStore = useAuthStore();
const isAuthenticated = authStore.currentUser !== null;
if (to.meta.requiresAuth) {
if (isAuthenticated) {
if (to.name === 'login') {
next({ name: 'home' });
} else next();
} else if (to.name === 'login') {
next();
} else {
try {
const response = authStore.getAuthUser();
console.log(response?.data?.user);
if (!response?.data?.user) {
console.log('not logged'); // le log is shown but it does not reditect to /login and it send infinite requests to authStore.getAuthUser() (/api/user)
return next({ name: 'login' });
} else {
next();
}
} catch (error) {
console.log('Error during authentication check:', error);
next({ name: 'login' });
}
}
} else {
if (to.name === 'login') {
next({ name: 'home' });
} else next();
}
});
can anyone help me !!