nuxt-auth-utils

Add authentication with secured & sealed cookie sessions.

Nuxt Auth Utils

npm versionnpm downloadsLicenseNuxt

Add Authentication to Nuxt applications with secured & sealed cookies sessions.

Features

It has few dependencies (only from UnJS), run on multiple JS environments (Node, Deno, Workers) and is fully typed with TypeScript.

Requirements

This module requires Nuxt 4.6 or later. If you upgrade from v0.5, read Migrate from v0.5.

This module only works with a Nuxt server running as it uses server API routes (nuxt build).

This means that you cannot use this module with nuxt generate.

You can anyway use Hybrid Rendering to pre-render pages of your application or disable server-side rendering completely.

Quick Setup

  1. Add nuxt-auth-utils in your Nuxt project
npx nuxi@latest module add auth-utils
  1. Set the NUXT_APP_SECRET env variable in production, with at least 32 characters.
# Generate a secret
openssl rand -base64 32
# .env
NUXT_APP_SECRET=<the-generated-secret>

Nuxt Auth Utils seals the session cookie with a secret that it derives from the Nuxt appSecret. In development, Nuxt generates an appSecret for you if none is set. Builds never generate one, so you must set NUXT_APP_SECRET in production.

  1. That's it! You can now add authentication to your Nuxt app ✨

Vue Composable

Nuxt Auth Utils automatically adds some plugins to fetch the current user session to let you access it from your Vue components.

User Session

<script setup>
const { loggedIn, user, session, fetch, clear, openInPopup } = useUserSession()
</script>

<template>
  <div v-if="loggedIn">
    <h1>Welcome {{ user.login }}!</h1>
    <p>Logged in since {{ session.loggedInAt }}</p>
    <button @click="clear">Logout</button>
  </div>
  <div v-else>
    <h1>Not logged in</h1>
    <a href="/auth/github">Login with GitHub</a>
    <!-- or open the OAuth route in a popup -->
    <button @click="openInPopup('/auth/github')">Login with GitHub</button>
  </div>
</template>

TypeScript Signature:

interface UserSessionComposable {
  /**
   * Computed indicating if the auth session is ready
   */
  ready: ComputedRef<boolean>
  /**
   * Computed indicating if the user is logged in.
   */
  loggedIn: ComputedRef<boolean>
  /**
   * The user object if logged in, null otherwise.
   */
  user: ComputedRef<User | null>
  /**
   * The session object.
   */
  session: Ref<UserSession>
  /**
   * Fetch the user session from the server.
   */
  fetch: () => Promise<void>
  /**
   * Clear the user session and remove the session cookie.
   */
  clear: () => Promise<void>
  /**
   * Open the OAuth route in a popup that auto-closes when successful.
   */
  openInPopup: (route: string, size?: { width?: number, height?: number }) => void
}

!IMPORTANT Nuxt Auth Utils uses the /api/_auth/session route for session management. Ensure your API route middleware doesn't interfere with this path.

Server Utils

The following helpers are auto-imported in your server/ directory.

They accept the event of a handler defined with defineEventHandler from nuxt/server. On Nuxt 4, they also accept the event of a handler defined with the auto-imported defineEventHandler from h3.

// server/api/me.get.ts
import { defineEventHandler } from 'nuxt/server'

export default defineEventHandler(async (event) => {
  const { user } = await requireUserSession(event)

  return user
})

Session Management

// Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call
// Only store the data that allow you to recognize a user, but do not store sensitive data
// Merges new data with existing data using unjs/defu library
await setUserSession(event, {
  // User data
  user: {
    login: 'atinux'
  },
  // Private data accessible only on server/ routes
  secure: {
    apiToken: '1234567890'
  },
  // Any extra fields for the session data
  loggedInAt: new Date()
})

// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data
await replaceUserSession(event, data)

// Get the current user session
const session = await getUserSession(event)

// Clear the current user session
await clearUserSession(event)

// Require a user session (send back 401 if no `user` key in session)
const session = await requireUserSession(event)

// Customize the error status and message
const session = await requireUserSession(event, { status: 403, message: 'Forbidden' })

You 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:

// shared/types/auth.d.ts
declare module '#auth-utils' {
  interface User {
    // Add your own fields
  }

