### Install Dependencies Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/README.md Installs project dependencies using pnpm. Ensure Node.js and pnpm are installed. ```bash pnpm install ``` -------------------------------- ### Start Development Server Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/README.md Starts the Nuxt development server on http://localhost:3000. Useful for local development and testing. ```bash pnpm dev ``` -------------------------------- ### useSanctumFetch with Options Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/4.useSanctumFetch.md Shows how to make a GET request with additional options, such as specifying query parameters to filter the results. ```typescript const { data } = await useSanctumFetch("/api/users", { method: "GET", query: { is_active: true }, }) ``` -------------------------------- ### Manually Install Nuxt Auth Sanctum Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/1.getting-started/2.installation.md Manually install the package using pnpm and register it in your nuxt.config.ts. ```bash pnpm add nuxt-auth-sanctum ``` ```typescript export default defineNuxtConfig({ modules: [ // other modules 'nuxt-auth-sanctum' ], sanctum: {}, }) ``` -------------------------------- ### Server vs. Client Configuration Overrides Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/1.configuration.md Set different configurations for server-side and client-side environments using both the module's default options and `runtimeConfig`. This example shows distinct base URLs and log levels for each context. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], // Default values for both server and client sanctum: { baseUrl: 'http://localhost:80', logLevel: 3, }, // Server-specific overrides runtimeConfig: { sanctum: { baseUrl: 'http://laravel:80', // Docker internal URL logLevel: 4, // Verbose server logs }, // Client-specific overrides public: { sanctum: { baseUrl: 'https://myapp.com', // Public TLD logLevel: 2, // Minimal client logs } } }, }) ``` -------------------------------- ### Basic useSanctumFetch Request Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/4.useSanctumFetch.md Demonstrates a basic GET request to retrieve user data. It shows how to access the fetched data, status, error, and functions to refresh or clear the data. ```typescript const { data, status, error, refresh, clear } = await useSanctumFetch("/api/users") ``` -------------------------------- ### Full Nuxt Auth Sanctum Module Configuration Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/1.configuration.md An example of a complete module configuration for Nuxt Auth Sanctum, demonstrating various options for endpoints, CSRF handling, redirects, and middleware. ```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, keepRouteOnUnauthenticated: false, onLogin: '/', onLogout: '/', onAuthOnly: '/login', onGuestOnly: '/', }, globalMiddleware: { enabled: false, allow404WithoutAuth: true, }, logLevel: 3, appendPlugin: false, } }) ``` -------------------------------- ### Define Sanctum Request and Response Interceptors Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/1.interceptors.md Set up a Nuxt plugin to define custom behavior for outgoing requests and incoming responses using the `sanctum:request` and `sanctum:response` hooks. This example logs information about each request and response. ```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) }) }) ``` -------------------------------- ### Access Sanctum App Configuration Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/7.useSanctumAppConfig.md Use this composable to get the Sanctum module's configuration. Access specific configuration properties like interceptors.onRequest. ```typescript const config = useSanctumAppConfig(); console.log(config.interceptors.onRequest); // appConfig.sanctum.interceptors.onRequest ``` -------------------------------- ### Using useApiError Composable for Form Validation Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/2.error-handling.md This example demonstrates how to integrate the `useApiError` composable within a try-catch block to handle login errors. It specifically checks for validation errors using `error.isValidationError` and applies them to the form, or logs other server errors with their respective codes. ```typescript 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) } ``` -------------------------------- ### Logout User with Custom Method Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md The `logout` method can accept an options object to customize the request. For example, to use the `DELETE` HTTP method instead of the default `POST`. ```typescript const { logout } = useSanctumAuth() await logout({ method: "DELETE" }) ``` -------------------------------- ### Build Playground App Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Run this command to build the playground application. ```bash pnpm dev:build ``` -------------------------------- ### Create Local Package Archive Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Run this command to create a .tgz archive of the package for local testing. ```bash pnpm rc ``` -------------------------------- ### Run ESLint Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Execute this command to check the code style and standards using ESLint. ```bash pnpm lint ``` -------------------------------- ### Preview Production Build Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/README.md Locally previews the production build. This command helps to test the production version before deploying. ```bash pnpm preview ``` -------------------------------- ### Generate Static Hosting Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/README.md Generates all pages for static hosting. This is useful for deploying to platforms like Netlify or Vercel. ```bash pnpm generate ``` -------------------------------- ### Run Vitest Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Execute this command to run the project's tests using Vitest. ```bash pnpm test ``` -------------------------------- ### Build for Production Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/README.md Builds the Nuxt application for production deployment. This optimizes assets and code for performance. ```bash pnpm build ``` -------------------------------- ### useLazySanctumFetch with Options Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/5.useLazySanctumFetch.md Shows how to use useLazySanctumFetch with additional options, such as specifying the HTTP method and query parameters for the API request. ```typescript const { data } = await useLazySanctumFetch("/api/users", { method: "GET", query: { page: 1 }, }) ``` -------------------------------- ### Initialize and Use useSanctumClient Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/3.useSanctumClient.md Initialize the client and use it with `useAsyncData` to fetch data from an API endpoint. The client is pre-configured with CSRF token headers and cookie management. ```typescript const client = useSanctumClient(); const { data, status, error, refresh } = await useAsyncData('users', () => client('/api/users') ); ``` -------------------------------- ### Generate Type Stubs Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Execute this command to generate type stubs for the project. ```bash pnpm dev:prepare ``` -------------------------------- ### Login User with Credentials Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/3.token.md Use the `login` composable to authenticate a user by submitting their credentials. The user will be redirected to the `redirect.onLogin` route upon successful authentication. ```typescript const { login } = useSanctumAuth() const credentials = { email: "john@doe.com", password: "password", remember: true, } await login(credentials) ``` -------------------------------- ### Basic useLazySanctumFetch Usage Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/5.useLazySanctumFetch.md Demonstrates the basic usage of useLazySanctumFetch to retrieve data from an API endpoint. It shows how to access the fetched data, status, error, and functions to refresh or clear the data. ```typescript const { data, status, error, refresh, clear } = await useLazySanctumFetch("/api/users") ``` -------------------------------- ### Login Method Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md Logs in the user by sending credentials to the backend. Optionally disables automatic user identity fetching after a successful login. ```APIDOC ## login ### Description Authenticates the user by sending credentials to the backend. It can optionally disable automatic fetching of user identity after a successful login. ### Method Signature `login(credentials: object, fetchIdentity: boolean = true, options?: SanctumFetchOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **credentials** (object) - Required - An object containing user credentials (e.g., email, password) required by the Laravel Sanctum backend. - **fetchIdentity** (boolean) - Optional - Defaults to `true`. If `false`, user identity will not be loaded after a successful login response. - **options** (SanctumFetchOptions) - Optional - Additional fetch options, such as custom headers or HTTP methods. ### Request Example ```typescript const { login } = useSanctumAuth(); const userCredentials = { email: "user@mail.com", password: "123123", } // Login with default settings await login(userCredentials); // Login without fetching user identity await login(userCredentials, false); // Login with custom headers await login(userCredentials, true, { headers: { "X-Custom-Header": "header_value" } }); ``` ### Response #### Success Response (200) - **user** (object) - The authenticated user's data will be updated if `fetchIdentity` is true. #### Response Example (Response body depends on your Laravel API configuration for user data) ``` -------------------------------- ### Clone the Repository Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Use this command to clone the nuxt-auth-sanctum repository to your local machine. ```bash git clone git@github.com:manchenkoff/nuxt-auth-sanctum.git ``` -------------------------------- ### Login User with Custom Headers Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md Pass an `options` object as the third argument to the `login` method to include custom headers or other fetch configurations. ```typescript const { login } = useSanctumAuth() const userCredentials = { email: "user@mail.com", password: "123123", } await login( userCredentials, false, { headers: { "X-Custom-Header": "header_value" } } ) ``` -------------------------------- ### Run Nuxt Type Check Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Run this command to perform type checking for the Nuxt project. ```bash pnpm test:types ``` -------------------------------- ### Add nuxt-auth-sanctum Dependency Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/README.md Use this command to add the nuxt-auth-sanctum module to your Nuxt project. ```bash npx nuxi@latest module add nuxt-auth-sanctum ``` -------------------------------- ### Login User with Credentials Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md Use the `login` method to authenticate a user by passing their credentials. The `user` property will be updated automatically upon successful login. ```typescript const { login } = useSanctumAuth(); const userCredentials = { email: "user@mail.com", password: "123123", } await login(userCredentials) ``` -------------------------------- ### Release New Version Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Run this command to release a new version of the package after all changes are merged into the main branch. ```bash pnpm release ``` -------------------------------- ### useSanctumFetch with Type Casting Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/4.useSanctumFetch.md Illustrates how to use type casting with useSanctumFetch to strongly type the expected API response, improving code safety and developer experience. ```typescript interface MyResponse { name: string } const { data } = await useSanctumFetch("/api/endpoint") const name = data.value?.name ``` -------------------------------- ### Reference Local Package in Project Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Add this entry to your project's devDependencies to reference the locally created package archive. ```json { "devDependencies": { "nuxt-auth-sanctum": "file:/dist/nuxt-auth-sanctum-0.0.0.tgz" } } ``` -------------------------------- ### Configure nuxt-auth-sanctum in nuxt.config.ts Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/README.md Configure the module by specifying the base URL for your Laravel API in the nuxt.config.ts file. This is essential for the module to communicate with your backend. ```javascript export default defineNuxtConfig({ modules: ["nuxt-auth-sanctum"], sanctum: { baseUrl: "http://localhost:80", // Laravel API }, }); ``` -------------------------------- ### Handle SSL Certificate Verification Error Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/7.troubleshooting.md When working locally with SSL enabled, you might encounter certificate verification errors. Set the environment variable `NODE_TLS_REJECT_UNAUTHORIZED=0` to bypass this. ```bash NODE_TLS_REJECT_UNAUTHORIZED=0 npm run dev ``` -------------------------------- ### Enable Global Middleware in nuxt.config.ts Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/4.middleware/3.global.md Configure nuxt.config.ts to enable global middleware and define redirect routes for authenticated and guest users. Ensure `onAuthOnly` and `onGuestOnly` routes are set. ```typescript export default defineNuxtConfig({ modules: [ 'nuxt-auth-sanctum' ], sanctum: { baseUrl: 'http://localhost:80', redirect: { onAuthOnly: '/login', onGuestOnly: '/profile', }, globalMiddleware: { enabled: true, }, } }) ``` -------------------------------- ### Environment Variables for Sanctum Origin Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/1.configuration.md Configure the `origin` option using environment variables. A static default must be set in `nuxt.config.ts` first. `NUXT_PUBLIC_SANCTUM_ORIGIN` is for client-side, and `NUXT_SANCTUM_ORIGIN` is for server-side. ```typescript sanctum: { origin: 'http://localhost:3000', // Set static default first } ``` ```env # For client-side (CSR) NUXT_PUBLIC_SANCTUM_ORIGIN=https://your-domain.com # For server-side (SSR) NUXT_SANCTUM_ORIGIN=https://your-domain.com ``` -------------------------------- ### useLazySanctumFetch with Type Casting Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/5.useLazySanctumFetch.md Illustrates how to use type casting with useLazySanctumFetch to specify the expected response type, enabling better type safety and autocompletion. ```typescript interface MyResponse { name: string } const { data } = await useLazySanctumFetch("/api/endpoint") const name = data.value?.name ``` -------------------------------- ### Configure 404 Handling with Global Middleware Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/4.middleware/3.global.md Modify `nuxt.config.ts` to control how non-existing routes are handled when global middleware is enabled. Setting `allow404WithoutAuth` to `false` redirects to the `onAuthOnly` route instead of showing a 404 error. ```typescript export default defineNuxtConfig({ modules: [ 'nuxt-auth-sanctum', ], sanctum: { baseUrl: 'http://localhost:80', redirect: { onAuthOnly: '/login', onGuestOnly: '/profile', }, globalMiddleware: { enabled: true, allow404WithoutAuth: false, }, } }) ``` -------------------------------- ### Subscribe to sanctum:init Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/6.sanctum-init.md Subscribe to the `sanctum:init` hook within a Nuxt plugin to execute custom logic after the initial user identity request. This hook is essential for ensuring that authentication-related middleware and redirects function correctly. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:init', () => { console.log('Sanctum init hook triggered') }) }) ``` -------------------------------- ### Configure Sanctum via RuntimeConfig Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/1.configuration.md Manage Nuxt Auth Sanctum configuration using the `runtimeConfig` property in `nuxt.config.ts`. This allows for environment-specific settings, particularly for the public-facing base URL. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], runtimeConfig: { public: { sanctum: { baseUrl: 'http://localhost:80', }, }, }, }) ``` -------------------------------- ### Check Nuxt Logs for Authentication Errors Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/7.troubleshooting.md Examine Nuxt logs for 'set-cookie header is missing' or 'User is not authenticated' messages. These indicate issues with Sanctum stateful domains. ```log [nuxt-auth-sanctum:ssr] WARN [response] set-cookie header is missing [nuxt-auth-sanctum:ssr] ⚙ User is not authenticated on plugin initialization, status: 401 ``` -------------------------------- ### Use useSanctumFetch with Server Proxy Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/4.proxy.md Make API requests using `useSanctumFetch` when the server proxy is enabled. The proxy automatically handles stripping the Nuxt route prefix from the request URL before forwarding it to the 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 Nuxt Auth Sanctum Base URL Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/1.getting-started/2.installation.md Provide the configuration for nuxt-auth-sanctum in nuxt.config.ts, specifying the Laravel API base URL. ```typescript export default defineNuxtConfig({ //... other parts of the config // nuxt-auth-sanctum options (also configurable via environment variables) sanctum: { baseUrl: 'http://localhost:80', } }) ``` -------------------------------- ### Retrieve Sanctum Configuration with useSanctumConfig Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/6.useSanctumConfig.md Use this composable to access Sanctum module configuration. It automatically provides server-side configuration (runtimeConfig.sanctum) or client-side configuration (runtimeConfig.public.sanctum) based on the execution context. Access properties like `baseUrl` directly from the returned config object. ```typescript const config = useSanctumConfig(); // On server: runtimeConfig.sanctum.baseUrl // On client: runtimeConfig.public.sanctum.baseUrl console.log(config.baseUrl); ``` -------------------------------- ### Configure Environment Variables for SSR Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/7.troubleshooting.md Ensure both public and private environment variables for the Sanctum base URL are set. The server needs the private variable for SSR requests. ```env NUXT_PUBLIC_SANCTUM_BASE_URL=http://your-api-url NUXT_SANCTUM_BASE_URL=http://your-api-url ``` -------------------------------- ### Subscribe to Sanctum Login Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/8.sanctum-login.md Use this plugin to subscribe to the `sanctum:login` hook. It logs a message to the console when the hook is triggered after a successful login. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:login', () => { console.log('Sanctum login hook triggered') }) }) ``` -------------------------------- ### Run Vitest in Watch Mode Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Use this command to run Vitest in watch mode, which automatically re-runs tests on file changes. ```bash pnpm test:watch ``` -------------------------------- ### Separate Validation Commands Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/README.md Runs linting and type checking separately. Useful for debugging specific code quality issues. ```bash pnpm lint ``` ```bash pnpm typecheck ``` -------------------------------- ### Configure Sanctum Base URL for Docker Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/7.troubleshooting.md Ensure `sanctum.baseUrl` in `nuxt.config.ts` is accessible from both the web browser and the Nuxt container when using Docker. Using a container name as a domain is recommended. ```typescript export default defineNuxtConfig({ modules: [ '@nuxtjs/auth-sanctum', ], auth: { // ... redirect: { login: '/login', logout: '/logout', callback: false, home: '/dashboard', }, // Example for Docker: // baseUrl: 'http://nuxt-app:3000', // Example for local: // baseUrl: 'http://localhost:3000', }, }) ``` -------------------------------- ### Mark a Page as Guest-Only Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/4.middleware/3.global.md Use `definePageMeta` with `sanctum.guestOnly: true` to specify pages that should only be accessible to unauthenticated users. Note that these pages are still processed by global middleware. ```typescript definePageMeta({ sanctum: { guestOnly: true, } }) ``` -------------------------------- ### Validate Code Quality Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/README.md Checks code quality using linters and type checkers. Run this command to ensure code standards are met. ```bash pnpm validate ``` -------------------------------- ### Enable Server Proxy in nuxt.config.ts Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/4.proxy.md Enable the server proxy feature and configure its route and base URL in your Nuxt configuration file. Ensure SSR is enabled for this feature to be effective. ```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', }, }, }) ``` -------------------------------- ### Custom Auth Plugin with Dependencies Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/5.dependencies.md Define a custom Nuxt plugin that explicitly depends on other plugins like `@nuxtjs/i18n` and `nuxt-auth-sanctum`. This ensures proper loading order before performing the initial authentication request. ```typescript export default defineNuxtPlugin({ name: 'custom-auth', dependsOn: ['@nuxtjs/i18n', 'nuxt-auth-sanctum'], async setup() { nuxtApp.hook('sanctum:request', (app, ctx, logger) => { ctx .options .headers .set("X-Language", app.$i18n.localeProperties.value.code) }) const { init } = useSanctumAuth() await init() } }) ``` -------------------------------- ### Shared Configuration for Server and Client Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/1.configuration.md Define a shared configuration for Nuxt Auth Sanctum that applies to both server-side and client-side contexts using the `runtimeConfig.public.sanctum` property. ```typescript runtimeConfig: { public: { sanctum: { baseUrl: 'http://localhost:80', }, }, } ``` -------------------------------- ### sanctum:init Hook Signature Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/6.sanctum-init.md This interface defines the signature for the `sanctum:init` hook, indicating that it triggers when an initial user identity request has been made and returns a `HookResult`. ```typescript interface RuntimeNuxtHooks { /** * Triggers when an initial user identity request has been made. */ 'sanctum:init': () => HookResult } ``` -------------------------------- ### Protecting a Login Page with Sanctum Guest Middleware Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/4.middleware/2.sanctum-guest.md Apply the `sanctum:guest` middleware to a page component to restrict access to unauthenticated users. This is commonly used for login or registration pages. ```vue ``` -------------------------------- ### Define Custom Token Storage in App Config Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/4.token-storage.md Define a custom token storage handler directly in app.config.ts for use in development and Node.js production builds. Note that this approach does not work with static site generation (`nuxt generate`). ```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, }, }); ``` -------------------------------- ### Catching Specific API Errors with FetchError Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/2.error-handling.md This snippet shows how to use a try-catch block to handle potential errors during the login process. It specifically checks if the error is an instance of `FetchError` and if the response status code is 422 (Unprocessable Entity), allowing you to extract and display validation errors. ```typescript 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) } } } ``` -------------------------------- ### Laravel API Routes for Authentication Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/3.token.md Define API routes for login and logout. Ensure these routes are distinct from web routes to prevent CSRF token mismatches. The login endpoint should handle guest users, and the logout endpoint should authenticate users. ```php post('/login', [TokenAuthenticationController::class, 'store']); Route::middleware(['auth:sanctum'])->post('/logout', [TokenAuthenticationController::class, 'destroy']); ``` -------------------------------- ### Define Custom Token Storage with Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/4.token-storage.md Implement custom token storage using the 'sanctum:storage:token' hook in a client-side plugin. This method is recommended for all build types, including static builds, and uses Capacitor Preferences for storage. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook("sanctum:storage:token", () => { const storage = { async get(app: NuxtApp) { const { Preferences } = await import("@capacitor/preferences"); const result = await Preferences.get({ key: "sanctum.token" }); return result.value ?? undefined; }, async set(app: NuxtApp, token?: string) { const { Preferences } = await import("@capacitor/preferences"); if (token) { await Preferences.set({ key: "sanctum.token", value: token }); } else { await Preferences.remove({ key: "sanctum.token" }); } }, }; useSanctumTokenStorage(storage); }); }); ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/CONTRIBUTING.md Follow this naming convention when creating a new branch for a feature, replacing XXX with the GitHub issue number. ```bash git checkout -b XXX-feature-name ``` -------------------------------- ### Enable Detailed Logging in Nuxt Config Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/7.troubleshooting.md Set `logLevel` to 5 in `nuxt.config.ts` to enable detailed logging for debugging SSR and CSR output. ```typescript export default defineNuxtConfig({ modules: [ '@nuxtjs/auth-sanctum', ], auth: { // ... logLevel: 5, }, }) ``` -------------------------------- ### Environment Variables for Sanctum Base URL Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/1.configuration.md Override the `baseUrl` option using environment variables for both client-side (CSR) and server-side (SSR) rendering. Ensure both public and private variables are set if using SSR. ```env # Used by the browser (CSR) NUXT_PUBLIC_SANCTUM_BASE_URL='http://localhost:8000' # Used by the Nuxt server (SSR) NUXT_SANCTUM_BASE_URL='http://localhost:8000' ``` -------------------------------- ### Logout Method Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md Logs out the current user. Allows customization of the HTTP method used for the request. ```APIDOC ## logout ### Description Logs out the current user. The HTTP method for the request can be customized. ### Method Signature `logout(options?: SanctumFetchOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (SanctumFetchOptions) - Optional - Additional fetch options, such as specifying the HTTP method (defaults to POST). ### Request Example ```typescript const { logout } = useSanctumAuth(); // Logout using the default POST method await logout(); // Logout using the DELETE method await logout({ method: "DELETE" }); ``` ### Response #### Success Response (200) - No specific response body is detailed, typically indicates successful session termination. #### Response Example (No specific response body example provided) ``` -------------------------------- ### Subscribe to Sanctum Request Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/1.sanctum-request.md Use this plugin to subscribe to the `sanctum:request` hook. It allows you to perform custom actions, such as logging, before a request is sent to the Laravel API. The hook receives the Nuxt app instance, request context, and a logger. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (nuxtApp, context, logger) => { logger.info('Sanctum request hook triggered', context.request) }) }) ``` -------------------------------- ### Computed Properties Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md Provides reactive properties for the currently authenticated user and their authentication status. ```APIDOC ## Computed Properties ### Description The composable exposes computed properties to easily access the authentication state. ### Properties - **user** (object | null): A computed property that holds the currently authenticated user's data. It is `null` if the user is not authenticated. This is essentially the same as `useSanctumUser()`. - **isAuthenticated** (boolean): A computed boolean flag that indicates whether the user is currently authenticated. It is `true` if a user is logged in, and `false` otherwise. ### Usage Example ```typescript const { user, isAuthenticated } = useSanctumAuth(); // Access user data console.log(user.value?.name); // Check authentication status if (isAuthenticated.value) { console.log('User is logged in'); } else { console.log('User is not logged in'); } ``` ``` -------------------------------- ### Subscribe to Sanctum Redirect Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/5.sanctum-redirect.md Use this plugin to subscribe to the 'sanctum:redirect' hook. It allows you to perform custom actions, like logging, before the redirect is finalized. Ensure this plugin is correctly registered in your Nuxt application. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:redirect', (url) => { console.log('Sanctum redirect hook triggered', url) }) }) ``` -------------------------------- ### Refresh Identity Method Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md Manually re-fetches the current authenticated user's data. ```APIDOC ## refreshIdentity ### Description Manually re-fetches the current authenticated user's data from the backend. ### Method Signature `refreshIdentity(): Promise` ### Parameters None ### Request Example ```typescript const { refreshIdentity } = useSanctumAuth(); await refreshIdentity(); ``` ### Response #### Success Response (200) - **user** (object) - The `user` computed property will be updated with the latest user information. #### Response Example (Response body depends on your Laravel API configuration for user data) ``` -------------------------------- ### Subscribe to Sanctum Proxy Request Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/10.sanctum-proxy-request.md Implement this hook within a Nitro plugin to log information about incoming proxy requests. It triggers for every request made to the Laravel API through the Nuxt server proxy. ```typescript export default defineNitroPlugin((nuxtApp) => { nitroApp.hooks.hook("sanctum:proxy:request", (context, logger) => { logger.info("Sanctum proxy request hook triggered", context.request); }); }); ``` -------------------------------- ### Configure Laravel Environment for CSRF and Sessions Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/7.troubleshooting.md Adjust SANCTUM_STATEFUL_DOMAINS and SESSION_DOMAIN in your Laravel application to match your frontend and backoffice domains. This resolves CSRF token mismatch errors. ```env SESSION_DOMAIN=.myapp.com SANCTUM_STATEFUL_DOMAINS=myapp.com,admin.myapp.com ``` -------------------------------- ### Subscribe to Sanctum Logout Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/9.sanctum-logout.md Use this plugin to subscribe to the `sanctum:logout` hook. It executes custom logic once the user is logged out and their identity is reset. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:logout', () => { console.log('Sanctum logout hook triggered') }) }) ``` -------------------------------- ### JSON Response for API Token Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/3.token.md The login endpoint must return a JSON response containing a 'token' key with the plain token value. This token is used by the client for subsequent authenticated requests. ```json { "token": "" } ``` -------------------------------- ### Protecting a Page with Sanctum Auth Middleware Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/4.middleware/1.sanctum-auth.md Apply the `sanctum:auth` middleware to a page to restrict access to authenticated users only. If the user is not authenticated, they will be redirected to the login page. ```vue ``` -------------------------------- ### Subscribe to Sanctum Error Response Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/4.sanctum-error-response.md Implement this plugin to listen for the `sanctum:error:response` hook. This allows you to process HTTP error responses from your API, such as 401, 419, 403, or 404, and implement custom logic. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:error:response', (response) => { console.log('Sanctum error hook triggered', response) }) }) ``` -------------------------------- ### Configure Token Mode in Nuxt Config Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/4.token-storage.md Set the authentication mode to 'token' in your nuxt.config.ts to enable token-based authentication. This configuration is necessary for the module to manage authentication tokens. ```typescript export default defineNuxtConfig({ modules: ["nuxt-auth-sanctum"], sanctum: { // ... mode: "token", // ... }, }); ``` -------------------------------- ### Login User without Identity Fetch Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/1.useSanctumAuth.md To prevent automatic user identity fetching after a successful login (e.g., for 2FA), pass `false` as the second argument to the `login` method. ```typescript // user identity will not be loaded after successful response await login(userCredentials, false) ``` -------------------------------- ### Sanctum Response Hook Signature Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/2.sanctum-response.md Defines the TypeScript interface for the `sanctum:response` hook, outlining the parameters it receives: the Nuxt app instance, the fetch context, and a Consola logger instance. ```typescript interface RuntimeNuxtHooks { /** * Triggers on every server response. */ 'sanctum:response': (app: NuxtApp, ctx: FetchContext, logger: ConsolaInstance) => HookResult } ``` -------------------------------- ### Accessing Authenticated User with Custom Type Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/3.composables/2.useSanctumUser.md Use this composable to retrieve the authenticated user, optionally casting it to a custom interface. If no user is logged in, it returns null. ```typescript interface MyCustomUser { id: number; login: string; custom_metadata: { group: string; role: string; }; } const user = useSanctumUser(); ``` -------------------------------- ### Sanctum Login Hook Interface Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/8.sanctum-login.md This interface defines the signature for the `sanctum:login` hook, indicating it triggers on successful user login. ```typescript interface RuntimeNuxtHooks { /** * Triggers when user successfully logs in. */ 'sanctum:login': () => HookResult } ``` -------------------------------- ### Sanctum Request Hook Signature Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/1.sanctum-request.md This TypeScript interface defines the signature for the `sanctum:request` hook. It specifies the types of arguments passed to the hook callback: the Nuxt app instance, the fetch context, and a Consola logger instance. ```typescript interface RuntimeNuxtHooks { /** * Triggers on every client request. */ 'sanctum:request': (app: NuxtApp, ctx: FetchContext, logger: ConsolaInstance) => HookResult } ``` -------------------------------- ### Define Proxy Headers in Nuxt Config Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/7.troubleshooting.md When using routeRules with proxy, explicitly define any custom headers required by your API. This ensures Nuxt passes them during proxied requests. ```typescript export default defineNuxtConfig({ // ... other config routeRules: { '/backend/api/**': { proxy: { to: `http://laravel.test/api/**`, headers: { YOUR_HEADER: 'header_value' }, } } } }) ``` -------------------------------- ### Sanctum Redirect Hook Signature Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/5.sanctum-redirect.md This interface defines the signature for the 'sanctum:redirect' hook. It indicates that the hook receives a FetchResponse object and returns a HookResult. This is useful for understanding the data available within the hook. ```typescript interface RuntimeNuxtHooks { /** * Triggers when user has been redirected. */ 'sanctum:redirect': (response: FetchResponse) => HookResult } ``` -------------------------------- ### Sanctum Proxy Request Hook Signature Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/10.sanctum-proxy-request.md This interface defines the signature for the `sanctum:proxy:request` hook, specifying the context and logger objects available during the request. ```typescript interface NitroRuntimeHooks { /** * Triggers on every client proxy request. */ "sanctum:proxy:request": (ctx: FetchContext, logger: ConsolaInstance) => void; } ``` -------------------------------- ### Subscribe to Sanctum Request Error Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/3.sanctum-error-request.md Use this plugin to subscribe to the `sanctum:error:request` hook. This allows you to log or handle errors that occur during API requests. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:error:request', (context) => { console.log('Sanctum request error hook triggered', context) }) }) ``` -------------------------------- ### Composable for API Error Handling Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/2.error-handling.md This composable function `useApiError` simplifies the process of identifying and extracting information from API errors. It distinguishes between validation errors (422) and other server errors, providing a structured way to access error codes and validation error bags. ```typescript import { FetchError } from 'ofetch' const VALIDATION_ERROR_CODE = 422 const SERVER_ERROR_CODE = 500 export const useApiError = (error: any) => { const isFetchError = error instanceof FetchError const isValidationError = isFetchError && error.response?.status === VALIDATION_ERROR_CODE const code = isFetchError ? error.response?.status : SERVER_ERROR_CODE const bag: Record = isValidationError ? error.response?._data.errors : {} return { isValidationError, code, bag, } } ``` -------------------------------- ### sanctum:error:request Hook Usage Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/3.sanctum-error-request.md This snippet demonstrates how to subscribe to the `sanctum:error:request` hook within a Nuxt plugin to handle request errors. The hook provides a context object containing details about the error. ```APIDOC ## sanctum:error:request Hook ### Description This hook is triggered when an error occurs during a fetch request, before the request reaches the remote server. It allows for custom error handling logic. ### Usage Subscribe to the `sanctum:error:request` hook in your Nuxt plugin to intercept and manage these errors. ```typescript [app/plugins/sanctum-listener.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:error:request', (context) => { console.log('Sanctum request error hook triggered', context) }) }) ``` ### Hook Signature ```typescript interface RuntimeNuxtHooks { /** * Triggers when receiving an error on fetch request. */ 'sanctum:error:request': (context: FetchContext) => HookResult } ``` ### Parameters #### context (FetchContext) An object containing details about the fetch request error. The exact structure of `FetchContext` is not detailed in the provided source, but it is passed to the hook's callback function. ``` -------------------------------- ### Subscribe to Sanctum Response Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/2.sanctum-response.md Subscribe to the `sanctum:response` hook within a Nuxt plugin to execute custom logic whenever an API response is received. This hook provides access to the response context and a logger instance. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:response', (nuxtApp, context, logger) => { logger.info('Sanctum response hook triggered', context.request) }) }) ``` -------------------------------- ### Sanctum Request Error Hook Signature Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/3.sanctum-error-request.md This interface defines the signature for the `sanctum:error:request` hook, indicating it triggers on fetch request errors and provides a `FetchContext`. ```typescript interface RuntimeNuxtHooks { /** * Triggers when receiving an error on fetch request. */ 'sanctum:error:request': (context: FetchContext) => HookResult } ``` -------------------------------- ### Sanctum Logout Hook Interface Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/9.sanctum-logout.md This interface defines the signature for the `sanctum:logout` hook, indicating it triggers upon successful user logout. ```typescript interface RuntimeNuxtHooks { /** * Triggers when user successfully logs out. */ 'sanctum:logout': () => HookResult } ``` -------------------------------- ### Override Module Defaults in nuxt.config.ts Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/2.usage/1.configuration.md Configure Nuxt Auth Sanctum by overriding default options directly within your `nuxt.config.ts` file. Specify your Laravel API base URL and custom redirect routes. ```typescript export default defineNuxtConfig({ modules: ['nuxt-auth-sanctum'], sanctum: { baseUrl: 'http://localhost:80', // Your Laravel API redirect: { onLogin: '/dashboard', // Custom route after successful login }, }, }) ``` -------------------------------- ### Exclude a Page from Global Middleware Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/4.middleware/3.global.md Use `definePageMeta` with `sanctum.excluded: true` to prevent a specific page from being checked by the global middleware. This is useful for public pages. ```typescript definePageMeta({ sanctum: { excluded: true, } }) ``` -------------------------------- ### Subscribe to Sanctum Refresh Hook Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/7.sanctum-refresh.md Subscribe to the 'sanctum:refresh' hook within a Nuxt plugin to execute custom code once the user identity refresh request is completed. This hook is useful for performing actions after authentication state changes. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:refresh', () => { console.log('Sanctum refresh hook triggered') }) }) ``` -------------------------------- ### Sanctum Refresh Hook Interface Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/7.sanctum-refresh.md This interface defines the signature for the 'sanctum:refresh' hook, indicating that it triggers when the user identity has been refreshed and returns a HookResult. ```typescript interface RuntimeNuxtHooks { /** * Triggers when user identity has been refreshed. */ 'sanctum:refresh': () => HookResult } ``` -------------------------------- ### Sanctum Error Response Hook Signature Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/5.hooks/4.sanctum-error-response.md This interface defines the signature for the `sanctum:error:response` hook, indicating that it receives a `FetchResponse` object and returns a `HookResult`. ```typescript interface RuntimeNuxtHooks { /** * Triggers when receiving an error response. */ 'sanctum:error:response': (response: FetchResponse) => HookResult } ``` -------------------------------- ### Add i18n Header to Sanctum Requests Source: https://github.com/manchenkoff/nuxt-auth-sanctum/blob/main/docs/content/6.advanced/5.dependencies.md Use the `sanctum:request` hook within a Nuxt plugin to add custom headers, such as language codes from an i18n plugin, to Sanctum API requests. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('sanctum:request', (app, ctx, logger) => { ctx .options .headers .set("X-Language", app.$i18n.localeProperties.value.code) }) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.