export default defineNuxtRouteMiddleware(async (to, from) => { // Allow pages to opt-out of auth with definePageMeta({ auth: false }) if (to.meta.auth === false) { return } // Public routes that don't require authentication const publicRoutes = ['/login', '/register'] if (publicRoutes.includes(to.path)) { return } const authMessage = useCookie('authMessage') // Check for tenant cookie (set alongside session cookie on login) const tenantCookie = useCookie('routebox_tenant') // Also check for session cookie (HTTP-only, but readable in SSR context) const sessionCookie = useCookie('routebox_session') // Routes that don't need a toast message (user knows they need to login) const silentRoutes = ['/'] // On client side, check the reactive auth state if (import.meta.client) { const { isAuthenticated, checkAuth } = useAuth() // If we already know we're authenticated, allow if (isAuthenticated.value) { return } // If we have a tenant cookie, try to validate the session if (tenantCookie.value) { const isValid = await checkAuth() if (isValid) { return } } // Not authenticated if (!silentRoutes.includes(to.path)) { authMessage.value = 'Please login to access this page' } return navigateTo('/login') } // Server-side: check for both session and tenant cookies // The session cookie is HTTP-only but can be read in SSR context if (!sessionCookie.value || !tenantCookie.value) { if (!silentRoutes.includes(to.path)) { authMessage.value = 'Please login to access this page' } return navigateTo('/login') } })