  interface UserSession {
    // Add your own fields
  }

  interface SecureSessionData {
    // Add your own fields
  }
}

export {}

!IMPORTANT Since we encrypt and store session data in cookies, we're constrained by the 4096-byte cookie size limit. Store only essential information.

OAuth Event Handlers

All handlers can be auto-imported and used in your server routes or API routes.

The pattern is defineOAuth<Provider>EventHandler({ onSuccess, config?, onError? }), example: defineOAuthGitHubEventHandler.

The helper returns an event handler that automatically redirects to the provider authorization page and then calls onSuccess or onError depending on the result.

The config can be defined directly from the runtimeConfig in your nuxt.config.ts:

export default defineNuxtConfig({
  runtimeConfig: {
    oauth: {
      // provider in lowercase (github, google, etc.)
      <provider>: {
        clientId: '...',
        clientSecret: '...'
      }
    }
  }
})

It can also be set using environment variables:

  • NUXT_OAUTH_<PROVIDER>_CLIENT_ID
  • NUXT_OAUTH_<PROVIDER>_CLIENT_SECRET

Provider is in uppercase (GITHUB, GOOGLE, etc.)

Supported OAuth Providers

  • Apple
  • Atlassian
  • Auth0
  • Authentik
  • AWS Cognito
  • Azure B2C
  • Battle.net
  • Bluesky (AT Protocol)
  • Box.com
  • Cloudflare
  • Discord
  • Dropbox
  • Facebook
  • GitHub
  • GitLab
  • Gitea
  • Google
  • Heroku
  • Hubspot
  • Instagram
  • Kick
  • Keycloak
  • Line
  • Linear
  • LinkedIn
  • LiveChat
  • Mastodon
  • Microsoft
  • OIDC / OpenID Connect (Generic)
  • Okta
  • Ory
  • osu!
  • PayPal
  • Polar
  • Riot Games
  • Salesforce
  • Seznam
  • Shopify Customer
  • Slack
  • Spotify
  • Steam
  • Strava
  • TikTok
  • Twitch
  • VK
  • WeChat
  • WorkOS
  • X (Twitter)
  • XSUAA
  • Yandex
  • Zendesk
  • Zitadel

You can add your favorite provider by creating a new file in src/runtime/server/lib/oauth/.

Example

Example: ~/server/routes/auth/github.get.ts

import { sendRedirect } from 'nuxt/server'

export default defineOAuthGitHubEventHandler({
  config: {
    emailRequired: true
  },
  async onSuccess(event, { user, tokens }) {
    await setUserSession(event, {
      user: {
        githubId: user.id
      }
    })
    return sendRedirect(event, '/')
  },
  // Optional, will return a json error and 401 status code by default
  onError(event, error) {
    console.error('GitHub OAuth error:', error)
    return sendRedirect(event, '/')
  },
})

The event given to onSuccess and onError is a RequestEvent from nuxt/server. Import the helpers you use from nuxt/server, for example sendRedirect. On Nuxt 4, the auto-imported h3 helpers also work, but TypeScript reports a type error.

Make sure to set the callback URL in your OAuth app settings as <your-domain>/auth/github.

If the redirect URL mismatch in production, this means that the module cannot guess the right redirect URL. You can set the NUXT_OAUTH_<PROVIDER>_REDIRECT_URL env variable to overwrite the default one.

Mastodon

