habits.andr33v.ru/middleware/auth.global.ts

20 lines
722 B
TypeScript

// /middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
const { isAuthenticated, initialized } = useAuth();
// Do not run middleware until auth state is initialized on client-side
if (!initialized.value) {
return;
}
// if the user is authenticated and tries to access /login, redirect to home
if (isAuthenticated.value && to.path === '/login') {
return navigateTo('/', { replace: true });
}
// if the user is not authenticated and tries to access any page other than public routes, redirect to /login
const publicRoutes = ['/login', '/register'];
if (!isAuthenticated.value && !publicRoutes.includes(to.path)) {
return navigateTo('/login', { replace: true });
}
});