### Install Nuxt Auth Sanctum Module Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/getting-started/installation Installs the nuxt-auth-sanctum module using npx, automatically registering it in your nuxt.config.ts. ```bash npx nuxi@latest module add nuxt-auth-sanctum ``` -------------------------------- ### Install Nuxt Auth Sanctum Manually (pnpm) Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/getting-started/installation Adds nuxt-auth-sanctum as a development dependency to your Nuxt.js project using pnpm. ```bash pnpm add -D nuxt-auth-sanctum ``` -------------------------------- ### Install Nuxt Auth Sanctum Manually (npm) Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/getting-started/installation Adds nuxt-auth-sanctum as a development dependency to your Nuxt.js project using npm. ```bash npm install --save-dev nuxt-auth-sanctum ``` -------------------------------- ### Install Nuxt Auth Sanctum Manually (yarn) Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/getting-started/installation Adds nuxt-auth-sanctum as a development dependency to your Nuxt.js project using yarn. ```bash yarn add --dev nuxt-auth-sanctum ``` -------------------------------- ### Token Authentication Login Example Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/token-authentication Demonstrates how to authenticate a user using token-based authentication by submitting credentials to the login endpoint. It utilizes the `useSanctumAuth` composable to initiate the login process. ```javascript const { login } = useSanctumAuth() const credentials = { email: "john@doe.com", password: "password", remember: true, } await login(credentials) ``` -------------------------------- ### Sanctum Request/Response Hooks Plugin Example Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced Example Nuxt plugin demonstrating how to hook into `sanctum:request` and `sanctum:response` events for logging. It uses `defineNuxtPlugin` and provides access to the Nuxt app instance, fetch context, and a logger. ```TypeScript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (app, ctx, logger) => { logger.info('Sanctum request hook triggered', ctx.request) }) nuxtApp.hook('sanctum:response', (app, ctx, logger) => { logger.info('Sanctum response hook triggered', ctx.request) }) }) ``` -------------------------------- ### Sanctum Request/Response Hooks Plugin Example Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/interceptors Example Nuxt plugin demonstrating how to hook into `sanctum:request` and `sanctum:response` events for logging. It uses `defineNuxtPlugin` and provides access to the Nuxt app instance, fetch context, and a logger. ```TypeScript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (app, ctx, logger) => { logger.info('Sanctum request hook triggered', ctx.request) }) nuxtApp.hook('sanctum:response', (app, ctx, logger) => { logger.info('Sanctum response hook triggered', ctx.request) }) }) ``` -------------------------------- ### Hooks: sanctum:init Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Fired when the Sanctum module is initialized within the Nuxt application. This hook is useful for performing setup tasks or accessing initial module configurations. ```javascript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { // ... hooks: { 'sanctum:init': (config) => { console.log('Nuxt Auth Sanctum module initialized with config:', config); // Example: Perform some initial setup based on config } } } }); ``` -------------------------------- ### Hooks: sanctum:init Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Fired when the Sanctum module is initialized within the Nuxt application. This hook is useful for performing setup tasks or accessing initial module configurations. ```javascript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { // ... hooks: { 'sanctum:init': (config) => { console.log('Nuxt Auth Sanctum module initialized with config:', config); // Example: Perform some initial setup based on config } } } }); ``` -------------------------------- ### Nuxt Configuration for Sanctum Module Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Configures the nuxt-auth-sanctum module within your Nuxt application's configuration file. This example sets the required `baseUrl` for your Laravel API. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { baseUrl: 'http://localhost:80' // Laravel API } }); ``` -------------------------------- ### Nuxt Auth Sanctum Module Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration This example demonstrates a complete configuration object for the Nuxt Auth Sanctum module. It includes settings for authentication mode, user state management, redirect behaviors, API endpoints, CSRF protection, client request options, and global middleware. ```javascript sanctum: { mode: 'cookie', userStateKey: 'sanctum.user.identity', redirectIfAuthenticated: false, redirectIfUnauthenticated: false, endpoints: { csrf: '/sanctum/csrf-cookie', login: '/login', logout: '/logout', user: '/api/user', }, csrf: { cookie: 'XSRF-TOKEN', header: 'X-XSRF-TOKEN', }, client: { retry: false, initialRequest: true, }, redirect: { keepRequestedRoute: false, onLogin: '/', onLogout: '/', onAuthOnly: '/login', onGuestOnly: '/', }, globalMiddleware: { enabled: false, allow404WithoutAuth: true, }, logLevel: 3, appendPlugin: false, } ``` -------------------------------- ### Docker Configuration Example for Sanctum Base URL Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/troubleshooting Illustrates a docker-compose.yml snippet for a Laravel API, demonstrating how to expose the application via a domain name accessible from the Nuxt container. This is crucial for SSR requests to correctly resolve the API's base URL. ```yaml services: # ... other services php: build: context: . dockerfile: Dockerfile ports: - "8000:8000" volumes: - .:/var/www/html networks: - sail depends_on: - mysql - redis environment: # ... other env vars APP_URL: http://localhost:8000 SANCTUM_STATEFUL_DOMAINS: localhost:3000 FRONTEND_URL: http://localhost:3000 networks: sail: driver: bridge ``` -------------------------------- ### Nuxt Configuration for Sanctum Module Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Configures the nuxt-auth-sanctum module within your Nuxt application's configuration file. This example sets the required `baseUrl` for your Laravel API. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { baseUrl: 'http://localhost:80' // Laravel API } }); ``` -------------------------------- ### Nuxt Auth Sanctum Module Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage This example demonstrates a complete configuration object for the Nuxt Auth Sanctum module. It includes settings for authentication mode, user state management, redirect behaviors, API endpoints, CSRF protection, client request options, and global middleware. ```javascript sanctum: { mode: 'cookie', userStateKey: 'sanctum.user.identity', redirectIfAuthenticated: false, redirectIfUnauthenticated: false, endpoints: { csrf: '/sanctum/csrf-cookie', login: '/login', logout: '/logout', user: '/api/user', }, csrf: { cookie: 'XSRF-TOKEN', header: 'X-XSRF-TOKEN', }, client: { retry: false, initialRequest: true, }, redirect: { keepRequestedRoute: false, onLogin: '/', onLogout: '/', onAuthOnly: '/login', onGuestOnly: '/', }, globalMiddleware: { enabled: false, allow404WithoutAuth: true, }, logLevel: 3, appendPlugin: false, } ``` -------------------------------- ### Sanctum Request Hook Example Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/hooks/sanctum-request Demonstrates how to subscribe to the `sanctum:request` hook to intercept and react to outgoing requests made to the Laravel API. This hook is analogous to ofetch interceptors and provides access to the request context and a logger instance. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (nuxtApp, context, logger) => { logger.info('Sanctum request hook triggered', context.request) }) }) ``` -------------------------------- ### Sanctum Request Hook Example Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/hooks Demonstrates how to subscribe to the `sanctum:request` hook to intercept and react to outgoing requests made to the Laravel API. This hook is analogous to ofetch interceptors and provides access to the request context and a logger instance. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (nuxtApp, context, logger) => { logger.info('Sanctum request hook triggered', context.request) }) }) ``` -------------------------------- ### Sanctum Response Hook Example Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/hooks/sanctum-response Demonstrates how to subscribe to the 'sanctum:response' hook to react to responses received from the Laravel API. This hook allows custom logic execution on API responses, similar to ofetch interceptors. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:response', (nuxtApp, context, logger) => { logger.info('Sanctum response hook triggered', context.request) }) }) ``` -------------------------------- ### Define LocalStorage Token Handler Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/token-storage Example of creating a custom `TokenStorage` handler using browser `localStorage` for storing authentication tokens. This handler includes checks for server-side rendering (SSR) to prevent errors. ```typescript // LocalStorage example for Laravel Authentication token const tokenStorageKey = 'sanctum.storage.token'; const localTokenStorage: TokenStorage = { get: async () => { if (import.meta.server) { return undefined; } return window.localStorage.getItem(tokenStorageKey) ?? undefined; }, set: async (app: NuxtApp, token?: string) => { if (import.meta.server) { return; } if (!token) { window.localStorage.removeItem(tokenStorageKey); return; } window.localStorage.setItem(tokenStorageKey, token); }, }; export default defineAppConfig({ sanctum: { tokenStorage: localTokenStorage, }, }); ``` -------------------------------- ### Get Nuxt Auth Sanctum Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/composables/usesanctumconfig The `useSanctumConfig` composable provides direct access to the module's runtime configuration. This simplifies retrieving settings like `baseUrl` compared to navigating `useRuntimeConfig` and multiple keys. ```javascript const config = useSanctumConfig(); console.log(config.baseUrl); ``` -------------------------------- ### CORS Policy Error Example Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/troubleshooting Demonstrates a typical CORS error message encountered when a Nuxt application's origin does not match the allowed origins configured in Laravel's CORS settings. This often requires adjusting `FRONTEND_URL` or `allowed_origins`. ```http Access to fetch at 'X' from origin 'Y' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'Z' that is not equal to the supplied origin. ``` -------------------------------- ### Nuxt SSR API User Fetch Failure (No Response) Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/troubleshooting An example of an error message indicating that Nuxt's server-side rendering could not reach the Laravel API endpoint for user identity. This suggests network issues, incorrect URLs, or port misconfigurations. ```bash [nuxt-auth-sanctum:ssr] ERROR Unable to load user identity from API [GET] "https://laravel.test/api/user": fetch failed ``` -------------------------------- ### Breeze Nuxt Template Overview Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/breeze-nuxt-template Introduction to a Nuxt application template built for Laravel Sanctum API backend, featuring pre-implemented authentication logic and common pages like Landing, Login, Sign up, Password Reset, and Dashboard. It leverages Nuxt UI for building interfaces. ```markdown Quick introduction to application template based on Nuxt for Laravel Sanctum API backend. Suppose you want to start a fresh project based on Nuxt and Laravel Sanctum with the Breeze API kit. In that case, you may consider trying out the template repository that has implemented all authentication logic and contains several pages such as: * Landing * Login * Sign up * Password reset * Dashboard The repository is available here - [breeze-nuxt](https://github.com/manchenkoff/breeze-nuxt), follow the guide in `readme.md` to set up Laravel API and connect it to the front-end application. Also, it uses the Nuxt UI module that allows you to start building complex interfaces with ease thanks to predefined components and Tailwind CSS. For more details, check the repository. As for the backend API part, we have you covered as well - check our [breeze-api](https://github.com/manchenkoff/breeze-api) template. ``` -------------------------------- ### Nuxt Auth Sanctum Configuration Parameters Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Lists and describes the available configuration parameters for the Nuxt Auth Sanctum module, covering API endpoints, authentication modes, redirects, and client/server settings. ```APIDOC NuxtAuthSanctumConfiguration: baseUrl: string The base URL of the Laravel API. Default: undefined mode: "cookie" | "token" Authentication mode to work with Laravel API. Supported values - `cookie`, `token`. Default: "cookie" origin: string The URL of the current application to use in Referrer header. Default: `useRequestUrl().origin` userStateKey: string The key to use to store the user identity in the `useState` variable. Default: "sanctum.user.identity" redirectIfAuthenticated: boolean Determine whether to redirect the user if it is already authenticated on a login attempt. Default: false redirectIfUnauthenticated: boolean Determine whether to redirect when the user got unauthenticated on any API request. Default: false endpoints: csrf: string The endpoint to request a new CSRF token. Default: "/sanctum/csrf-cookie" login: string The endpoint to send user credentials to authenticate. Default: "/login" logout: string The endpoint to destroy current user session. Default: "/logout" user: string The endpoint to fetch current user data. Default: "/api/user" csrf: cookie: string Name of the CSRF cookie to extract from server response. Default: "XSRF-TOKEN" header: string Name of the CSRF header to pass from client to server. Default: "X-XSRF-TOKEN" client: retry: false | number The number of times to retry a request when it fails. Default: false initialRequest: boolean Determines whether to request the user identity on plugin initialization. Default: true redirect: keepRequestedRoute: boolean Determines whether to keep the requested route when redirecting after login. Default: false onLogin: string | false Route to redirect to when user is authenticated. If set to false, do nothing. Default: "/" onLogout: string | false Route to redirect to when user is not authenticated. If set to false, do nothing. Default: "/" onAuthOnly: string | false Route to redirect to when user has to be authenticated. If set to false, do nothing. Default: "/login" onGuestOnly: string | false Route to redirect to when user has to be a guest. If set to false, do nothing. Default: "/" globalMiddleware: enabled: boolean Determines whether the global middleware is enabled. Default: false prepend: boolean Determines whether to allow 404 pages without authentication. Default: false allow404WithoutAuth: boolean Determines whether to allow 404 page without authentication. Default: true logLevel: number The level to use for the logger. More details [here](/nuxt-auth-sanctum/advanced/logging). Default: 3 appendPlugin: boolean Determines whether to append the plugin to the Nuxt application. More details [here](https://nuxt.com/docs/api/kit/plugins#options). Default: false serverProxy: enabled: boolean Determines whether the server side proxy is enabled. Available on server-side only. Default: false route: string Nuxt server route to catch all requests. This route will receive any nested path as well. Available on server-side only. Default: "/api/sanctum" baseUrl: string The base URL of the Laravel API. Available on server-side only. Default: "http://localhost:80" ``` -------------------------------- ### Nuxt Auth Sanctum Configuration Parameters Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Lists and describes the available configuration parameters for the Nuxt Auth Sanctum module, covering API endpoints, authentication modes, redirects, and client/server settings. ```APIDOC NuxtAuthSanctumConfiguration: baseUrl: string The base URL of the Laravel API. Default: undefined mode: "cookie" | "token" Authentication mode to work with Laravel API. Supported values - `cookie`, `token`. Default: "cookie" origin: string The URL of the current application to use in Referrer header. Default: `useRequestUrl().origin` userStateKey: string The key to use to store the user identity in the `useState` variable. Default: "sanctum.user.identity" redirectIfAuthenticated: boolean Determine whether to redirect the user if it is already authenticated on a login attempt. Default: false redirectIfUnauthenticated: boolean Determine whether to redirect when the user got unauthenticated on any API request. Default: false endpoints: csrf: string The endpoint to request a new CSRF token. Default: "/sanctum/csrf-cookie" login: string The endpoint to send user credentials to authenticate. Default: "/login" logout: string The endpoint to destroy current user session. Default: "/logout" user: string The endpoint to fetch current user data. Default: "/api/user" csrf: cookie: string Name of the CSRF cookie to extract from server response. Default: "XSRF-TOKEN" header: string Name of the CSRF header to pass from client to server. Default: "X-XSRF-TOKEN" client: retry: false | number The number of times to retry a request when it fails. Default: false initialRequest: boolean Determines whether to request the user identity on plugin initialization. Default: true redirect: keepRequestedRoute: boolean Determines whether to keep the requested route when redirecting after login. Default: false onLogin: string | false Route to redirect to when user is authenticated. If set to false, do nothing. Default: "/" onLogout: string | false Route to redirect to when user is not authenticated. If set to false, do nothing. Default: "/" onAuthOnly: string | false Route to redirect to when user has to be authenticated. If set to false, do nothing. Default: "/login" onGuestOnly: string | false Route to redirect to when user has to be a guest. If set to false, do nothing. Default: "/" globalMiddleware: enabled: boolean Determines whether the global middleware is enabled. Default: false prepend: boolean Determines whether to allow 404 pages without authentication. Default: false allow404WithoutAuth: boolean Determines whether to allow 404 page without authentication. Default: true logLevel: number The level to use for the logger. More details [here](/nuxt-auth-sanctum/advanced/logging). Default: 3 appendPlugin: boolean Determines whether to append the plugin to the Nuxt application. More details [here](https://nuxt.com/docs/api/kit/plugins#options). Default: false serverProxy: enabled: boolean Determines whether the server side proxy is enabled. Available on server-side only. Default: false route: string Nuxt server route to catch all requests. This route will receive any nested path as well. Available on server-side only. Default: "/api/sanctum" baseUrl: string The base URL of the Laravel API. Available on server-side only. Default: "http://localhost:80" ``` -------------------------------- ### Nuxt Auth Sanctum Middleware Usage Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/middleware Example of applying the 'sanctum:auth' middleware to a Nuxt.js page to protect it for authenticated users only. If the user is not authenticated, they will be redirected based on the module's configuration. ```vue ``` -------------------------------- ### Nuxt Auth Sanctum RuntimeConfig Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Shows how to expose module configuration, specifically the base API URL, through Nuxt's runtimeConfig public property. ```javascript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], runtimeConfig: { public: { sanctum: { baseUrl: 'http://localhost:80', }, }, }, }); ``` -------------------------------- ### Nuxt Auth Sanctum Middleware Usage Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/middleware/sanctum-auth Example of applying the 'sanctum:auth' middleware to a Nuxt.js page to protect it for authenticated users only. If the user is not authenticated, they will be redirected based on the module's configuration. ```vue ``` -------------------------------- ### Nuxt Auth Sanctum RuntimeConfig Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Shows how to expose module configuration, specifically the base API URL, through Nuxt's runtimeConfig public property. ```javascript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], runtimeConfig: { public: { sanctum: { baseUrl: 'http://localhost:80', }, }, }, }); ``` -------------------------------- ### Basic useSanctumFetch Usage Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/composables/usesanctumfetch Demonstrates the basic usage of useSanctumFetch to fetch data from an API endpoint. ```javascript const { data, status, error, refresh } = await useSanctumFetch('/api/users'); ``` -------------------------------- ### Nuxt Auth Sanctum Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/getting-started Details on how to configure the Nuxt Auth Sanctum module, including API endpoints and authentication settings. ```APIDOC nuxt.config.ts: plugins: - '@manchenkoff/nuxt-auth-sanctum' authSanctum: # Base URL for your Laravel API apiURL: 'http://localhost:8000' # Endpoint for login (relative to apiURL) login: '/api/auth/login' # Endpoint for logout logout: '/api/auth/logout' # Endpoint for user registration register: '/api/auth/register' # Endpoint for refreshing user session refresh: '/api/auth/refresh' # Key for CSRF token in cookies csrfCookie: 'XSRF-TOKEN' # Key for Bearer token in headers tokenHeader: 'Authorization' # Prefix for Bearer token (e.g., 'Bearer ') tokenPrefix: 'Bearer ' # Whether to auto-refresh the token on startup autoRefresh: true # How often to refresh the token (in milliseconds) refreshInterval: 300000 # Middleware configuration middleware: global: true # Apply auth middleware globally # Or specify routes: # routes: ['/admin', '/profile'] # Interceptor configuration interceptors: request: true response: true errorResponse: true errorRequest: true # Other options like redirect paths, etc. ``` -------------------------------- ### Subscribe to sanctum:error:response Hook in Nuxt.js Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/hooks/sanctum-error-response This snippet demonstrates how to subscribe to the 'sanctum:error:response' hook within a Nuxt.js plugin. It logs any error response received from the Laravel API, providing a starting point for custom error handling logic. ```javascript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:error:respnse', (response) => { console.log('Sanctum error hook triggered', response) }) }) ``` -------------------------------- ### useSanctumClient Composable Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Provides a pre-configured HTTP client instance, typically using Nuxt's `$fetch` or a similar mechanism, ready to make authenticated requests to your Laravel API. ```javascript // Example usage in a Nuxt page or component import { useSanctumClient } from '#imports'; const client = useSanctumClient(); async function fetchUserData() { try { const response = await client('/api/user'); console.log('User data from API:', response); } catch (error) { console.error('Error fetching user data:', error); } } ``` -------------------------------- ### Nuxt Plugin Registration Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/plugin-dependencies Explains how to configure the Sanctum module's plugin loading order using the `sanctum.appendPlugin` option to ensure it loads after other modules. ```nuxt // In nuxt.config.ts export default defineNuxtConfig({ modules: [ // ... ['nuxt-auth-sanctum', { // Set to true to append the plugin instead of prepending // This ensures it loads after other modules. appendPlugin: true }] ] }) ``` -------------------------------- ### Handle API Errors in Login Form (Vue) Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/error-handling This example shows how to integrate the `useApiError` composable within a Vue component's `try...catch` block. It specifically checks for validation errors to display them to the user via `form.setErrors` or logs other server errors. ```vue try { await login(credentials); } catch (e) { const error = useApiError(e); if (error.isValidationError) { form.setErrors(error.bag); return; } console.error('Request failed not because of a validation', error.code); } ``` -------------------------------- ### Nuxt Auth Sanctum Module Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Demonstrates how to configure the nuxt-auth-sanctum module within the nuxt.config.ts file, including setting the base API URL and custom redirect routes. ```javascript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { baseUrl: 'http://localhost:80', // Your Laravel API redirect: { onLogin: '/dashboard', // Custom route after successful login }, }, }); ``` -------------------------------- ### Nuxt Auth Sanctum Composables Overview Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/composables/usesanctumappconfig This section lists the available composables provided by the Nuxt Auth Sanctum module. These composables offer utilities for managing authentication state, fetching data, and interacting with the Sanctum backend. ```APIDOC Composables: - useSanctumAuth: Manages authentication state and provides authentication-related methods. - useSanctumUser: Provides access to the currently authenticated user's data. - useSanctumClient: Offers a client instance for making authenticated requests. - useSanctumFetch: A wrapper around Nuxt's fetch for authenticated API calls. - useLazySanctumFetch: Similar to useSanctumFetch but for lazy loading data. - useSanctumConfig: Accesses the module's configuration directly. - useSanctumAppConfig: Provides quick access to the module configuration via `useAppConfig().sanctum`. ``` -------------------------------- ### Token Storage Interface (APIDOC) Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/token-storage Defines the interface for custom token storage mechanisms within the Nuxt Auth Sanctum module. This interface is used when the Sanctum mode is set to 'token' to manage the persistence of authentication tokens. By default, cookies are used if no custom storage is provided. The interface includes methods to get and set the token, interacting with the Nuxt application instance. ```APIDOC /** * Handlers to work with authentication token. */ export interface TokenStorage { /** * Function to load a token from the storage. * @param app The Nuxt application instance. * @returns A promise that resolves with the stored token string or undefined if not found. */ get: (app: NuxtApp) => Promise; /** * Function to save a token to the storage. * @param app The Nuxt application instance. * @param token The token string to save, or undefined to clear the token. * @returns A promise that resolves when the token is saved. */ set: (app: NuxtApp, token?: string) => Promise; } // Usage Context: // Storage is used only when `sanctum.mode` equals to `token`. // By default, if there is no custom token storage defined, cookies will be used. // The module passes the token from the response to the `set` method and the current Nuxt application instance. // Before each request against the API, the module loads the token by calling `get` method. ``` -------------------------------- ### Nuxt Authentication Initialization Warning (401) Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/troubleshooting A common warning indicating that the user is not authenticated during plugin initialization, often due to missing 'set-cookie' headers. This points to a misconfiguration in Laravel's `SANCTUM_STATEFUL_DOMAINS`. ```bash [nuxt-auth-sanctum:ssr] WARN [response] set-cookie header is missing [nuxt-auth-sanctum:ssr] ⚙ User is not authenticated on plugin initialization, status: 401 ``` -------------------------------- ### Configure Nuxt Auth Sanctum Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/getting-started/installation Sets the base URL for the Laravel API in the nuxt.config.ts file, which is a required configuration for the module. ```typescript export default defineNuxtConfig({ // ... // nuxt-auth-sanctum options (also configurable via environment variables) sanctum: { baseUrl: 'http://localhost:80', // Laravel API }, }); ``` -------------------------------- ### useSanctumClient Composable Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Provides a pre-configured HTTP client instance, typically using Nuxt's `$fetch` or a similar mechanism, ready to make authenticated requests to your Laravel API. ```javascript // Example usage in a Nuxt page or component import { useSanctumClient } from '#imports'; const client = useSanctumClient(); async function fetchUserData() { try { const response = await client('/api/user'); console.log('User data from API:', response); } catch (error) { console.error('Error fetching user data:', error); } } ``` -------------------------------- ### Nuxt Auth Sanctum Module Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Demonstrates how to configure the nuxt-auth-sanctum module within the nuxt.config.ts file, including setting the base API URL and custom redirect routes. ```javascript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { baseUrl: 'http://localhost:80', // Your Laravel API redirect: { onLogin: '/dashboard', // Custom route after successful login }, }, }); ``` -------------------------------- ### Nuxt Auth Sanctum Composables Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/token-authentication Provides an overview of the core composables offered by the Nuxt Auth Sanctum module for managing authentication state and performing authenticated requests. ```APIDOC useSanctumAuth: Description: Provides access to authentication methods like login, logout, and checking authentication status. Methods: login(credentials): Authenticates the user with provided credentials. logout(): Logs out the current user. check(): Returns a boolean indicating if the user is authenticated. user(): Returns the authenticated user object or null. useSanctumUser: Description: Provides reactive access to the authenticated user's data. Returns: A ref containing the user object or null. useSanctumClient: Description: Provides a pre-configured Axios instance for making authenticated requests to the Sanctum backend. Usage: Use this client for custom API calls that require Sanctum authentication. useSanctumFetch: Description: A wrapper around Nuxt's useFetch composable that automatically includes Sanctum authentication credentials (cookies or tokens) in requests. Usage: Use this for fetching data that requires authentication. useLazySanctumFetch: Description: Similar to useSanctumFetch but provides lazy loading capabilities for data fetching. Usage: Use for fetching data that can be loaded asynchronously. useSanctumConfig: Description: Allows access to the module's configuration options within your Nuxt application. Usage: Retrieve configuration values like API endpoints or authentication modes. useSanctumAppConfig: Description: Provides access to Nuxt's app configuration, potentially useful for dynamic settings related to authentication. Usage: Access application-level configuration. ``` -------------------------------- ### Nuxt Configuration for Logging Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/advanced/troubleshooting Enables detailed logging in nuxt.config.ts to help diagnose issues. Setting logLevel to 5 provides more verbose output in both server and browser consoles. ```typescript export default defineNuxtConfig({ modules: [ '@nuxtjs/auth-next' ], auth: { // ... other auth config logLevel: 5 } }) ``` -------------------------------- ### Nuxt Auth Sanctum Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/index Details on how to configure the Nuxt Auth Sanctum module, including API endpoints and authentication settings. ```APIDOC nuxt.config.ts: plugins: - '@manchenkoff/nuxt-auth-sanctum' authSanctum: # Base URL for your Laravel API apiURL: 'http://localhost:8000' # Endpoint for login (relative to apiURL) login: '/api/auth/login' # Endpoint for logout logout: '/api/auth/logout' # Endpoint for user registration register: '/api/auth/register' # Endpoint for refreshing user session refresh: '/api/auth/refresh' # Key for CSRF token in cookies csrfCookie: 'XSRF-TOKEN' # Key for Bearer token in headers tokenHeader: 'Authorization' # Prefix for Bearer token (e.g., 'Bearer ') tokenPrefix: 'Bearer ' # Whether to auto-refresh the token on startup autoRefresh: true # How often to refresh the token (in milliseconds) refreshInterval: 300000 # Middleware configuration middleware: global: true # Apply auth middleware globally # Or specify routes: # routes: ['/admin', '/profile'] # Interceptor configuration interceptors: request: true response: true errorResponse: true errorRequest: true # Other options like redirect paths, etc. ``` -------------------------------- ### useLazySanctumFetch Composable Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Similar to `useSanctumFetch`, but provides lazy loading capabilities. The request is not executed until the `useLazySanctumFetch` call is activated, often controlled by component lifecycle or other conditions. ```javascript // Example usage in a Nuxt page or component import { useLazySanctumFetch } from '#imports'; const { data, pending, error } = useLazySanctumFetch('/api/dashboard-data'); // The request will be made when the component mounts or when 'data' is accessed. // You can control execution with options like { immediate: false } ``` -------------------------------- ### Register Nuxt Auth Sanctum Module Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/getting-started/installation Manually registers the nuxt-auth-sanctum module in the 'modules' section of your nuxt.config.ts file. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], }); ``` -------------------------------- ### useLazySanctumFetch Composable Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Similar to `useSanctumFetch`, but provides lazy loading capabilities. The request is not executed until the `useLazySanctumFetch` call is activated, often controlled by component lifecycle or other conditions. ```javascript // Example usage in a Nuxt page or component import { useLazySanctumFetch } from '#imports'; const { data, pending, error } = useLazySanctumFetch('/api/dashboard-data'); // The request will be made when the component mounts or when 'data' is accessed. // You can control execution with options like { immediate: false } ``` -------------------------------- ### Sanctum Nuxt Composables API Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/hooks/sanctum-logout Lists the available composables provided by the Sanctum Nuxt module for managing authentication state and performing authenticated requests. These composables simplify interaction with Laravel Sanctum. ```APIDOC useSanctumAuth(): object - Provides authentication status and methods. useSanctumUser(): object - Returns the currently authenticated user data. useSanctumClient(): object - Provides a client instance for making Sanctum API requests. useSanctumFetch(): object - A wrapper around Nuxt's fetch for authenticated requests. useLazySanctumFetch(): object - A lazy version of useSanctumFetch for deferred requests. useSanctumConfig(): object - Accesses the module's configuration settings. useSanctumAppConfig(): object - Accesses application configuration related to Sanctum. ``` -------------------------------- ### useSanctumFetch Composable Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage A wrapper around Nuxt's `useFetch` that automatically includes authentication credentials (like cookies) for requests made to your Laravel API. It simplifies authenticated data fetching. ```javascript // Example usage in a Nuxt page or component import { useSanctumFetch } from '#imports'; async function getPosts() { const { data, pending, error } = await useSanctumFetch('/api/posts'); if (error.value) { console.error('Error fetching posts:', error.value); } if (data.value) { console.log('Posts:', data.value); } } ``` -------------------------------- ### Advanced useSanctumFetch Usage with Options Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/composables/usesanctumfetch Shows how to use useSanctumFetch with custom request options like HTTP method and query parameters, along with AsyncDataOptions to pick specific data fields. ```javascript const { data, status, error, refresh } = await useSanctumFetch( '/api/users', { method: 'GET', query: { is_active: true, }, }, { pick: ['id'], }, ); ``` -------------------------------- ### useSanctumFetch Composable Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration A wrapper around Nuxt's `useFetch` that automatically includes authentication credentials (like cookies) for requests made to your Laravel API. It simplifies authenticated data fetching. ```javascript // Example usage in a Nuxt page or component import { useSanctumFetch } from '#imports'; async function getPosts() { const { data, pending, error } = await useSanctumFetch('/api/posts'); if (error.value) { console.error('Error fetching posts:', error.value); } if (data.value) { console.log('Posts:', data.value); } } ``` -------------------------------- ### Nuxt Auth Sanctum Environment Variable Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Illustrates how to override module options, such as the base API URL, using environment variables, commonly defined in a .env file. ```dotenv NUXT_PUBLIC_SANCTUM_BASE_URL='http://localhost:80' ``` -------------------------------- ### Advanced: Error Handling Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage/configuration Details strategies for managing errors that occur during API communication. This covers handling network errors, server-side errors, and application-level errors gracefully. ```APIDOC Error Handling: Overview: Comprehensive strategies for managing API-related errors in Nuxt applications. Mechanisms: 1. `sanctum:error:request` Hook: Catches errors during the request lifecycle (e.g., network issues, invalid configuration). 2. `sanctum:error:response` Hook: Catches errors returned by the API server (e.g., 4xx, 5xx status codes). 3. `useSanctumFetch` / `useSanctumClient` Error Handling: Use try-catch blocks or `.catch()` with promises for specific API calls. Key Practices: - Centralized Error Logging: Use hooks to log errors to a console or error tracking service. - User Feedback: Provide clear messages to the user for common errors (e.g., network unavailable, invalid credentials). - Error Transformation: Standardize error formats returned by the API. Example (Centralized Error Logging): sanctum: { hooks: { 'sanctum:error:request': (error) => { console.error('Request failed:', error.message); // Potentially trigger a global error notification return error; }, 'sanctum:error:response': (error) => { console.error('API Error:', error.response?.status, error.response?.data); // Handle specific status codes, e.g., redirect on 401 if (error.response?.status === 401) { // redirect to login } return error; } } } Related Composables: - `useSanctumFetch`: Provides `error` ref for immediate error access. - `useSanctumClient`: Returns a client instance that can be used with standard Promise error handling. ``` -------------------------------- ### Nuxt Auth Sanctum Environment Variable Configuration Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/usage Illustrates how to override module options, such as the base API URL, using environment variables, commonly defined in a .env file. ```dotenv NUXT_PUBLIC_SANCTUM_BASE_URL='http://localhost:80' ``` -------------------------------- ### Nuxt Auth Sanctum Advanced Features Source: https://manchenkoff.gitbook.io/nuxt-auth-sanctum/composables/usesanctumappconfig This section covers advanced topics for customizing and extending the Nuxt Auth Sanctum module, including interceptors, error handling, logging, token storage, and troubleshooting. ```APIDOC Advanced Topics: - Interceptors: Detailed configuration and usage of request/response interceptors. - Error handling: Strategies for managing and displaying API errors. - Logging: Options for enabling and configuring module logging. - Token storage: Methods for storing and retrieving authentication tokens. - Plugin dependencies: Understanding and managing dependencies with other Nuxt plugins. - Breeze Nuxt template: Specific guidance for integration with the Breeze Nuxt template. - Troubleshooting: Common issues and their solutions. ```