Mastodon does not have a single shared OAuth server: every account lives on its own instance (e.g. mastodon.social, h4.io), and there is no portable identity across instances the way there is with AT Protocol/Bluesky. Because of this, the provider needs to know which instance to talk to before it can start the flow, and it registers an application against that instance on first use via POST /api/v1/apps (Mastodon's own API, not the RFC 7591 Dynamic Client Registration spec it superficially resembles).

// server/routes/auth/mastodon.get.ts
export default defineOAuthMastodonEventHandler({
  async onSuccess(event, { user }) {
    await setUserSession(event, {
      user: {
        mastodon: user.acct,
      },
    })
    return sendRedirect(event, '/')
  },
})

The instance can be provided either as a static instance config/NUXT_OAUTH_MASTODON_INSTANCE env variable, or per-request as an instance query parameter, e.g. /auth/mastodon?instance=mastodon.social:

navigateTo({ path: '/auth/mastodon', query: { instance: 'mastodon.social' } }, { external: true })

A full handle (@user@mastodon.social) is also accepted and only the instance part is used, since that's all that is required to start the OAuth flow.

Registered apps are cached in memory per instance and redirect URL for the lifetime of the server process, so it does not re-register on every login. The callback doesn't depend on this cache, so after a restart or on another worker, the next login only registers a new application.

Password Hashing

Nuxt Auth Utils provides password hashing utilities like hashPassword and verifyPassword to hash and verify passwords by using scrypt as it is supported in many JS runtime.

const hashedPassword = await hashPassword('user_password')

if (await verifyPassword(hashedPassword, 'user_password')) {
  // Password is valid
}

It also provides a passwordNeedsRehash function to check if a password needs to be rehashed. This is useful when the hash settings are changed, such as as increasing the scrypt cost parameters.

const needsRehash = passwordNeedsRehash(hashedPassword)

if (needsRehash) {
  // Password needs to be rehashed
  hashedPassword = await hashPassword('user_password')
}

You can configure the scrypt options in your nuxt.config.ts:

export default defineNuxtConfig({
  modules: ['nuxt-auth-utils'],
  auth: {
    hash: {
      scrypt: {
        // See https://github.com/adonisjs/hash/blob/94637029cd526783ac0a763ec581306d98db2036/src/types.ts#L144
      }
    }
  }
})

AT Protocol

Social networks that rely on AT Protocol (e.g., Bluesky) slightly differ from a regular OAuth flow.

To enable OAuth with AT Protocol, you need to:

  1. Install the peer dependencies:
npx nypm i @atproto/oauth-client-node @atproto/api
  1. Enable it in your nuxt.config.ts
export default defineNuxtConfig({
  auth: {
    atproto: true
  }
})

WebAuthn (passkey)

WebAuthn (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.

To enable WebAuthn you need to:

  1. Install the peer dependencies:
npx nypm i @simplewebauthn/server@13 @simplewebauthn/browser@13
  1. Enable it in your nuxt.config.ts
export default defineNuxtConfig({
  auth: {
    webAuthn: true
  }
})

Example

In this example we will implement the very basic steps to register and authenticate a credential.

The full code can be found in the playground. The example uses a SQLite database with the following minimal tables:

CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  email TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS credentials (
  userId INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE,
  id TEXT UNIQUE NOT NULL,
  publicKey TEXT NOT NULL,
  counter INTEGER NOT NULL,
  backedUp INTEGER NOT NULL,
  transports TEXT NOT NULL,
  PRIMARY KEY ("userId", "id")
);
  • 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.
  • The credentials table stores:
    • The userId from the users table.
    • The credential id (as unique index)
    • The credential publicKey
    • 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. For this example, we won't be using the counter. But you should update the counter in your database with the new value.
    • 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 for more details.
    • 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 for more details.

The 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, authentication and the database setup.

// server/api/webauthn/register.post.ts
import { z } from 'zod'
export default defineWebAuthnRegisterEventHandler({
  // optional
  async validateUser(userBody, event) {
    // bonus: check if the user is already authenticated to link a credential to his account
    // We first check if the user is already authenticated by getting the session
    // And verify that the email is the same as the one in session
    const session = await getUserSession(event)
    if (session.user?.email && session.user.email !== userBody.userName) {
      throw createError({ status: 400, message: 'Email not matching current session' })
    }

    // If he registers a new account with credentials
    return z.object({
      // we want the userName to be a valid email
      userName: z.string().email()
    }).parse(userBody)
  },
  async onSuccess(event, { credential, user }) {
    // The credential creation has been successful
    // We need to create a user if it does not exist
    const db = useDatabase()

    // Get the user from the database
    let dbUser = await db.sql`...`
    if (!dbUser) {
      // Store new user in database & its credentials
      dbUser = await db.sql`...`
    }

    // we now need to store the credential in our database and link it to the user
    await db.sql`...`

    // Set the user session
    await setUserSession(event, {
      user: {
        id: dbUser.id
      },
      loggedInAt: Date.now(),
    })
  },
})

!TIP If you want to plug in and use the Community sourced list of AAGUIDS to decorate your display of added passkeys, you can access the the ID via credential.aaguid inside onSuccess

// server/api/webauthn/authenticate.post.ts
export default defineWebAuthnAuthenticateEventHandler({
  // Optionally, we can prefetch the credentials if the user gives their userName during login
  async allowCredentials(event, userName) {
    const credentials = await useDatabase().sql`...`
    // If no credentials are found, the authentication cannot be completed
    if (!credentials.length)
      throw createError({ status: 400, message: 'User not found' })

    // If user is found, only allow credentials that are registered
    // The browser will automatically try to use the credential that it knows about
    // Skipping the step for the user to select a credential for a better user experience
    return credentials
    // example: [{ id: '...' }]
  },
  async getCredential(event, credentialId) {
    // Look for the credential in our database
    const credential = await useDatabase().sql`...`

    // If the credential is not found, there is no account to log in to
    if (!credential)
      throw createError({ status: 400, message: 'Credential not found' })

    return credential
  },
  async onSuccess(event, { credential, authenticationInfo }) {
    // The credential authentication has been successful
    // We can look it up in our database and get the corresponding user
    const db = useDatabase()
    const user = await db.sql`...`

    // Update the counter in the database (authenticationInfo.newCounter)
    await db.sql`...`

    // Set the user session
    await setUserSession(event, {
      user: {
        id: user.id
      },
      loggedInAt: Date.now(),
    })
  },
})

!IMPORTANT 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.

export default defineWebAuthnAuthenticateEventHandler({
  async storeChallenge(event, challenge, attemptId) {
    // Store the challenge in a KV store or DB
    await useStorage().setItem(`attempt:${attemptId}`, challenge)
  },
  async getChallenge(event, attemptId) {
    const challenge = await useStorage().getItem(`attempt:${attemptId}`)

    // Make sure to always remove the attempt because they are single use only!
    await useStorage().removeItem(`attempt:${attemptId}`)

    if (!challenge)
      throw createError({ status: 400, message: 'Challenge expired' })

    return challenge
  },
  async onSuccess(event, { authenticator }) {
    // ...
  },
})

On the frontend it is as simple as:

<script setup lang="ts">
const { register, authenticate } = useWebAuthn({
  registerEndpoint: '/api/webauthn/register', // Default
  authenticateEndpoint: '/api/webauthn/authenticate', // Default
})
const { fetch: fetchUserSession } = useUserSession()

const userName = ref('')
async function signUp() {
  await register({ userName: userName.value })
    .then(fetchUserSession) // refetch the user session
}

async function signIn() {
  await authenticate(userName.value)
    .then(fetchUserSession) // refetch the user session
}
</script>

<template>
  <form @submit.prevent="signUp">
    <input v-model="userName" placeholder="Email or username" />
    <button type="submit">Sign up</button>
  </form>
  <form @submit.prevent="signIn">
    <input v-model="userName" placeholder="Email or username" />
    <button type="submit">Sign in</button>
  </form>
</template>

Take a look at the WebAuthnModal.vue for a full example.

Demo

A full demo can be found on https://todo-passkeys.nuxt.dev using Drizzle ORM and NuxtHub.

The source code of the demo is available on https://github.com/atinux/todo-passkeys.

Extend Session

We leverage hooks to let you extend the session data with your own data or log when the user clears the session.

// server/plugins/session.ts
// A server plugin is a function, so this file runs on Nuxt 4 (Nitro 2) and Nuxt 5 (Nitro 3)
export default () => {
  // Called when the session is fetched during SSR for the Vue composable (/api/_auth/session)
  // Or when we call useUserSession().fetch()
  sessionHooks.hook('fetch', async (session, event) => {
    // extend User Session by calling your database
    // or
    // throw createError({ ... }) if session is invalid for example
  })

  // Called when we call useUserSession().clear() or clearUserSession(event)
  sessionHooks.hook('clear', async (session, event) => {
    // Log that user logged out
  })
}

Server-Side Rendering

You 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()

<script setup lang="ts">
// When using useAsyncData
const { data } = await useAsyncData('team', () => useRequestFetch()('/api/protected-endpoint'))

// useFetch will automatically use useRequestFetch during SSR
const { data } = await useFetch('/api/protected-endpoint')
</script>

There's an open issue to include credentials in $fetch in Nuxt.

Hybrid Rendering

When using Nuxt routeRules 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).

This is because the user session is stored in a secure cookie and cannot be accessed during prerendering.

This means that you should not rely on the user session during prerendering.

You may also choose to instruct Nuxt Auth Utils to fetch the user session only on the client side, with the loadStrategy option in your nuxt.config.ts:

export default defineNuxtConfig({
  auth: {
    loadStrategy: 'client-only'
  }
})

When using the client-only load strategy, the user session can still be manually fetched on the server side by calling fetch from the useUserSession composable.

Disable session loading

You may also choose to disable session loading entirely, with the loadStrategy option in your nuxt.config.ts:

export default defineNuxtConfig({
  auth: {
    loadStrategy: 'none'
  }
})

When using the none load strategy, the user session can still be manually fetched by calling useUserSession().fetch().

<AuthState> component

You can use the <AuthState> component to safely display auth-related data in your components without worrying about the rendering mode.

One common use case if the Login button in the header:

<template>
  <header>
    <AuthState v-slot="{ loggedIn, clear }">
      <button v-if="loggedIn" @click="clear">Logout</button>
      <NuxtLink v-else to="/login">Login</NuxtLink>
    </AuthState>
  </header>
</template>

If the page is cached or prerendered or the load strategy set as client-only, nothing will be rendered until the user session is fetched on the client-side.

You 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:

<template>
  <header>
    <AuthState>
      <template #default="{ loggedIn, clear }">
        <button v-if="loggedIn" @click="clear">Logout</button>
        <NuxtLink v-else to="/login">Login</NuxtLink>
      </template>
      <template #placeholder>
        <button disabled>Loading...</button>
      </template>
    </AuthState>
  </header>
</template>

If you are caching your routes with routeRules, please make sure to use Nitro >= 2.9.7 to support the client-side fetching of the user session.

WebSocket Support

Nuxt Auth Utils is compatible with Nitro WebSockets.

Make sure to enable the experimental.websocket option in your nuxt.config.ts:

export default defineNuxtConfig({
  nitro: {
    experimental: {
      websocket: true
    }
  }
})

You can use the requireUserSession function in the upgrade function to check if the user is authenticated before upgrading the WebSocket connection. In WebSocket handlers, the session is read-only: setUserSession, replaceUserSession and clearUserSession throw an error when given a WebSocket peer or upgrade request.

// server/routes/ws.ts
// `defineWebSocketHandler` is not auto-imported on Nuxt 5, `h3` works on Nuxt 4 and Nuxt 5
import { defineWebSocketHandler } from 'h3'

export default defineWebSocketHandler({
  async upgrade(request) {
    // Make sure the user is authenticated before upgrading the WebSocket connection
    await requireUserSession(request)
  },
  async open(peer) {
    const { user } = await requireUserSession(peer)

    peer.send(`Hello, ${user.name}!`)
  },
  message(peer, message) {
    peer.send(`Echo: ${message}`)
  },
})

Then, in your application, you can use the useWebSocket composable to connect to the WebSocket:

<script setup>
const { status, data, send, open, close } = useWebSocket('/ws', { immediate: false })

// Only open the websocket after the page is hydrated (client-only)
onMounted(open)
</script>

<template>
  <div>
    <p>Status: {{ status }}</p>
    <p>Data: {{ data }}</p>
    <p>
      <button @click="open">Open</button>
      <button @click="close(1000, 'Closing')">Close</button>
      <button @click="send('hello')">Send hello</button>
    </p>
  </div>
</template>

Configuration

Nuxt Auth Utils stores the user session with useSession from nuxt/server. It uses runtimeConfig.session for the default options.

You can overwrite the options in your nuxt.config.ts:

export default defineNuxtConfig({
  modules: ['nuxt-auth-utils'],
  runtimeConfig: {
    session: {
      maxAge: 60 * 60 * 24 * 7 // 1 week
    }
  }
})

Our defaults are:

{
  name: 'nuxt-auth-session',
  cookie: {
    sameSite: 'lax'
  }
}

The available options are:

  • name: the name of the session cookie.
  • maxAge: the lifetime of the cookie and of the sealed session, in seconds.
  • cookie: the cookie options, merged over httpOnly: true, secure: true, sameSite: 'lax', and path: '/'.

The session is sealed with a secret that Nuxt derives from appSecret. The module ignores runtimeConfig.session.password.

You can also overwrite the session config by passing it as 3rd argument of the setUserSession and replaceUserSession functions:

await setUserSession(event, { ... } , {
  maxAge: 60 * 60 * 24 * 7 // 1 week
})

Migrate from v0.5

Nuxt Auth Utils v0.6 moves to nuxt/server, the server API of Nuxt 4.6. The same server code runs on Nuxt 4 and Nuxt 5. This release has breaking changes.

!WARNING All users are logged out once after the upgrade. The session cookie has a new name and a new format.

To migrate your app, follow these steps:

  1. Upgrade Nuxt to 4.6 or later.
  2. Generate a secret with openssl rand -base64 32.
  3. Set the secret as NUXT_APP_SECRET in your production environment.
  4. On Cloudflare Workers, set compatibility_date to 2025-04-01 or later, or add the nodejs_compat_populate_process_env compatibility flag. Otherwise the module can't read NUXT_APP_SECRET and the NUXT_OAUTH_* variables from your Worker variables and secrets.
  5. Remove NUXT_SESSION_PASSWORD from your environment and from your .env file. The module logs a warning while it is set.
  6. Change statusCode to status in createError() calls.
  7. In onSuccess and onError callbacks, import helpers such as sendRedirect from nuxt/server.

The other changes in v0.6 are:

  • The session cookie is nuxt-auth-session. It was nuxt-session, which is now the default name of useSession from nuxt/server.
  • The session can't be read from the x-nuxt-session-session request header anymore.
  • The sessionHeader, seal, crypto, generateId, and password session options are removed.
  • The event in the OAuth and WebAuthn callbacks is a RequestEvent from nuxt/server, and error is a NuxtError.
  • In WebSocket handlers, setUserSession, replaceUserSession and clearUserSession throw an error, as the session cookie can't be sent back to the client.
  • requireUserSession accepts a status option. The statusCode option still works, but it's deprecated.
  • Nuxt throws a 500 error if a session cookie is larger than 4096 bytes.
  • The session maxAge counts from the last write: each setUserSession call extends the cookie. In v0.5, it counted from when the session was created.
  • The session can't be named nuxt-session, the cookie of useSession() from nuxt/server. The module warns and uses nuxt-auth-session instead.
  • WebAuthn requires SimpleWebAuthn v13, with @simplewebauthn/server 13.3.2 or later. Import its JSON types from @simplewebauthn/server or @simplewebauthn/browser instead of @simplewebauthn/types.

Shared session between microservices and subdomains

To share a session between multiple applications, use the same NUXT_APP_SECRET and session name in each of them.

Any application with the same NUXT_APP_SECRET can also derive the other keys Nuxt derives from it, so share it only between applications you trust equally.

If the applications run on different subdomains, also set the session cookie domain to the parent domain in each nuxt.config.ts:

export default defineNuxtConfig({
  modules: ['nuxt-auth-utils'],
  runtimeConfig: {
    session: {
      cookie: {
        domain: '.example.com'
      }
    }
  }
})

The browser then sends the session cookie to every subdomain of example.com, and each application can decrypt it.

More

  • nuxt-authorization: Authorization module for managing permissions inside a Nuxt app, compatible with nuxt-auth-utils

Development

# Install dependencies
pnpm install

# Generate type stubs
pnpm run dev:prepare

# Develop with the playground
pnpm run dev

# Develop with the playground on the Nuxt 5 nightly (Nitro 3), run `pnpm install` to go back to the lockfile
pnpm run dev:v5

# Run the tests on the Nuxt 5 nightly
pnpm run install:nuxt5 && pnpm run dev:prepare && pnpm run test

# Build the playground
pnpm run dev:build

# Run ESLint
pnpm run lint

# Run Vitest
pnpm run test
pnpm run test:watch

Releases are automated with uppt: every push to main opens or updates a draft release PR from conventional commits. Merging it tags the version, creates the GitHub release and stages the npm publish, which is then approved on npmjs.com.