{"id":13810476,"url":"https://github.com/Atinux/nuxt-auth-utils","last_synced_at":"2025-05-14T10:33:39.052Z","repository":{"id":205995792,"uuid":"711008639","full_name":"Atinux/nuxt-auth-utils","owner":"Atinux","description":"Minimal Auth module for Nuxt 3.","archived":false,"fork":false,"pushed_at":"2024-04-12T19:04:38.000Z","size":527,"stargazers_count":410,"open_issues_count":22,"forks_count":39,"subscribers_count":6,"default_branch":"main","last_synced_at":"2024-04-15T14:01:20.620Z","etag":null,"topics":["authentication","nuxt","nuxt-auth","nuxt-module"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Atinux.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2023-10-28T00:30:08.000Z","updated_at":"2024-07-23T22:40:34.663Z","dependencies_parsed_at":"2023-11-29T15:30:55.511Z","dependency_job_id":"a218bd63-cf7e-4fbd-9ab2-ededa33bcc20","html_url":"https://github.com/Atinux/nuxt-auth-utils","commit_stats":null,"previous_names":["atinux/nuxt-auth-utils"],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Atinux%2Fnuxt-auth-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Atinux%2Fnuxt-auth-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Atinux%2Fnuxt-auth-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Atinux%2Fnuxt-auth-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Atinux","download_url":"https://codeload.github.com/Atinux/nuxt-auth-utils/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225249319,"owners_count":17444412,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","nuxt","nuxt-auth","nuxt-module"],"created_at":"2024-08-04T02:00:55.362Z","updated_at":"2025-05-14T10:33:39.010Z","avatar_url":"https://github.com/Atinux.png","language":"TypeScript","readme":"# Nuxt Auth Utils\n\n[![npm version][npm-version-src]][npm-version-href]\n[![npm downloads][npm-downloads-src]][npm-downloads-href]\n[![License][license-src]][license-href]\n[![Nuxt][nuxt-src]][nuxt-href]\n\nAdd Authentication to Nuxt applications with secured \u0026 sealed cookies sessions.\n\n- [Release Notes](/CHANGELOG.md)\n- [Demo with OAuth](https://github.com/atinux/atidone)\n- [Demo with Passkeys](https://github.com/atinux/todo-passkeys)\n\u003c!-- - [🏀 Online playground](https://stackblitz.com/github/your-org/nuxt-auth-utils?file=playground%2Fapp.vue) --\u003e\n\u003c!-- - [📖 \u0026nbsp;Documentation](https://example.com) --\u003e\n\n## Features\n\n- [Hybrid Rendering](#hybrid-rendering) support (SSR / CSR / SWR / Prerendering)\n- [40+ OAuth Providers](#supported-oauth-providers)\n- [Password Hashing](#password-hashing)\n- [WebAuthn (passkey)](#webauthn-passkey)\n- [`useUserSession()` Vue composable](#vue-composable)\n- [Tree-shakable server utils](#server-utils)\n- [`\u003cAuthState\u003e` component](#authstate-component)\n- [Extendable with hooks](#extend-session)\n- [WebSocket support](#websocket-support)\n\nIt has few dependencies (only from [UnJS](https://github.com/unjs)), run on multiple JS environments (Node, Deno, Workers) and is fully typed with TypeScript.\n\n## Requirements\n\nThis module only works with a Nuxt server running as it uses server API routes (`nuxt build`).\n\nThis means that you cannot use this module with `nuxt generate`.\n\nYou can anyway use [Hybrid Rendering](#hybrid-rendering) to pre-render pages of your application or disable server-side rendering completely.\n\n## Quick Setup\n\n1. Add `nuxt-auth-utils` in your Nuxt project\n\n```bash\nnpx nuxi@latest module add auth-utils\n```\n\n2. Add a `NUXT_SESSION_PASSWORD` env variable with at least 32 characters in the `.env`.\n\n```bash\n# .env\nNUXT_SESSION_PASSWORD=password-with-at-least-32-characters\n```\n\nNuxt Auth Utils generates one for you when running Nuxt in development the first time if no `NUXT_SESSION_PASSWORD` is set.\n\n3. That's it! You can now add authentication to your Nuxt app ✨\n\n## Vue Composable\n\nNuxt Auth Utils automatically adds some plugins to fetch the current user session to let you access it from your Vue components.\n\n### User Session\n\n```vue\n\u003cscript setup\u003e\nconst { loggedIn, user, session, fetch, clear, openInPopup } = useUserSession()\n\u003c/script\u003e\n\n\u003ctemplate\u003e\n  \u003cdiv v-if=\"loggedIn\"\u003e\n    \u003ch1\u003eWelcome {{ user.login }}!\u003c/h1\u003e\n    \u003cp\u003eLogged in since {{ session.loggedInAt }}\u003c/p\u003e\n    \u003cbutton @click=\"clear\"\u003eLogout\u003c/button\u003e\n  \u003c/div\u003e\n  \u003cdiv v-else\u003e\n    \u003ch1\u003eNot logged in\u003c/h1\u003e\n    \u003ca href=\"/auth/github\"\u003eLogin with GitHub\u003c/a\u003e\n    \u003c!-- or open the OAuth route in a popup --\u003e\n    \u003cbutton @click=\"openInPopup('/auth/github')\"\u003eLogin with GitHub\u003c/button\u003e\n  \u003c/div\u003e\n\u003c/template\u003e\n```\n\n**TypeScript Signature:**\n\n```ts\ninterface UserSessionComposable {\n  /**\n   * Computed indicating if the auth session is ready\n   */\n  ready: ComputedRef\u003cboolean\u003e\n  /**\n   * Computed indicating if the user is logged in.\n   */\n  loggedIn: ComputedRef\u003cboolean\u003e\n  /**\n   * The user object if logged in, null otherwise.\n   */\n  user: ComputedRef\u003cUser | null\u003e\n  /**\n   * The session object.\n   */\n  session: Ref\u003cUserSession\u003e\n  /**\n   * Fetch the user session from the server.\n   */\n  fetch: () =\u003e Promise\u003cvoid\u003e\n  /**\n   * Clear the user session and remove the session cookie.\n   */\n  clear: () =\u003e Promise\u003cvoid\u003e\n  /**\n   * Open the OAuth route in a popup that auto-closes when successful.\n   */\n  openInPopup: (route: string, size?: { width?: number, height?: number }) =\u003e void\n}\n```\n\n\u003e [!IMPORTANT]\n\u003e Nuxt Auth Utils uses the `/api/_auth/session` route for session management. Ensure your API route middleware doesn't interfere with this path.\n\n## Server Utils\n\nThe following helpers are auto-imported in your `server/` directory.\n\n### Session Management\n\n```ts\n// Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call\n// Only store the data that allow you to recognize a user, but do not store sensitive data\n// Merges new data with existing data using unjs/defu library\nawait setUserSession(event, {\n  // User data\n  user: {\n    login: 'atinux'\n  },\n  // Private data accessible only on server/ routes\n  secure: {\n    apiToken: '1234567890'\n  },\n  // Any extra fields for the session data\n  loggedInAt: new Date()\n})\n\n// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data\nawait replaceUserSession(event, data)\n\n// Get the current user session\nconst session = await getUserSession(event)\n\n// Clear the current user session\nawait clearUserSession(event)\n\n// Require a user session (send back 401 if no `user` key in session)\nconst session = await requireUserSession(event)\n```\n\nYou can define the type for your user session by creating a type declaration file (for example, `auth.d.ts`) in your project to augment the `UserSession` type:\n\n```ts\n// auth.d.ts\ndeclare module '#auth-utils' {\n  interface User {\n    // Add your own fields\n  }\n\n  interface UserSession {\n    // Add your own fields\n  }\n\n  interface SecureSessionData {\n    // Add your own fields\n  }\n}\n\nexport {}\n```\n\n\u003e [!IMPORTANT]\n\u003e Since we encrypt and store session data in cookies, we're constrained by the 4096-byte cookie size limit. Store only essential information.\n\n### OAuth Event Handlers\n\nAll handlers can be auto-imported and used in your server routes or API routes.\n\nThe pattern is `defineOAuth\u003cProvider\u003eEventHandler({ onSuccess, config?, onError? })`, example: `defineOAuthGitHubEventHandler`.\n\nThe helper returns an event handler that automatically redirects to the provider authorization page and then calls `onSuccess` or `onError` depending on the result.\n\nThe `config` can be defined directly from the `runtimeConfig` in your `nuxt.config.ts`:\n\n```ts\nexport default defineNuxtConfig({\n  runtimeConfig: {\n    oauth: {\n      // provider in lowercase (github, google, etc.)\n      \u003cprovider\u003e: {\n        clientId: '...',\n        clientSecret: '...'\n      }\n    }\n  }\n})\n```\n\nIt can also be set using environment variables:\n\n- `NUXT_OAUTH_\u003cPROVIDER\u003e_CLIENT_ID`\n- `NUXT_OAUTH_\u003cPROVIDER\u003e_CLIENT_SECRET`\n\n\u003e Provider is in uppercase (GITHUB, GOOGLE, etc.)\n\n#### Supported OAuth Providers\n\n- Apple\n- Atlassian\n- Auth0\n- Authentik\n- AWS Cognito\n- Azure B2C\n- Battle.net\n- Bluesky (AT Protocol)\n- Discord\n- Dropbox\n- Facebook\n- GitHub\n- GitLab\n- Gitea\n- Google\n- Heroku\n- Hubspot\n- Instagram\n- Kick\n- Keycloak\n- Line\n- Linear\n- LinkedIn\n- LiveChat\n- Microsoft\n- PayPal\n- Polar\n- Salesforce\n- Seznam\n- Slack\n- Spotify\n- Steam\n- Strava\n- TikTok\n- Twitch\n- VK\n- WorkOS\n- X (Twitter)\n- XSUAA\n- Yandex\n- Zitadel\n\nYou can add your favorite provider by creating a new file in [src/runtime/server/lib/oauth/](https://github.com/atinux/nuxt-auth-utils/tree/main/src/runtime/server/lib/oauth).\n\n#### Example\n\nExample: `~/server/routes/auth/github.get.ts`\n\n```ts\nexport default defineOAuthGitHubEventHandler({\n  config: {\n    emailRequired: true\n  },\n  async onSuccess(event, { user, tokens }) {\n    await setUserSession(event, {\n      user: {\n        githubId: user.id\n      }\n    })\n    return sendRedirect(event, '/')\n  },\n  // Optional, will return a json error and 401 status code by default\n  onError(event, error) {\n    console.error('GitHub OAuth error:', error)\n    return sendRedirect(event, '/')\n  },\n})\n```\n\nMake sure to set the callback URL in your OAuth app settings as `\u003cyour-domain\u003e/auth/github`.\n\nIf the redirect URL mismatch in production, this means that the module cannot guess the right redirect URL. You can set the `NUXT_OAUTH_\u003cPROVIDER\u003e_REDIRECT_URL` env variable to overwrite the default one.\n\n### Password Hashing\n\nNuxt Auth Utils provides password hashing utilities like `hashPassword` and `verifyPassword` to hash and verify passwords by using [scrypt](https://en.wikipedia.org/wiki/Scrypt) as it is supported in many JS runtime.\n\n```ts\nconst hashedPassword = await hashPassword('user_password')\n\nif (await verifyPassword(hashedPassword, 'user_password')) {\n  // Password is valid\n}\n```\n\nYou can configure the scrypt options in your `nuxt.config.ts`:\n\n```ts\nexport default defineNuxtConfig({\n  modules: ['nuxt-auth-utils'],\n  auth: {\n    hash: {\n      scrypt: {\n        // See https://github.com/adonisjs/hash/blob/94637029cd526783ac0a763ec581306d98db2036/src/types.ts#L144\n      }\n    }\n  }\n})\n```\n\n### AT Protocol\n\nSocial networks that rely on AT Protocol (e.g., Bluesky) slightly differ from a regular OAuth flow.\n\nTo enable OAuth with AT Protocol, you need to:\n\n1. Install the peer dependencies:\n\n```bash\nnpx nypm i @atproto/oauth-client-node @atproto/api\n```\n\n2. Enable it in your `nuxt.config.ts`\n\n```ts\nexport default defineNuxtConfig({\n  auth: {\n    atproto: true\n  }\n})\n```\n\n### WebAuthn (passkey)\n\nWebAuthn (Web Authentication) is a web standard that enhances security by replacing passwords with passkeys using public key cryptography. Users can authenticate with biometric data (like fingerprints or facial recognition) or physical devices (like USB keys), reducing the risk of phishing and password breaches. This approach offers a more secure and user-friendly authentication method, supported by major browsers and platforms.\n\nTo enable WebAuthn you need to:\n\n1. Install the peer dependencies:\n\n```bash\nnpx nypm i @simplewebauthn/server@11 @simplewebauthn/browser@11\n```\n\n2. Enable it in your `nuxt.config.ts`\n\n```ts\nexport default defineNuxtConfig({\n  auth: {\n    webAuthn: true\n  }\n})\n```\n\n#### Example\n\nIn this example we will implement the very basic steps to register and authenticate a credential.\n\nThe full code can be found in the [playground](https://github.com/atinux/nuxt-auth-utils/blob/main/playground/server/api/webauthn). The example uses a SQLite database with the following minimal tables:\n\n```sql\nCREATE TABLE users (\n  id INTEGER PRIMARY KEY AUTOINCREMENT,\n  email TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS credentials (\n  userId INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE,\n  id TEXT UNIQUE NOT NULL,\n  publicKey TEXT NOT NULL,\n  counter INTEGER NOT NULL,\n  backedUp INTEGER NOT NULL,\n  transports TEXT NOT NULL,\n  PRIMARY KEY (\"userId\", \"id\")\n);\n```\n\n- For the `users` table it is important to have a unique identifier such as a username or email (here we use email). When creating a new credential, this identifier is required and stored with the passkey on the user's device, password manager, or authenticator.\n- The `credentials` table stores:\n  - The `userId` from the `users` table.\n  - The credential `id` (as unique index)\n  - The credential `publicKey`\n  - A `counter`. Each time a credential is used, the counter is incremented. We can use this value to perform extra security checks. More about `counter` can be read [here](https://simplewebauthn.dev/docs/packages/server#3-post-registration-responsibilities). For this example, we won't be using the counter. But you should update the counter in your database with the new value.\n  - A `backedUp` flag. Normally, credentials are stored on the generating device. When you use a password manager or authenticator, the credential is \"backed up\" because it can be used on multiple devices. See [this section](https://arc.net/l/quote/ugaemxot) for more details.\n  - The credential `transports`. It is an array of strings that indicate how the credential communicates with the client. It is used to show the correct UI for the user to utilize the credential. Again, see [this section](https://arc.net/l/quote/ycxtiorp) for more details.\n\nThe following code does not include the actual database queries, but shows the general steps to follow. The full example can be found in the playground: [registration](https://github.com/atinux/nuxt-auth-utils/blob/main/playground/server/api/webauthn/register.post.ts), [authentication](https://github.com/atinux/nuxt-auth-utils/blob/main/playground/server/api/webauthn/authenticate.post.ts) and the [database setup](https://github.com/atinux/nuxt-auth-utils/blob/main/playground/server/plugins/database.ts).\n\n```ts\n// server/api/webauthn/register.post.ts\nimport { z } from 'zod'\nexport default defineWebAuthnRegisterEventHandler({\n  // optional\n  async validateUser(userBody, event) {\n    // bonus: check if the user is already authenticated to link a credential to his account\n    // We first check if the user is already authenticated by getting the session\n    // And verify that the email is the same as the one in session\n    const session = await getUserSession(event)\n    if (session.user?.email \u0026\u0026 session.user.email !== userBody.userName) {\n      throw createError({ statusCode: 400, message: 'Email not matching curent session' })\n    }\n\n    // If he registers a new account with credentials\n    return z.object({\n      // we want the userName to be a valid email\n      userName: z.string().email() \n    }).parse(userBody)\n  },\n  async onSuccess(event, { credential, user }) {\n    // The credential creation has been successful\n    // We need to create a user if it does not exist\n    const db = useDatabase()\n\n    // Get the user from the database\n    let dbUser = await db.sql`...`\n    if (!dbUser) {\n      // Store new user in database \u0026 its credentials\n      dbUser = await db.sql`...`\n    }\n\n    // we now need to store the credential in our database and link it to the user\n    await db.sql`...`\n\n    // Set the user session\n    await setUserSession(event, {\n      user: {\n        id: dbUser.id\n      },\n      loggedInAt: Date.now(),\n    })\n  },\n})\n```\n\n```ts\n// server/api/webauthn/authenticate.post.ts\nexport default defineWebAuthnAuthenticateEventHandler({\n  // Optionally, we can prefetch the credentials if the user gives their userName during login\n  async allowCredentials(event, userName) {\n    const credentials = await useDatabase().sql`...`\n    // If no credentials are found, the authentication cannot be completed\n    if (!credentials.length)\n      throw createError({ statusCode: 400, message: 'User not found' })\n\n    // If user is found, only allow credentials that are registered\n    // The browser will automatically try to use the credential that it knows about\n    // Skipping the step for the user to select a credential for a better user experience\n    return credentials\n    // example: [{ id: '...' }]\n  },\n  async getCredential(event, credentialId) {\n    // Look for the credential in our database\n    const credential = await useDatabase().sql`...`\n\n    // If the credential is not found, there is no account to log in to\n    if (!credential)\n      throw createError({ statusCode: 400, message: 'Credential not found' })\n\n    return credential\n  },\n  async onSuccess(event, { credential, authenticationInfo }) {\n    // The credential authentication has been successful\n    // We can look it up in our database and get the corresponding user\n    const db = useDatabase()\n    const user = await db.sql`...`\n\n    // Update the counter in the database (authenticationInfo.newCounter)\n    await db.sql`...`\n\n    // Set the user session\n    await setUserSession(event, {\n      user: {\n        id: user.id\n      },\n      loggedInAt: Date.now(),\n    })\n  },\n})\n```\n\n\u003e [!IMPORTANT]\n\u003e Webauthn uses challenges to prevent replay attacks. By default, this module does not make use if this feature. If you want to use challenges (**which is highly recommended**), the `storeChallenge` and `getChallenge` functions are provided. An attempt ID is created and sent with each authentication request. You can use this ID to store the challenge in a database or KV store as shown in the example below.\n\n\u003e ```ts\n\u003e export default defineWebAuthnAuthenticateEventHandler({\n\u003e   async storeChallenge(event, challenge, attemptId) {\n\u003e     // Store the challenge in a KV store or DB\n\u003e     await useStorage().setItem(`attempt:${attemptId}`, challenge)\n\u003e   },\n\u003e   async getChallenge(event, attemptId) {\n\u003e     const challenge = await useStorage().getItem(`attempt:${attemptId}`)\n\u003e\n\u003e     // Make sure to always remove the attempt because they are single use only!\n\u003e     await useStorage().removeItem(`attempt:${attemptId}`)\n\u003e\n\u003e     if (!challenge)\n\u003e       throw createError({ statusCode: 400, message: 'Challenge expired' })\n\u003e\n\u003e     return challenge\n\u003e   },\n\u003e   async onSuccess(event, { authenticator }) {\n\u003e     // ...\n\u003e   },\n\u003e })\n\u003e ```\n\nOn the frontend it is as simple as:\n\n```vue\n\u003cscript setup lang=\"ts\"\u003e\nconst { register, authenticate } = useWebAuthn({\n  registerEndpoint: '/api/webauthn/register', // Default\n  authenticateEndpoint: '/api/webauthn/authenticate', // Default\n})\nconst { fetch: fetchUserSession } = useUserSession()\n\nconst userName = ref('')\nasync function signUp() {\n  await register({ userName: userName.value })\n    .then(fetchUserSession) // refetch the user session\n}\n\nasync function signIn() {\n  await authenticate(userName.value)\n    .then(fetchUserSession) // refetch the user session\n}\n\u003c/script\u003e\n\n\u003ctemplate\u003e\n  \u003cform @submit.prevent=\"signUp\"\u003e\n    \u003cinput v-model=\"userName\" placeholder=\"Email or username\" /\u003e\n    \u003cbutton type=\"submit\"\u003eSign up\u003c/button\u003e\n  \u003c/form\u003e\n  \u003cform @submit.prevent=\"signIn\"\u003e\n    \u003cinput v-model=\"userName\" placeholder=\"Email or username\" /\u003e\n    \u003cbutton type=\"submit\"\u003eSign in\u003c/button\u003e\n  \u003c/form\u003e\n\u003c/template\u003e\n```\n\nTake a look at the [`WebAuthnModal.vue`](https://github.com/atinux/nuxt-auth-utils/blob/main/playground/components/WebAuthnModal.vue) for a full example.\n\n#### Demo\n\nA full demo can be found on https://todo-passkeys.nuxt.dev using [Drizzle ORM](https://orm.drizzle.team/) and [NuxtHub](https://hub.nuxt.com).\n\nThe source code of the demo is available on https://github.com/atinux/todo-passkeys.\n\n### Extend Session\n\nWe leverage hooks to let you extend the session data with your own data or log when the user clears the session.\n\n```ts\n// server/plugins/session.ts\nexport default defineNitroPlugin(() =\u003e {\n  // Called when the session is fetched during SSR for the Vue composable (/api/_auth/session)\n  // Or when we call useUserSession().fetch()\n  sessionHooks.hook('fetch', async (session, event) =\u003e {\n    // extend User Session by calling your database\n    // or\n    // throw createError({ ... }) if session is invalid for example\n  })\n\n  // Called when we call useUserSession().clear() or clearUserSession(event)\n  sessionHooks.hook('clear', async (session, event) =\u003e {\n    // Log that user logged out\n  })\n})\n```\n\n## Server-Side Rendering\n\nYou can make authenticated requests both from the client and the server. However, you must use `useRequestFetch()` to make authenticated requests during SSR if you are not using `useFetch()`\n\n```vue\n\u003cscript setup lang=\"ts\"\u003e\n// When using useAsyncData\nconst { data } = await useAsyncData('team', () =\u003e useRequestFetch()('/api/protected-endpoint'))\n\n// useFetch will automatically use useRequestFetch during SSR\nconst { data } = await useFetch('/api/protected-endpoint')\n\u003c/script\u003e\n```\n\n\u003e There's [an open issue](https://github.com/nuxt/nuxt/issues/24813) to include credentials in `$fetch` in Nuxt.\n\n## Hybrid Rendering\n\nWhen using [Nuxt `routeRules`](https://nuxt.com/docs/guide/concepts/rendering#hybrid-rendering) to prerender or cache your pages, Nuxt Auth Utils will not fetch the user session during prerendering but instead fetch it on the client-side (after hydration).\n\nThis is because the user session is stored in a secure cookie and cannot be accessed during prerendering.\n\n**This means that you should not rely on the user session during prerendering.**\n\n### `\u003cAuthState\u003e` component\n\nYou can use the `\u003cAuthState\u003e` component to safely display auth-related data in your components without worrying about the rendering mode.\n\nOne common use case if the Login button in the header:\n\n```vue\n\u003ctemplate\u003e\n  \u003cheader\u003e\n    \u003cAuthState v-slot=\"{ loggedIn, clear }\"\u003e\n      \u003cbutton v-if=\"loggedIn\" @click=\"clear\"\u003eLogout\u003c/button\u003e\n      \u003cNuxtLink v-else to=\"/login\"\u003eLogin\u003c/NuxtLink\u003e\n    \u003c/AuthState\u003e\n  \u003c/header\u003e\n\u003c/template\u003e\n```\n\nIf the page is cached or prerendered, nothing will be rendered until the user session is fetched on the client-side.\n\nYou can use the `placeholder` slot to show a placeholder on server-side and while the user session is being fetched on client-side for the prerendered pages:\n\n```vue\n\u003ctemplate\u003e\n  \u003cheader\u003e\n    \u003cAuthState\u003e\n      \u003ctemplate #default=\"{ loggedIn, clear }\"\u003e\n        \u003cbutton v-if=\"loggedIn\" @click=\"clear\"\u003eLogout\u003c/button\u003e\n        \u003cNuxtLink v-else to=\"/login\"\u003eLogin\u003c/NuxtLink\u003e\n      \u003c/template\u003e\n      \u003ctemplate #placeholder\u003e\n        \u003cbutton disabled\u003eLoading...\u003c/button\u003e\n      \u003c/template\u003e\n    \u003c/AuthState\u003e\n  \u003c/header\u003e\n\u003c/template\u003e\n```\n\nIf you are caching your routes with `routeRules`, please make sure to use [Nitro](https://github.com/unjs/nitro) \u003e= `2.9.7` to support the client-side fetching of the user session.\n\n## WebSocket Support\n\nNuxt Auth Utils is compatible with [Nitro WebSockets](https://nitro.build/guide/websocket).\n\nMake sure to enable the `experimental.websocket` option in your `nuxt.config.ts`:\n\n```ts\nexport default defineNuxtConfig({\n  nitro: {\n    experimental: {\n      websocket: true\n    }\n  }\n})\n```\n\nYou can use the `requireUserSession` function in the `upgrade` function to check if the user is authenticated before upgrading the WebSocket connection.\n\n```ts\n// server/routes/ws.ts\nexport default defineWebSocketHandler({\n  async upgrade(request) {\n    // Make sure the user is authenticated before upgrading the WebSocket connection\n    await requireUserSession(request)\n  },\n  async open(peer) {\n    const { user } = await requireUserSession(peer)\n\n    peer.send(`Hello, ${user.name}!`)\n  },\n  message(peer, message) {\n    peer.send(`Echo: ${message}`)\n  },\n})\n```\n\nThen, in your application, you can use the [useWebSocket](https://vueuse.org/core/useWebSocket/) composable to connect to the WebSocket:\n\n```vue\n\u003cscript setup\u003e\nconst { status, data, send, open, close } = useWebSocket('/ws', { immediate: false })\n\n// Only open the websocket after the page is hydrated (client-only)\nonMounted(open)\n\u003c/script\u003e\n\n\u003ctemplate\u003e\n  \u003cdiv\u003e\n    \u003cp\u003eStatus: {{ status }}\u003c/p\u003e\n    \u003cp\u003eData: {{ data }}\u003c/p\u003e\n    \u003cp\u003e\n      \u003cbutton @click=\"open\"\u003eOpen\u003c/button\u003e\n      \u003cbutton @click=\"close(1000, 'Closing')\"\u003eClose\u003c/button\u003e\n      \u003cbutton @click=\"send('hello')\"\u003eSend hello\u003c/button\u003e\n    \u003c/p\u003e\n  \u003c/div\u003e\n\u003c/template\u003e\n```\n\n## Configuration\n\nWe leverage `runtimeConfig.session` to give the defaults option to [h3 `useSession`](https://h3.unjs.io/examples/handle-session).\n\nYou can overwrite the options in your `nuxt.config.ts`:\n\n```ts\nexport default defineNuxtConfig({\n  modules: ['nuxt-auth-utils'],\n  runtimeConfig: {\n    session: {\n      maxAge: 60 * 60 * 24 * 7 // 1 week\n    }\n  }\n})\n```\n\nOur defaults are:\n\n```ts\n{\n  name: 'nuxt-session',\n  password: process.env.NUXT_SESSION_PASSWORD || '',\n  cookie: {\n    sameSite: 'lax'\n  }\n}\n```\n\nYou can also overwrite the session config by passing it as 3rd argument of the `setUserSession` and `replaceUserSession` functions:\n\n```ts\nawait setUserSession(event, { ... } , {\n  maxAge: 60 * 60 * 24 * 7 // 1 week\n})\n```\n\nCheckout the [`SessionConfig`](https://github.com/unjs/h3/blob/c04c458810e34eb15c1647e1369e7d7ef19f567d/src/utils/session.ts#L20) for all options.\n\n## More\n\n- [nuxt-authorization](https://github.com/barbapapazes/nuxt-authorization): Authorization module for managing permissions inside a Nuxt app, compatible with `nuxt-auth-utils`\n\n## Development\n\n```bash\n# Install dependencies\npnpm install\n\n# Generate type stubs\npnpm run dev:prepare\n\n# Develop with the playground\npnpm run dev\n\n# Build the playground\npnpm run dev:build\n\n# Run ESLint\npnpm run lint\n\n# Run Vitest\npnpm run test\npnpm run test:watch\n\n# Release new version\npnpm run release\n```\n\n\u003c!-- Badges --\u003e\n[npm-version-src]: https://img.shields.io/npm/v/nuxt-auth-utils/latest.svg?style=flat\u0026colorA=020420\u0026colorB=00DC82\n[npm-version-href]: https://npmjs.com/package/nuxt-auth-utils\n\n[npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-auth-utils.svg?style=flat\u0026colorA=020420\u0026colorB=00DC82\n[npm-downloads-href]: https://npm.chart.dev/nuxt-auth-utils\n\n[license-src]: https://img.shields.io/npm/l/nuxt-auth-utils.svg?style=flat\u0026colorA=020420\u0026colorB=00DC82\n[license-href]: https://npmjs.com/package/nuxt-auth-utils\n\n[nuxt-src]: https://img.shields.io/badge/Nuxt-020420?logo=nuxt.js\n[nuxt-href]: https://nuxt.com\n","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAtinux%2Fnuxt-auth-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAtinux%2Fnuxt-auth-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAtinux%2Fnuxt-auth-utils/lists"}