Skip to content

Auth Init Plugin ​

File Information ​

  • Path: app/plugins/01.auth-init.ts
  • Purpose: Initialize authentication state from HTTP-only cookies during SSR
  • Type: Universal (runs on both server and client)
  • Load Order: 3 (after Pinia and API client)

Overview ​

The Auth Init plugin initializes the authentication state from HTTP-only cookies during server-side rendering. On the client-side, it also loads accessible instances from localStorage. This ensures that authenticated users are recognized immediately when the page loads.

Key Features ​

  1. Cookie-Based Authentication

    • Reads auth_token cookie
    • Reads auth_user cookie
    • Parses user data from cookies
  2. Store Initialization

    • Initializes auth store with token and user data
    • Skips initialization if token already exists (hydration)
    • Handles cookie parsing errors gracefully
  3. Accessible Instances

    • Loads accessible instances from localStorage on client
    • Merges with existing store state
    • Only runs on client-side
  4. SSR Compatibility

    • Works during server-side rendering
    • Handles cookie reading on server
    • Properly hydrates state on client

Code Structure ​

typescript
export default defineNuxtPlugin(() => {
  const authStore = useAuthStore()
  
  // Skip if token already exists (from hydration)
  if (authStore.accessToken) {
    if (import.meta.client) {
      authStore.loadAccessibleInstancesFromStorage()
    }
    return
  }
  
  // Read cookies
  const tokenCookie = useCookie<string | null>('auth_token')
  const userCookie = useCookie<string | null>('auth_user')
  
  // Parse user data
  let userData = null
  if (userCookie.value) {
    try {
      userData = typeof userCookie.value === 'string' 
        ? JSON.parse(userCookie.value) 
        : userCookie.value
    } catch (e) {
      console.error('[Auth Init] Failed to parse user cookie:', e)
    }
  }
  
  // Initialize store
  if (tokenCookie.value) {
    authStore.initialize(tokenCookie.value, userData)
    
    if (import.meta.client) {
      authStore.loadAccessibleInstancesFromStorage()
    }
  }
})

Dependencies ​

  • Pinia Plugin - Must load before this plugin (provides auth store)
  • API Client Plugin - Must load before this plugin (for API calls)

Methods Used ​

authStore.initialize(token, userData) ​

Initializes auth store with token and user data.

Parameters:

  • token: string - Authentication token
  • userData: any - User data object

authStore.loadAccessibleInstancesFromStorage() ​

Loads accessible instances from localStorage.

Note: Only runs on client-side.

auth_token ​

  • Type: string | null
  • Purpose: Authentication token
  • Security: HTTP-only cookie

auth_user ​

  • Type: string | null (JSON stringified)
  • Purpose: User data
  • Format: JSON string that needs parsing

Error Handling ​

  • Cookie parsing errors are caught and logged
  • Failed parsing doesn't break initialization
  • Missing cookies are handled gracefully

SSR Behavior ​

Server-Side ​

  • Reads cookies from request headers
  • Initializes store with cookie values
  • Prepares state for hydration

Client-Side ​

  • Hydrates store from SSR payload (if token exists)
  • Loads accessible instances from localStorage
  • Merges localStorage data with store state

Usage ​

This plugin runs automatically during Nuxt initialization. No manual setup required.

Security Considerations ​

  • Uses HTTP-only cookies (prevents XSS attacks)
  • Token stored securely in cookies
  • User data parsed safely with error handling

Notes for Development ​

  • Plugin name starts with 01. to ensure load order
  • Must load after Pinia and API client plugins
  • Skips initialization if token already exists (hydration)
  • Accessible instances only loaded on client-side
  • Cookie parsing handles both string and object formats