@nuxtjs/auth Documentation

repository·dev·Indexed 23 days ago

https://github.com/nuxt-community/auth-module

Authentication module for Nuxt 2 applications providing zero-boilerplate support. Features include a globally injected $auth instance, reactive user state, strategy-based login via loginWith(), and configurable token storage using cookies (required for SSR) or localStorage. Includes utilities for managing redirects, token refreshing via RefreshController, and universal storage synchronization across Vuex, cookies, and localStorage.

Tokens
22.7K
Snippets
65
Records
136
Agent score
83%

What's inside @nuxtjs/auth

  1. Nuxt Auth Module Overview

    dev

    The Auth Module provides zero-boilerplate authentication support for Nuxt 2. It allows you to authenticate users via configurable schemes or directly supported providers.

    Key characteristics:

    • Client-side storage: It automatically handles storing authentication information on the client-side.
    • API access: It provides a $auth service API to trigger authentication actions and access user data.
    • Limitation: It does NOT implement session handling or provide session-based authentication on the NuxtJS server.
  2. Understand the role of Providers in Auth Module

    dev

    Providers are an abstraction layer built on top of Schemes. While Schemes handle the core authentication logic, Providers simplify integration with popular third-party authentication services (e.g., Google, Facebook, etc.).

    Beyond simple integration, Providers can handle complex requirements such as server-side changes like token signing. You can also implement custom Providers if you need to integrate with a proprietary or non-standard authentication service.

  3. Use $auth reactive properties

    dev

    All properties on the $auth instance are reactive and can be used in Vue template v-if conditions.

    user

    An object containing details about the authenticated user (e.g., name).

    loggedIn

    A boolean flag indicating if a user is currently authenticated and available.

    // Accessing properties in a component
    this.$auth.user
    this.$auth.loggedIn
    
    // Accessing via Vuex
    this.$store.state.auth.user
    this.$store.state.auth.loggedIn
  4. Understand the difference between Scheme, Strategy, and Provider

    dev

    The Auth Module uses three core abstractions to manage authentication:

    • Scheme: Defines the underlying authentication logic (e.g., how to handle tokens, how to communicate with a backend).
    • Strategy: A specific, configured instance of a Scheme. While a Scheme defines the how, a Strategy is the actual implementation used by your application with specific settings.
    • Provider: An abstraction that auto-configures Schemes for you, simplifying the setup process.
  5. How token refresh works in OAuth2

    dev

    If your provider issues refresh tokens, the module will automatically use them to refresh the token before every Axios request.

    Note: This feature is only supported for jwt tokens.

    Behavior when the refresh token has expired:

    • Server side (during page reload or initial navigation): The user is logged out and navigated to the home page.
    • Client side (Client initiated axios request): The user is logged out and navigated to the logout page.
  6. Sync Token Lifetimes with Laravel JWT config

    dev

    The Laravel JWT provider manages token refreshing automatically based on the token lifetime. To ensure seamless authentication, the maxAge values in your Nuxt configuration must match the ttl and refresh_ttl settings in your Laravel JWT configuration.

    Values in Nuxt must be provided in seconds.

    Example mapping:

    • token.maxAge $\rightarrow$ Laravel ttl (in seconds)
    • refreshToken.maxAge $\rightarrow$ Laravel refresh_ttl (in seconds)
    auth: {
      strategies: {
        'laravelJWT': {
          ...
          token: {
            maxAge: 60 * 60 // same as ttl but in seconds
          },
          refreshToken: {
            maxAge: 20160 * 60 // same as refresh_ttl but in seconds
          }
          ...
        }
      }
    }
  7. Use the refresh scheme for token-based authentication

    dev

    The refresh scheme is an extension of the local scheme designed for authentication systems that utilize token refreshing. To use it, set your strategy's scheme to 'refresh' in your Nuxt configuration.

    This scheme allows you to manage both an access token and a refresh token, automatically handling token renewal to maintain user sessions.

    auth: {
      strategies: {
        local: {
          scheme: 'refresh',
          // ... other options
        }
      }
    }
  8. How user information fetching works in the `local` scheme

    dev

    The local scheme requires a way to persist user information (like ID or email) across page reloads. This is typically handled via a user endpoint.

    Automatic Fetching

    By default, user.autoFetch is true. After a successful loginWith call, the module automatically calls the configured endpoints.user URL. The resulting JSON is assigned to this.$auth.user.

    Manual Fetching (Optimized)

    To save an extra HTTP request, you can set user.autoFetch: false. In this scenario, you should:

    1. Capture the user data from the loginWith response.
    2. Pass that data to this.$auth.setUser(userData).

    Note: Even if autoFetch is false, you should still implement the user endpoint if you want user info to be available on page refreshes. If you want to disable user info entirely, set endpoints.user: false, which results in this.$auth.user being {}.

  9. How schemes and strategies work together

    dev

    Schemes define the core authentication logic (e.g., how to fetch a user or handle a login). A Strategy is a specific, configured instance of a Scheme.

    You can define multiple strategies in your nuxt.config.js under the auth.strategies key. By default, the strategy name is used as the scheme name, but you can use the scheme property to point to a different scheme or a custom file path to allow multiple instances of the same scheme or to use a custom implementation.

    auth: {
      strategies: {
        local1: { scheme: 'local', /* ... */ },
        local2: { scheme: 'local', /* ... */ },
        custom: { scheme: '~/schemes/customStrategy', /* ... */ },
      }
    }
    auth: {
      strategies: {
        local: { /* ... */ },
        github: { /* ... */ },
      }
    }
  10. Configure Laravel JWT routes and user endpoint

    dev

    The Laravel JWT provider expects specific route patterns. Based on standard Laravel JWT route groups (e.g., using a prefix like auth), the expected endpoints are:

    • login: /api/auth/login
    • logout: /api/auth/logout
    • refresh: /api/auth/refresh
    • user: /api/auth/user

    Important: While Laravel JWT documentation often suggests using /api/auth/me/ for the user endpoint, this Nuxt Auth provider defaults to /api/auth/user/. Ensure your Laravel routes match the latter or override the endpoints in your strategy configuration.

  11. Use the Cookie scheme for authentication

    dev

    The cookie scheme is an extended version of the local scheme. Instead of relying solely on a token stored in local storage, it depends on a cookie set by your authentication provider. This is useful for scenarios where the server manages session state via cookies (e.g., for CSRF protection or HttpOnly cookies).

    auth: {
      strategies: {
        cookie: {
          // configuration options
        }
      }
    }