Skip to content

Redirect If Logged In Middleware ​

File Information ​

  • Path: app/middleware/redirect-if-logged-in.ts
  • Purpose: Prevents authenticated users from accessing authentication pages
  • Type: Per-Route Middleware

Overview ​

The redirect-if-logged-in.ts middleware prevents authenticated users from accessing authentication-related pages (login, forgot password, reset password, generate password). If an authenticated user tries to access these pages, they are automatically redirected to their brand's home page.

Features ​

  • Auth Page Detection: Identifies authentication pages
  • Authentication Check: Checks if user is authenticated
  • Automatic Redirect: Redirects to brand home page
  • Better UX: Prevents unnecessary auth page visits

Protected Pages ​

The middleware protects these authentication pages:

  • /login - Login page
  • /forgot-password - Password recovery page
  • /reset-password - Password reset page
  • /generate-password - Password generation page

Implementation ​

Auth Page Detection ​

typescript
const authPages = [
  '/login',
  '/forgot-password',
  '/reset-password',
  '/generate-password'
]

const isAuthPage = authPages.some(page => to.path.includes(page))

Authentication Check and Redirect ​

typescript
if (isAuthPage && authStore.isAuthenticated) {
  const brandName = to.params.brand_name as string
  
  if (brandName) {
    return navigateTo(`/${brandName}`) // Redirect to brand home
  } else {
    return navigateTo('/') // Fallback to root
  }
}

Usage ​

In Authentication Pages ​

vue
<!-- app/pages/[brand_name]/login.vue -->
<script setup lang="ts">
definePageMeta({
  middleware: 'redirect-if-logged-in'
})
</script>

<template>
  <div>
    <!-- Login form -->
  </div>
</template>

Applied to Multiple Pages ​

vue
<!-- Forgot Password -->
<script setup lang="ts">
definePageMeta({
  middleware: 'redirect-if-logged-in'
})
</script>

<!-- Reset Password -->
<script setup lang="ts">
definePageMeta({
  middleware: 'redirect-if-logged-in'
})
</script>

Behavior ​

Authenticated User Accessing Auth Page ​

  1. User is authenticated
  2. User navigates to /login (or other auth page)
  3. Middleware detects authentication
  4. User is redirected to /{brand_name}/ (brand home)

Unauthenticated User Accessing Auth Page ​

  1. User is not authenticated
  2. User navigates to /login
  3. Middleware allows access
  4. Login page renders normally

Redirect Logic ​

typescript
// With brand name
if (brandName) {
  return navigateTo(`/${brandName}`) // /mybrand/
}

// Without brand name (fallback)
return navigateTo('/') // Root

Benefits ​

  • Better UX: Prevents logged-in users from seeing login forms
  • Automatic: No manual redirect logic needed in pages
  • Consistent: Same behavior across all auth pages
  • Simple: Easy to apply to any auth page

Dependencies ​

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