### Nuxt Configuration: Basic Setup Source: https://sanctum.manchenkoff.me/usage/configuration Configures the nuxt-auth-sanctum module with the essential baseUrl for the Laravel API. This is the minimum required configuration to start using the module. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { baseUrl: 'http://localhost:80', // Laravel API }, }) ``` -------------------------------- ### Install nuxt-auth-sanctum Module Source: https://sanctum.manchenkoff.me/getting-started/installation Installs the nuxt-auth-sanctum module using either nuxi or pnpm. This module facilitates authentication between Nuxt and Laravel Sanctum. ```bash npx nuxi@latest module add nuxt-auth-sanctum ``` ```bash pnpm add nuxt-auth-sanctum ``` -------------------------------- ### Install nuxt-auth-sanctum Module Source: https://sanctum.manchenkoff.me/index This command installs the nuxt-auth-sanctum module using nuxi, the Nuxt 3 CLI. It's the primary step to integrate Laravel Sanctum authentication into your Nuxt application. ```bash npx nuxi@latest module add nuxt-auth-sanctum ``` -------------------------------- ### useSanctumFetch Usage Source: https://sanctum.manchenkoff.me/composables/usesanctumfetch Demonstrates basic and advanced usage of the useSanctumFetch composable for making GET requests to a Laravel API. ```APIDOC ## useSanctumFetch ### Description The `useSanctumFetch` composable provides a convenient way to make authenticated API requests from your Nuxt application to a Laravel backend protected by Sanctum. It wraps Nuxt's `useFetch` and `useAsyncData` with Sanctum-specific configurations. ### Method GET (default, can be overridden) ### Endpoint `/api/users` (example) ### Parameters #### Path Parameters None #### Query Parameters - **query** (object) - Optional - Key-value pairs to be appended as query parameters to the URL. #### Request Body Not applicable for default GET requests. ### Request Example ```javascript // Basic usage const { data, status, error, refresh } = await useSanctumFetch('/api/users') // With options (method, query parameters) const { data, status, error, refresh } = await useSanctumFetch( '/api/users', { method: 'GET', query: { is_active: true, }, }, { // AsyncDataOptions pick: ['id'], }, 'my-request-key' // optional request key ) ``` ### Response #### Success Response (200) - **data** (any) - The data returned from the API. - **status** (string) - The status of the fetch request ('pending', 'success', 'error'). - **error** (object) - Any error encountered during the fetch. - **refresh** (function) - A function to manually refetch the data. #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ``` ## Type Casting ### Description Allows you to cast the response data to a specific TypeScript interface for better type safety. ### Request Example ```javascript interface MyResponse { name: string } const { data } = await useSanctumFetch('/api/endpoint') // Accessing data with type safety const name = data.value.name ``` ## Reactive Parameters ### Description Enables the use of reactive references for query parameters, automatically refetching data when the referenced values change. ### Request Example ```javascript const page = ref(1) const { data } = await useSanctumFetch( '/api/posts', () => ({ params: { page: page.value, // reactive value } }), { watch: [page], }, ) ``` ## Reactive URL/Key ### Description Allows for reactive URLs or request keys, ensuring that the API is called with updated parameters whenever these reactive references change. ### Request Example ```javascript const currentUser = ref(1) const userUrl = computed(() => `/api/users/${currentUser.value}`) const { data } = await useSanctumFetch( userUrl, { // request params if needed }, { // async params if needed }, userUrl // reactive key ) ``` ``` -------------------------------- ### Nuxt Auth Middleware Example (sanctum:auth) Source: https://sanctum.manchenkoff.me/middleware/sanctum-auth This example demonstrates how to protect a Nuxt.js page from unauthenticated users using the 'sanctum:auth' middleware. If a user is not authenticated, they will be redirected to the login page. The middleware can also be configured to remember the requested route and redirect the user back after successful authentication. ```vue ``` -------------------------------- ### Nuxt Configuration: Overriding Options Source: https://sanctum.manchenkoff.me/usage/configuration Demonstrates how to override default module options in the Nuxt configuration file. This example shows how to change the redirect route after a successful login. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { baseUrl: 'http://localhost:80', // Your Laravel API redirect: { onLogin: '/dashboard', // Custom route after successful login }, }, }) ``` -------------------------------- ### Access Nuxt Sanctum Configuration with useSanctumConfig Source: https://sanctum.manchenkoff.me/composables/usesanctumconfig The `useSanctumConfig` composable simplifies retrieving the module's configuration by directly accessing runtime configuration values related to Sanctum. It avoids the need to manually navigate through `useRuntimeConfig` and multiple keys. The example shows how to get the `baseUrl` from the configuration. ```javascript const config = useSanctumConfig(); console.log(config.baseUrl); // runtimeConfig.public.sanctum.baseUrl ``` -------------------------------- ### Retrieve Sanctum Module Configuration using useSanctumConfig (Vue/Nuxt) Source: https://sanctum.manchenkoff.me/composables/usesanctumappconfig This composable allows retrieval of the Sanctum module's specific configuration settings. It simplifies accessing configuration values related to Sanctum. No specific usage example is provided in the text, but it's intended for configuration access. -------------------------------- ### Laravel API Routes Configuration Source: https://sanctum.manchenkoff.me/usage/token Example of how to define login and logout endpoints in Laravel's `api.php` routes file for Sanctum token authentication. ```APIDOC ## Laravel API Routes Example ### Description This example shows the typical setup for Sanctum token authentication endpoints within your Laravel application's `routes/api.php` file. ### Routes ```php post('/login', [TokenAuthenticationController::class, 'store']); // Protected logout route for authenticated users Route::middleware(['auth:sanctum'])->post('/logout', [TokenAuthenticationController::class, 'destroy']); ``` ### Notes - Ensure the login endpoint is accessible to guests (`middleware(['guest'])`). - The logout endpoint requires authentication (`middleware(['auth:sanctum'])`). - Avoid using the same endpoints as cookie-based authentication (`web.php`) to prevent CSRF token mismatches. ``` -------------------------------- ### Custom LocalStorage Token Storage Implementation Source: https://sanctum.manchenkoff.me/advanced/token-storage Provides an example of a custom token storage implementation using browser's localStorage for Laravel authentication tokens. This handler defines 'get' and 'set' functions to interact with localStorage, ensuring it's only used on the client-side. ```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, }, }) ``` -------------------------------- ### Retrieve Sanctum App Configuration using useSanctumAppConfig (Vue/Nuxt) Source: https://sanctum.manchenkoff.me/composables/usesanctumappconfig This composable provides direct access to the Sanctum module's application configuration, simplifying retrieval compared to the general `useAppConfig()`. It takes no arguments and returns the Sanctum configuration object. Example usage shows accessing interceptor settings. ```javascript const config = useSanctumAppConfig(); console.log(config.interceptors.onRequest); // appConfig.sanctum.interceptors.onRequest ``` -------------------------------- ### Environment Variable Configuration Source: https://sanctum.manchenkoff.me/usage/configuration Overrides module options using environment variables, commonly defined in a .env file. This example shows how to set the Laravel API base URL using an environment variable. ```env NUXT_PUBLIC_SANCTUM_BASE_URL='http://localhost:80' ``` -------------------------------- ### Register nuxt-auth-sanctum Module in Nuxt Config Source: https://sanctum.manchenkoff.me/getting-started/installation Registers the nuxt-auth-sanctum module in your Nuxt application's configuration file (`nuxt.config.ts`). This step is necessary after installation. ```typescript export default defineNuxtConfig({ modules: [ // other modules 'nuxt-auth-sanctum' ], sanctum: {}, }) ``` -------------------------------- ### Token Authentication Setup Source: https://sanctum.manchenkoff.me/usage/token Configure Sanctum to use token-based authentication by updating the sanctum.mode configuration property to 'token'. This is useful for SPAs, mobile, or desktop applications where the client is not on the same TLD as the server. ```APIDOC ## Token Authentication Configuration ### Description Configure Sanctum to use token-based authentication. This is generally recommended for SPAs, mobile, or desktop applications. ### Configuration Set the `sanctum.mode` configuration property to `token`. ```javascript // nuxt.config.js or equivalent export default { // ... other configurations sanctum: { mode: 'token', // ... other sanctum options }, // ... } ``` ``` -------------------------------- ### Configure Sanctum Request and Response Interceptors in Nuxt Plugin Source: https://sanctum.manchenkoff.me/advanced/interceptors This example demonstrates how to set up custom request and response interceptors using Nuxt's plugin system. It utilizes the 'sanctum:request' and 'sanctum:response' hooks to log information about outgoing requests and incoming responses. The interceptors receive the Nuxt app instance, a FetchContext, and a Consola logger. This allows for centralized logging or modification of API interactions. ```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) }) }) ``` -------------------------------- ### TokenStorage Interface Definition Source: https://sanctum.manchenkoff.me/advanced/token-storage Defines the TypeScript interface for custom token storage handlers in Nuxt.js with Laravel Sanctum. It specifies the 'get' and 'set' methods required for managing the authentication token. ```typescript /** * Handlers to work with authentication token. */ export interface TokenStorage { /** * Function to load a token from the storage. */ get: (app: NuxtApp) => Promise /** * Function to save a token to the storage. */ set: (app: NuxtApp, token?: string) => Promise } ``` -------------------------------- ### Get Authenticated User with useSanctumUser (TypeScript) Source: https://sanctum.manchenkoff.me/composables/usesanctumuser The `useSanctumUser` composable retrieves the currently authenticated user. It supports generic types, allowing you to cast the user object to a custom interface. If no user is authenticated, it returns `null`. ```typescript interface MyCustomUser { id: number; login: string; custom_metadata: { group: string; role: string; }; } const user = useSanctumUser(); ``` -------------------------------- ### Integrating useApiError Composable in Nuxt for Validation Errors Source: https://sanctum.manchenkoff.me/advanced/error-handling This example demonstrates the practical application of the `useApiError` composable within a Nuxt `catch` block. It shows how to conditionally handle validation errors by setting form errors using the extracted `bag` and log other types of API request failures based on their status code. ```javascript 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) } ``` -------------------------------- ### Fetch data with useLazySanctumFetch in Nuxt.js Source: https://sanctum.manchenkoff.me/composables/uselazysanctumfetch Demonstrates how to use the `useLazySanctumFetch` composable to retrieve data from a Laravel API. It shows basic usage, options for method and query parameters, and how to provide default values for the response. This composable is a wrapper around Nuxt's `useFetch`/`useAsyncData` and Laravel Sanctum. ```javascript const { data, status, error, refresh } = await useLazySanctumFetch('/api/users') // or const { data, status, error, refresh } = await useLazySanctumFetch( '/api/users', { method: 'GET', query: { page: 1 } }, { default() { return { data: [], meta: { total: 0, per_page: 0 } } } }, 'my-request-key', ) ``` -------------------------------- ### Sanctum Init Hook Source: https://sanctum.manchenkoff.me/hooks/sanctum-redirect Subscribe to the `sanctum:init` hook to inject custom event handling during the Sanctum module's initialization. ```APIDOC ## Sanctum Init Hook ### Description Subscribe to the `sanctum:init` hook to inject custom event handling when the Sanctum module is initialized. This can be used for setting up initial configurations or performing actions upon module startup. ### Method Subscription to Hook ### Endpoint N/A (Client-side hook) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Example usage in a Nuxt plugin export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:init', () => { console.log('Sanctum module initialized.'); // Custom initialization logic here }); }); ``` ### Response #### Success Response N/A (Hook execution) #### Response Example N/A ``` -------------------------------- ### Manual Sanctum Identity Request with Dependencies (Nuxt) Source: https://sanctum.manchenkoff.me/advanced/dependencies This Nuxt plugin shows how to manually initialize the Sanctum authentication and control its dependencies. It disables the default initial request and instead calls `init()` within a custom plugin that explicitly depends on '@nuxtjs/i18n' and 'nuxt-auth-sanctum', ensuring proper loading order. ```typescript export default defineNuxtPlugin({ name: 'custom-auth', dependsOn: ['@nuxtjs/i18n', 'nuxt-auth-sanctum'], async setup() { // nuxtApp is implicitly available in setup nuxtApp.hook('sanctum:request', (app, ctx, logger) => { ctx .options .headers .set("X-Language", app.$i18n.localeProperties.value.code) }) const { init } = useSanctumAuth() await init() } }) ``` -------------------------------- ### Use useSanctumClient for Preconfigured Fetch Client (JavaScript) Source: https://sanctum.manchenkoff.me/composables/usesanctumclient Demonstrates how to initialize and use the `useSanctumClient` composable in Nuxt.js. This client is pre-configured with CSRF token headers and cookie management, simplifying API requests to a Laravel backend. It utilizes the `ofetch` library and supports standard asynchronous data fetching patterns. ```javascript const client = useSanctumClient(); const { data, status, error, refresh } = await useAsyncData('users', () => client('/api/users') ); ``` -------------------------------- ### Reactive parameters for useLazySanctumFetch in Nuxt.js Source: https://sanctum.manchenkoff.me/composables/uselazysanctumfetch Explains how to use reactive parameters, such as page numbers, with `useLazySanctumFetch`. By passing `SanctumFetchOptions` as a function and including reactive values in the query parameters, the fetch will automatically re-execute when the reactive dependencies change, ensuring up-to-date data. ```javascript const page = ref(1) const { data } = await useLazySanctumFetch( '/api/posts', () => ({ params: { page: page.value, // reactive value } }), { watch: [page], }, ) ``` -------------------------------- ### Subscribe to Sanctum Initialization Hook (TypeScript) Source: https://sanctum.manchenkoff.me/hooks/sanctum-init This snippet demonstrates how to subscribe to the `sanctum:init` hook in Nuxt.js. This hook is triggered after the initial user identity request is completed, allowing for custom logic execution. It's useful for ensuring middleware and redirects function correctly by running custom code post-initialization. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:init', () => { console.log('Sanctum init hook triggered') }) }) ``` -------------------------------- ### useSanctumAuth Composable Source: https://sanctum.manchenkoff.me/composables/usesanctumauth Explains the usage and functionalities of the `useSanctumAuth` composable for handling authentication state and actions. ```APIDOC ## useSanctumAuth Composable ### Description The `useSanctumAuth` composable provides a set of computed properties and methods to manage user authentication state and perform authentication-related actions within a Nuxt.js application when using Laravel Sanctum for backend authentication. ### Composable Properties & Methods * **`user`** (computed property): Retrieves the currently authenticated user's data. This is essentially the same as `useSanctumUser`. * **`isAuthenticated`** (computed property): A boolean flag indicating whether a user is currently authenticated. * **`login(credentials)`** (method): Initiates the user login process. Requires a `credentials` object containing user authentication details (e.g., email, password) as expected by the Laravel Sanctum backend. * **`logout()`** (method): Logs the user out of the application. * **`refreshIdentity()`** (method): Manually re-fetches the current authenticated user's data from the backend. * **`checkSession()`** (method): Validates the existence of a user session, checking for cookies in the browser or tokens in storage. ### Login Usage Example To authenticate a user, pass the credentials payload as an argument to the `login` method. The payload should include all fields required by your Laravel Sanctum backend. ```javascript const { login } = useSanctumAuth(); const userCredentials = { email: 'user@mail.com', password: '123123', }; await login(userCredentials); ``` If the login operation is successful, the `user` property will be updated with the current user information returned by the Laravel API. ### Default Sanctum Endpoints By default, the composable methods will use the following Laravel Sanctum endpoints: * **Login:** `/login` * **Logout:** `/logout` * **Get User:** `/api/user` * **CSRF Cookie:** `/sanctum/csrf-cookie` *Note: These default endpoints can be customized via the Configuration section (not detailed in this snippet).* ### Session Validation The `checkSession` method is used to validate the existence of the user's session. It checks for the presence of a valid session cookie in the browser or a token in the application's storage. ``` -------------------------------- ### Configure nuxt-auth-sanctum Base URL Source: https://sanctum.manchenkoff.me/getting-started/installation Configures the base URL for the Laravel API within the nuxt-auth-sanctum module settings in `nuxt.config.ts`. This allows the Nuxt app to communicate with the Laravel backend. ```typescript export default defineNuxtConfig({ //... other parts of the config // nuxt-auth-sanctum options (also configurable via environment variables) sanctum: { baseUrl: 'http://localhost:80', // Laravel API } }) ``` -------------------------------- ### sanctum:refresh Hook Source: https://sanctum.manchenkoff.me/hooks/sanctum-init The sanctum:refresh hook provides an entry point for custom event handling when the user's session is refreshed. ```APIDOC ## sanctum:refresh Hook ### Description This hook subscribes to the event that fires when the user's session is refreshed by the Sanctum module. It allows for custom actions to be performed when a session refresh occurs, such as updating UI elements or fetching fresh data. ### Method Custom Hook ### Endpoint N/A (Client-side Nuxt.js hook) ### Parameters None ### Request Example ```typescript // Example usage (actual implementation depends on your needs) export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:refresh', () => { console.log('Sanctum refresh hook triggered') // Custom session refresh handling logic }) }) ``` ### Response #### Success Response Enables custom logic execution upon session refresh. #### Response Example N/A ``` -------------------------------- ### Reactive URL/Key with useSanctumFetch (Nuxt.js) Source: https://sanctum.manchenkoff.me/composables/usesanctumfetch Illustrates how to use a reactive fetch key with `useSanctumFetch` to trigger requests when the key changes. This allows the URL or key to be dynamically updated, causing the composable to refetch data with the new parameters. ```javascript const currentUser = ref(1) const userUrl = computed(() => `/api/users/${currentUser}`) const { data } = await useSanctumFetch( userUrl, { // request params if needed }, { // async params if needed }, userUrl ) // If `currentUser` value changed, then the request will be made automatically. ``` -------------------------------- ### sanctum:init Hook Source: https://sanctum.manchenkoff.me/hooks/sanctum-init The sanctum:init hook is triggered once the initial user identity request has been completed. This is useful for injecting custom event handling after authentication status is established. ```APIDOC ## sanctum:init Hook ### Description This hook subscribes to the event that fires when the initial user identity request by the Sanctum module is completed. It allows for custom logic to be executed after the application has determined the user's authentication status. ### Method Custom Hook ### Endpoint N/A (Client-side Nuxt.js hook) ### Parameters None ### Request Example ```typescript // app/plugins/sanctum-listener.ts export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:init', () => { console.log('Sanctum init hook triggered') // Add custom event handling here }) }) ``` ### Response #### Success Response Triggers custom logic defined within the hook listener. #### Response Example N/A ``` -------------------------------- ### sanctum:redirect Hook Source: https://sanctum.manchenkoff.me/hooks/sanctum-init The sanctum:redirect hook allows for custom event handling when a redirect occurs during the Sanctum authentication flow. ```APIDOC ## sanctum:redirect Hook ### Description This hook subscribes to the event that fires when a redirect is initiated by the Sanctum module. It enables custom handling of redirect events, such as modifying redirect destinations or performing actions before redirection. ### Method Custom Hook ### Endpoint N/A (Client-side Nuxt.js hook) ### Parameters None ### Request Example ```typescript // Example usage (actual implementation depends on your needs) export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:redirect', () => { console.log('Sanctum redirect hook triggered') // Custom redirect handling logic }) }) ``` ### Response #### Success Response Allows execution of custom logic related to redirect events. #### Response Example N/A ``` -------------------------------- ### Handle Non-existing Routes with Global Middleware in Nuxt.js Source: https://sanctum.manchenkoff.me/middleware/global Configures Nuxt.js global middleware to redirect users to the `onAuthOnly` route when a non-existent route (404) is encountered, instead of displaying the default error page, by setting `allow404WithoutAuth: false`. ```typescript export default defineNuxtConfig({ modules: [ 'nuxt-auth-sanctum', ], sanctum: { baseUrl: 'http://localhost:80', redirect: { onAuthOnly: '/login', onGuestOnly: '/profile', }, globalMiddleware: { enabled: true, allow404WithoutAuth: false, }, } }) ``` -------------------------------- ### Login User with Credentials - Nuxt.js Source: https://sanctum.manchenkoff.me/usage/cookie This snippet demonstrates how to log in a user by sending their credentials to the login endpoint using the useSanctumAuth composable in Nuxt.js. It requires the 'useSanctumAuth' hook and accepts a credentials object as input. ```javascript const { login } = useSanctumAuth() const credentials = { email: "john@doe.com", password: "password", remember: true, } await login(credentials) ``` -------------------------------- ### Reactive Parameters with useSanctumFetch (Nuxt.js) Source: https://sanctum.manchenkoff.me/composables/usesanctumfetch Shows how to use reactive parameters with `useSanctumFetch` by passing `SanctumFetchOptions` as a function. This allows query parameters to be recalculated on new requests when reactive values change, automatically triggering refetches. ```javascript const page = ref(1) const { data } = await useSanctumFetch( '/api/posts', () => ({ params: { page: page.value, // reactive value } }), { watch: [page], }, ) // Once `page` value changes, the data will be refetched automatically. ``` -------------------------------- ### Configure Global Middleware in Nuxt.js Source: https://sanctum.manchenkoff.me/middleware/global Enables global middleware for Sanctum authentication in Nuxt.js by setting `globalMiddleware.enabled` to true in `nuxt.config.ts`. This configuration also defines base URL, redirection routes for authenticated and guest users, and can optionally prepend middleware. ```typescript export default defineNuxtConfig({ modules: [ 'nuxt-auth-sanctum' ], sanctum: { baseUrl: 'http://localhost:80', redirect: { onAuthOnly: '/login', onGuestOnly: '/profile', }, globalMiddleware: { enabled: true, }, } }) ``` -------------------------------- ### Use useSanctumFetch for API Data Fetching (Nuxt.js) Source: https://sanctum.manchenkoff.me/composables/usesanctumfetch Demonstrates how to use the `useSanctumFetch` composable to fetch data from a Laravel API. It mirrors the interface of `useFetch`/`useAsyncData` and accepts endpoint, Sanctum fetch options, async data options, and an optional request key. Type casting is supported for response interfaces. ```javascript const { data, status, error, refresh } = await useSanctumFetch('/api/users') // or const { data, status, error, refresh } = await useSanctumFetch( '/api/users', { method: 'GET', query: { is_active: true, }, }, { pick: ['id'], }, 'my-request-key', ) ``` ```javascript interface MyResponse { name: string } const { data } = await useSanctumFetch('/api/endpoint') const name = data.value.name // augmented by MyResponse interface ``` -------------------------------- ### Login User with useSanctumAuth in Nuxt.js Source: https://sanctum.manchenkoff.me/composables/usesanctumauth Demonstrates how to use the `login` method from the `useSanctumAuth` composable to authenticate a user. It requires user credentials as an argument and updates the `user` property upon successful login. The default login endpoint is `/login`. ```javascript const { login } = useSanctumAuth(); const userCredentials = { email: 'user@mail.com', password: '123123', }; await login(userCredentials); ``` -------------------------------- ### Nuxt.js RuntimeNuxtHooks Interface for Sanctum Events Source: https://sanctum.manchenkoff.me/hooks/sanctum-login This TypeScript interface defines the available hooks within the Nuxt.js runtime, specifically for Laravel Sanctum authentication events. It outlines the `sanctum:login` hook and its signature, which is a function that returns a `HookResult`. ```typescript interface RuntimeNuxtHooks { /** * Triggers when user successfully logs in. */ 'sanctum:login': () => HookResult } ``` -------------------------------- ### Nuxt.js Module Configuration (nuxt.config.ts) Source: https://sanctum.manchenkoff.me/usage/configuration This snippet shows a complete module configuration for 'nuxt-auth-sanctum' within a Nuxt.js application. It specifies the module to be used and details various Sanctum settings including authentication mode, endpoint paths, CSRF configuration, client behavior, redirection logic, and global middleware options. Dependencies include 'nuxt-auth-sanctum' and Nuxt.js. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], 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, } }) ``` -------------------------------- ### Reactive URL/key for useSanctumFetch in Nuxt.js Source: https://sanctum.manchenkoff.me/composables/uselazysanctumfetch Demonstrates how to make the URL or request key reactive when using `useSanctumFetch`. By providing computed properties or refs for the URL and/or key, the request will automatically re-trigger when these values change, enabling dynamic data fetching based on changing states. ```javascript const currentUser = ref(1) const userUrl = computed(() => `/api/users/${currentUser}`) const { data } = await useSanctumFetch( userUrl, { // request params if needed }, { // async params if needed }, userUrl ) ``` -------------------------------- ### Nuxt Configuration: RuntimeConfig Source: https://sanctum.manchenkoff.me/usage/configuration Exposes module configuration to Nuxt's runtimeConfig. This allows overriding Sanctum module settings via the `runtimeConfig.public.sanctum` property in `nuxt.config.ts`. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], runtimeConfig: { public: { sanctum: { baseUrl: 'http://localhost:80', }, }, }, }) ``` -------------------------------- ### Use useSanctumFetch with Server Proxy in Nuxt Source: https://sanctum.manchenkoff.me/usage/proxy Demonstrates how to make authenticated API requests from a Nuxt.js application using the `useSanctumFetch` composable when the server proxy is enabled. The Nuxt server route `/api/sanctum` is automatically stripped from the request URL before forwarding to the configured `serverProxy.baseUrl` in the Laravel backend. ```typescript // Request URL = http://frontend.dev/api/sanctum/user/profile // Actual URL = http://api.frontend.dev/user/profile const { data } = await useSanctumFetch('/user/profile') ``` -------------------------------- ### Configure Guest-Only Pages in Nuxt.js Source: https://sanctum.manchenkoff.me/middleware/global Allows configuring pages that should only be accessible to unauthenticated users in Nuxt.js by setting `sanctum.guestOnly: true` in `definePageMeta`. While global middleware still checks authentication, this meta-property defines guest-only routes. ```javascript definePageMeta({ sanctum: { guestOnly: true, } }) ``` -------------------------------- ### Enable Nuxt Server Proxy for Sanctum API Requests Source: https://sanctum.manchenkoff.me/usage/proxy Configures Nuxt.js to act as a server proxy for Laravel Sanctum API requests when Server-Side Rendering (SSR) is enabled. This forwards client requests to the Laravel API, preserving cookies and headers. It requires the 'nuxt-auth-sanctum' module and specific configuration in `nuxt.config.ts`. The `serverProxy.baseUrl` should point to your Laravel backend. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], ssr: true, sanctum: { baseUrl: '/api/sanctum', serverProxy: { enabled: true, route: '/api/sanctum', baseUrl: 'http://api.frontend.dev', }, }, }) ``` -------------------------------- ### Type casting response with useLazySanctumFetch in Nuxt.js Source: https://sanctum.manchenkoff.me/composables/uselazysanctumfetch Illustrates how to apply TypeScript type casting to the data fetched using `useLazySanctumFetch`. This allows for better type safety and autocompletion when working with the API response data, ensuring the data conforms to a defined interface. ```typescript interface MyResponse { name: string } const { data } = await useLazySanctumFetch('/api/endpoint') const name = data.value.name // augmented by MyResponse interface ``` -------------------------------- ### Sanctum Error Response Hook Source: https://sanctum.manchenkoff.me/hooks/sanctum-redirect Subscribe to the `sanctum:error:response` hook to handle custom error responses from Sanctum. ```APIDOC ## Sanctum Error Response Hook ### Description Subscribe to the `sanctum:error:response` hook to inject custom event handling for error responses. This allows you to process or log errors received from Sanctum before they are handled by default. ### Method Subscription to Hook ### Endpoint N/A (Client-side hook) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Example usage in a Nuxt plugin export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:error:response', (errorResponse) => { console.error('Sanctum error response:', errorResponse); // Custom error handling logic here }); }); ``` ### Response #### Success Response N/A (Hook execution) #### Response Example N/A ``` -------------------------------- ### Configure API Proxy Headers in Nuxt Source: https://sanctum.manchenkoff.me/advanced/troubleshooting This snippet demonstrates how to configure custom headers for API proxy requests within the Nuxt configuration file. Ensure that any headers required by your Laravel API are explicitly defined here. This is crucial when using `routeRules` for proxying requests, as Nuxt might not pass all headers by default. ```typescript export default defineNuxtConfig({ // ... other config routeRules: { '/backend/api/**': { proxy: { to: `http://laravel.test/api/**`, headers: { YOUR_HEADER: 'header_value' }, } } } }) ``` -------------------------------- ### Laravel API Routes for Sanctum Token Authentication Source: https://sanctum.manchenkoff.me/usage/token Defines the necessary API routes in Laravel for token-based authentication. It includes a login endpoint for guest users and a logout endpoint for authenticated users, ensuring they use separate routes from cookie-based authentication to prevent CSRF issues. ```php post('/login', [TokenAuthenticationController::class, 'store']); Route::middleware(['auth:sanctum'])->post('/logout', [TokenAuthenticationController::class, 'destroy']); ``` -------------------------------- ### Sanctum Redirect Hook Interface Definition Source: https://sanctum.manchenkoff.me/hooks/sanctum-redirect Defines the interface for the 'sanctum:redirect' hook within the Nuxt.js runtime. This interface specifies that the hook is triggered when a user is redirected and receives the FetchResponse and HookResult as arguments. It's primarily for understanding the hook's signature. ```typescript interface RuntimeNuxtHooks { /** * Triggers when user has been redirected. */ 'sanctum:redirect': (response: FetchResponse) => HookResult } ``` -------------------------------- ### Subscribe to Sanctum Login Hook in Nuxt.js Source: https://sanctum.manchenkoff.me/hooks/sanctum-login This snippet demonstrates how to subscribe to the `sanctum:login` hook in Nuxt.js using a plugin. The hook triggers after a successful user login and identity refresh. It allows for custom event handling, such as logging a message to the console. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:login', () => { console.log('Sanctum login hook triggered') }) }) ``` -------------------------------- ### Protect Pages from Authenticated Users with sanctum:guest (Nuxt.js) Source: https://sanctum.manchenkoff.me/middleware/sanctum-guest The 'sanctum:guest' middleware prevents authenticated users from accessing specific pages. If a user is authenticated, they are redirected to a configured page (defaulting to '/'). If no redirect is set, a 403 error is thrown. This is useful for login or registration pages. ```vue ``` -------------------------------- ### Subscribe to Sanctum Request Hook in Nuxt.js Source: https://sanctum.manchenkoff.me/hooks/sanctum-request This code snippet demonstrates how to subscribe to the 'sanctum:request' hook in a Nuxt.js application. It allows you to inject custom event handling logic before a request is sent to the Laravel API. The hook provides access to the Nuxt app instance, fetch context, and a logger for debugging. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (nuxtApp, context, logger) => { logger.info('Sanctum request hook triggered', context.request) }) }) ``` -------------------------------- ### Subscribe to Sanctum Redirect Hook in Nuxt.js Source: https://sanctum.manchenkoff.me/hooks/sanctum-redirect This plugin subscribes to the 'sanctum:redirect' hook provided by the Nuxt.js Sanctum module. It allows for custom event handling before a redirect occurs, logging the target URL to the console. This is useful for adding pre-redirect logic or analytics. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:redirect', (url) => { console.log('Sanctum redirect hook triggered', url) }) }) ``` -------------------------------- ### Sanctum Redirect Hook Source: https://sanctum.manchenkoff.me/hooks/sanctum-redirect Subscribe to the `sanctum:redirect` hook to intercept and handle redirects triggered by Sanctum, such as after login or logout. ```APIDOC ## Sanctum Redirect Hook ### Description Subscribe to the `sanctum:redirect` hook to inject custom event handling for redirects. This hook is triggered before a redirect occurs, allowing you to modify or log the redirect URL. ### Method Subscription to Hook ### Endpoint N/A (Client-side hook) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // app/plugins/sanctum-listener.ts export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:redirect', (url) => { console.log('Sanctum redirect hook triggered', url) }) }) ``` ### Response #### Success Response N/A (Hook execution) #### Response Example N/A ``` -------------------------------- ### Login Endpoint Source: https://sanctum.manchenkoff.me/usage/token Authenticate a user by submitting credentials to the login endpoint. The module expects a plain token value in the response. ```APIDOC ## POST /login - User Login ### Description Authenticates a user by submitting their credentials. Upon successful authentication, the API should return a JSON response containing a `token`. ### Method `POST` ### Endpoint `/login` (or your configured login endpoint) ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. - **remember** (boolean) - Optional - Whether to remember the user. ### Request Example ```json { "email": "john@doe.com", "password": "password", "remember": true } ``` ### Response #### Success Response (200) - **token** (string) - The authentication token for the user. #### Response Example ```json { "token": "your_plain_token_value" } ``` ``` -------------------------------- ### Enrich Sanctum Request Headers with i18n Locale (Nuxt) Source: https://sanctum.manchenkoff.me/advanced/dependencies This Nuxt plugin demonstrates how to enrich Sanctum requests with an 'X-Language' header, using the current locale from the Nuxt i18n module. It hooks into the 'sanctum:request' event to set the header before the request is sent. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (app, ctx, logger) => { ctx .options .headers .set("X-Language", app.$i18n.localeProperties.value.code) }) } ``` -------------------------------- ### Handle Sanctum Request Errors in Nuxt.js Plugin Source: https://sanctum.manchenkoff.me/hooks/sanctum-error-request This snippet demonstrates how to subscribe to the `sanctum:error:request` hook in a Nuxt.js plugin. It allows for custom error handling when an API request fails before reaching the server, utilizing ofetch's onRequestError. The hook receives a FetchContext and can return a HookResult. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:error:request', (context) => { console.log('Sanctum request error hook triggered', context) }) }) ``` -------------------------------- ### Nuxt Plugin: Subscribe to Sanctum Logout Hook Source: https://sanctum.manchenkoff.me/hooks/sanctum-logout This Nuxt plugin subscribes to the 'sanctum:logout' hook. It executes custom code, such as logging a message, immediately after a user is successfully logged out and their identity is reset by Laravel Sanctum. No external dependencies are required beyond Nuxt and Laravel Sanctum integration. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:logout', () => { console.log('Sanctum logout hook triggered') }) }) ``` -------------------------------- ### Handle Sanctum API Responses in Nuxt.js Source: https://sanctum.manchenkoff.me/hooks/sanctum-response Subscribes to the `sanctum:response` hook in Nuxt.js to execute custom logic whenever a Laravel API response is received. This allows for centralized handling of responses, such as logging or conditional actions. It requires the Nuxt.js runtime and a plugin to register the hook. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:response', (nuxtApp, context, logger) => { logger.info('Sanctum response hook triggered', context.request) }) }) ``` -------------------------------- ### Catching Laravel API Errors with FetchError in Nuxt Source: https://sanctum.manchenkoff.me/advanced/error-handling This snippet shows how to handle potential errors during API calls made with the use of the Nuxt Sanctum module. It specifically catches `FetchError` instances and checks for a 422 status code to extract validation errors from the response, which can then be used for form feedback. ```javascript import { FetchError } from 'ofetch' const { login } = useSanctumAuth() const userCredentials = { email: 'user@mail.com', password: '123123', } async function onCredentialsFormSubmit() { try { await login(userCredentials) } catch (e) { if (error instanceof FetchError && error.response?.status === 422) { // here you can extract errors from a response // and put it in your form for example console.log(e.response?._data.errors) } } } ``` -------------------------------- ### Login Endpoint Response for Token Authentication Source: https://sanctum.manchenkoff.me/usage/token Illustrates the expected JSON response format from the Laravel login API endpoint when using token authentication. The response must include a 'token' key containing the plain token value, which the Nuxt client will use for subsequent requests. ```json { "token": "" } ```