Skip to content

Global Authentication Middleware ​

File Information ​

  • Path: app/middleware/auth.global.ts
  • Purpose: Global authentication middleware that runs on all routes
  • Type: Global Middleware (.global.ts suffix)

Overview ​

The auth.global.ts middleware is a global middleware that runs automatically on every page navigation. It handles authentication state validation, user data fetching, and protected route enforcement. This middleware cannot be disabled and runs before any per-route middleware.

Features ​

  • Automatic Execution: Runs on all routes without explicit configuration
  • Authentication Validation: Checks authentication state on every navigation
  • User Data Hydration: Fetches user data if token exists but user data is missing
  • Protected Route Enforcement: Redirects unauthenticated users to login
  • Public Route Detection: Allows access to public routes without authentication
  • Token-Based Route Support: Supports token-based authentication routes

Execution Flow ​

1. Check if route is public → Allow access
2. Check if user is authenticated → Allow access
3. If token exists but no user data → Fetch user data
4. If not authenticated → Redirect to login

Public Routes ​

The middleware allows access to these routes without authentication:

  • /shared-assets/* - Public shared assets
  • */login - Login page
  • */forgot-password - Password recovery
  • */reset-password - Password reset
  • */generate-password - Password generation
  • */[token] - Token-based routes (routes with token parameter)

Protected Routes ​

All other routes require authentication. If a user is not authenticated, they are redirected to the login page:

typescript
// Redirect format: /{brand_name}/login
return navigateTo(`/${brandName}/login`)

Special Cases ​

Brand Home Route ​

The middleware allows unauthenticated access to the exact brand home route (/{brand_name}) to allow client-side middleware (like public-portal-home) to check and auto-login public portals without a server-side redirect first.

typescript
// Special case: allow unauthenticated access to brand home
const brandName = to.params.brand_name as string
if (brandName && to.path === `/${brandName}`) {
  return // Allow access
}

User Data Fetching ​

If a token exists but user data is missing, the middleware attempts to fetch user data:

typescript
if (authStore.accessToken && !authStore.user) {
  try {
    await authStore.getUser(false)
  } catch (error) {
    // Handle error silently for public routes
  }
}

Implementation Details ​

Public Route Detection ​

typescript
const isSharedAssets = to.path.startsWith("/shared-assets")
const isAuthPage = to.path.includes("/login") ||
                   to.path.includes("/forgot-password") ||
                   to.path.includes("/reset-password") ||
                   to.path.includes("/generate-password")
const hasTokenParam = Boolean(to.params?.token)

Authentication Check ​

typescript
// Skip auth enforcement for public pages
if (isSharedAssets || isAuthPage || hasTokenParam) {
  return // Allow access
}

// Check if authenticated
if (authStore.isAuthenticated) {
  return // Allow access
}

Redirect Logic ​

typescript
// Not authenticated - redirect to login
if (brandName) {
  return navigateTo(`/${brandName}/login`)
}

Usage ​

This middleware runs automatically on all routes. No configuration is needed.

typescript
// Automatically runs - no definePageMeta needed
// Runs before any page component renders

Dependencies ​

  • useAuthStore() - Authentication store
  • navigateTo() - Nuxt navigation helper

Error Handling ​

The middleware handles errors gracefully:

  • Silently handles user fetch errors on public routes
  • Logs errors to console for debugging
  • Redirects to login on authentication failure

SSR Compatibility ​

The middleware works in both SSR and client contexts:

  • Server-side: Can access cookies and headers
  • Client-side: Can access browser APIs and stores