25 lines
709 B
TypeScript
25 lines
709 B
TypeScript
// middleware/auth.ts
|
|
import { useAuth } from '~/composables/useAuth';
|
|
|
|
export default defineNuxtRouteMiddleware(async (to) => {
|
|
// This middleware should only run on the client-side after the initial server-side render.
|
|
if (process.server) {
|
|
return;
|
|
}
|
|
|
|
const { isLoggedIn, fetchUserSession } = useAuth();
|
|
|
|
// Initial check
|
|
if (!isLoggedIn.value) {
|
|
await fetchUserSession();
|
|
}
|
|
|
|
// List of public routes that don't require authentication
|
|
const publicRoutes = ['/auth/login', '/auth/register'];
|
|
|
|
// If the route is not public and the user is not logged in, redirect to login
|
|
if (!publicRoutes.includes(to.path) && !isLoggedIn.value) {
|
|
return navigateTo('/auth/login');
|
|
}
|
|
});
|