Skip to content

Per-Route Authentication Middleware ​

File Information ​

  • Path: app/middleware/auth.ts
  • Purpose: Optional per-route authentication middleware
  • Type: Per-Route Middleware

Overview ​

The auth.ts middleware provides optional authentication checking for specific pages. Unlike the global auth middleware, this middleware only runs when explicitly specified in page metadata. It can be used for additional authentication checks or to override global middleware behavior.

Features ​

  • Optional Execution: Only runs when specified in definePageMeta
  • Authentication Validation: Checks authentication state
  • User Data Fetching: Attempts to fetch user data if token exists
  • Public Route Detection: Skips auth check for public routes
  • Brand-Aware Redirects: Redirects to brand-specific login page

Usage ​

In Page Component ​

vue
<script setup lang="ts">
definePageMeta({
  middleware: 'auth'
})
</script>

<template>
  <div>
    <!-- Page content -->
  </div>
</template>

Public Routes ​

The middleware skips authentication check for these routes:

  • /shared-assets/* - Public shared assets
  • */login - Login page
  • */forgot-password - Password recovery
  • */reset-password - Password reset
  • */generate-password - Password generation
  • */[token] - Token-based 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 = to.params.token || (to.params as any).token

Authentication Check ​

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

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

User Data Fetching ​

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

typescript
if (authStore.accessToken && !authStore.user) {
  try {
    const brandName = to.params.brand_name as string
    await authStore.getUser(false, brandName)
    
    if (authStore.isAuthenticated) {
      return // Allow access after fetching user
    }
  } catch (error) {
    console.error('[Auth Middleware] Failed to fetch user:', error)
  }
}

Redirect Logic ​

typescript
// Not authenticated - redirect to login
const brandName = to.params.brand_name as string
if (brandName) {
  return navigateTo(`/${brandName}/login`)
}

When to Use ​

Use this middleware when:

  • ✅ You need additional authentication checks on specific pages
  • ✅ You want to override global middleware behavior
  • ✅ You need custom authentication logic for a page
  • ✅ You want explicit authentication enforcement

Note: Most pages don't need this middleware because auth.global.ts already handles authentication. Use this only when you need page-specific authentication logic.

Comparison with Global Auth Middleware ​

FeatureGlobal Auth (auth.global.ts)Per-Route Auth (auth.ts)
ExecutionAutomatic on all routesOnly when specified
ConfigurationNo configuration neededRequires definePageMeta
Use CaseApp-wide authenticationPage-specific logic
OverrideCannot be disabledCan be used selectively

Dependencies ​

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