Gathering detailed insights and metrics for nuxt-auth-utils
Gathering detailed insights and metrics for nuxt-auth-utils
Gathering detailed insights and metrics for nuxt-auth-utils
Gathering detailed insights and metrics for nuxt-auth-utils
Add Authentication to Nuxt applications with secured & sealed cookies sessions.
npm install nuxt-auth-utils
Typescript
Module System
Node Version
NPM Version
35.5
Supply Chain
91
Quality
93.9
Maintenance
100
Vulnerability
99.3
License
Updated on 05 Dec 2024
Minified
Minified + Gzipped
TypeScript (92.4%)
Vue (7.44%)
JavaScript (0.16%)
Cumulative downloads
Total Downloads
Last day
-13%
Compared to previous day
Last week
-6.7%
Compared to previous week
Last month
14.7%
Compared to previous month
Last year
9,374.8%
Compared to previous year
2
Add Authentication to Nuxt applications with secured & sealed cookies sessions.
useUserSession()
Vue composable<AuthState>
componentIt has few dependencies (only from UnJS), run on multiple JS environments (Node, Deno, Workers) and is fully typed with TypeScript.
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.
nuxt-auth-utils
in your Nuxt project1npx nuxi@latest module add auth-utils
NUXT_SESSION_PASSWORD
env variable with at least 32 characters in the .env
.1# .env 2NUXT_SESSION_PASSWORD=password-with-at-least-32-characters
Nuxt Auth Utils generates one for you when running Nuxt in development the first time if no NUXT_SESSION_PASSWORD
is set.
Nuxt Auth Utils automatically adds some plugins to fetch the current user session to let you access it from your Vue components.
1<script setup> 2const { loggedIn, user, session, fetch, clear } = useUserSession() 3</script> 4 5<template> 6 <div v-if="loggedIn"> 7 <h1>Welcome {{ user.login }}!</h1> 8 <p>Logged in since {{ session.loggedInAt }}</p> 9 <button @click="clear">Logout</button> 10 </div> 11 <div v-else> 12 <h1>Not logged in</h1> 13 <a href="/auth/github">Login with GitHub</a> 14 </div> 15</template>
TypeScript Signature:
1interface UserSessionComposable { 2 /** 3 * Computed indicating if the auth session is ready 4 */ 5 ready: ComputedRef<boolean> 6 /** 7 * Computed indicating if the user is logged in. 8 */ 9 loggedIn: ComputedRef<boolean> 10 /** 11 * The user object if logged in, null otherwise. 12 */ 13 user: ComputedRef<User | null> 14 /** 15 * The session object. 16 */ 17 session: Ref<UserSession> 18 /** 19 * Fetch the user session from the server. 20 */ 21 fetch: () => Promise<void> 22 /** 23 * Clear the user session and remove the session cookie. 24 */ 25 clear: () => Promise<void> 26}
[!IMPORTANT] Nuxt Auth Utils uses the
/api/_auth/session
route for session management. Ensure your API route middleware doesn't interfere with this path.
The following helpers are auto-imported in your server/
directory.
1// Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call 2// Only store the data that allow you to recognize a user, but do not store sensitive data 3// Merges new data with existing data using unjs/defu library 4await setUserSession(event, { 5 // User data 6 user: { 7 login: 'atinux' 8 }, 9 // Private data accessible only on server/ routes 10 secure: { 11 apiToken: '1234567890' 12 }, 13 // Any extra fields for the session data 14 loggedInAt: new Date() 15}) 16 17// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data 18await replaceUserSession(event, data) 19 20// Get the current user session 21const session = await getUserSession(event) 22 23// Clear the current user session 24await clearUserSession(event) 25 26// Require a user session (send back 401 if no `user` key in session) 27const session = await requireUserSession(event)
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:
1// auth.d.ts 2declare module '#auth-utils' { 3 interface User { 4 // Add your own fields 5 } 6 7 interface UserSession { 8 // Add your own fields 9 } 10 11 interface SecureSessionData { 12 // Add your own fields 13 } 14} 15 16export {}
[!IMPORTANT] Since we encrypt and store session data in cookies, we're constrained by the 4096-byte cookie size limit. Store only essential information.
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
:
1export default defineNuxtConfig({ 2 runtimeConfig: { 3 oauth: { 4 // provider in lowercase (github, google, etc.) 5 <provider>: { 6 clientId: '...', 7 clientSecret: '...' 8 } 9 } 10 } 11})
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.)
You can add your favorite provider by creating a new file in src/runtime/server/lib/oauth/.
Example: ~/server/routes/auth/github.get.ts
1export default defineOAuthGitHubEventHandler({
2 config: {
3 emailRequired: true
4 },
5 async onSuccess(event, { user, tokens }) {
6 await setUserSession(event, {
7 user: {
8 githubId: user.id
9 }
10 })
11 return sendRedirect(event, '/')
12 },
13 // Optional, will return a json error and 401 status code by default
14 onError(event, error) {
15 console.error('GitHub OAuth error:', error)
16 return sendRedirect(event, '/')
17 },
18})
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.
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.
1const hashedPassword = await hashPassword('user_password') 2 3if (await verifyPassword(hashedPassword, 'user_password')) { 4 // Password is valid 5}
You can configure the scrypt options in your nuxt.config.ts
:
1export default defineNuxtConfig({
2 modules: ['nuxt-auth-utils'],
3 auth: {
4 hash: {
5 scrypt: {
6 // See https://github.com/adonisjs/hash/blob/94637029cd526783ac0a763ec581306d98db2036/src/types.ts#L144
7 }
8 }
9 }
10})
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:
1npx nypm i @simplewebauthn/server@11 @simplewebauthn/browser@11
nuxt.config.ts
1export default defineNuxtConfig({ 2 auth: { 3 webAuthn: true 4 } 5})
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:
1CREATE TABLE users ( 2 id INTEGER PRIMARY KEY AUTOINCREMENT, 3 email TEXT NOT NULL 4); 5 6CREATE TABLE IF NOT EXISTS credentials ( 7 userId INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE, 8 id TEXT UNIQUE NOT NULL, 9 publicKey TEXT NOT NULL, 10 counter INTEGER NOT NULL, 11 backedUp INTEGER NOT NULL, 12 transports TEXT NOT NULL, 13 PRIMARY KEY ("userId", "id") 14);
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.credentials
table stores:
userId
from the users
table.id
(as unique index)publicKey
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.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.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.
1// server/api/webauthn/register.post.ts
2import { z } from 'zod'
3export default defineWebAuthnRegisterEventHandler({
4 // optional
5 async validateUser(userBody, event) {
6 // bonus: check if the user is already authenticated to link a credential to his account
7 // We first check if the user is already authenticated by getting the session
8 // And verify that the email is the same as the one in session
9 const session = await getUserSession(event)
10 if (session.user?.email && session.user.email !== body.userName) {
11 throw createError({ statusCode: 400, message: 'Email not matching curent session' })
12 }
13
14 // If he registers a new account with credentials
15 return z.object({
16 // we want the userName to be a valid email
17 userName: z.string().email()
18 }).parse(userBody)
19 },
20 async onSuccess(event, { credential, user }) {
21 // The credential creation has been successful
22 // We need to create a user if it does not exist
23 const db = useDatabase()
24
25 // Get the user from the database
26 let dbUser = await db.sql`...`
27 if (!dbUser) {
28 // Store new user in database & its credentials
29 dbUser = await db.sql`...`
30 }
31
32 // we now need to store the credential in our database and link it to the user
33 await db.sql`...`
34
35 // Set the user session
36 await setUserSession(event, {
37 user: {
38 id: dbUser.id
39 },
40 loggedInAt: Date.now(),
41 })
42 },
43})
1// server/api/webauthn/authenticate.post.ts
2export default defineWebAuthnAuthenticateEventHandler({
3 // Optionally, we can prefetch the credentials if the user gives their userName during login
4 async allowCredentials(event, userName) {
5 const credentials = await useDatabase().sql`...`
6 // If no credentials are found, the authentication cannot be completed
7 if (!credentials.length)
8 throw createError({ statusCode: 400, message: 'User not found' })
9
10 // If user is found, only allow credentials that are registered
11 // The browser will automatically try to use the credential that it knows about
12 // Skipping the step for the user to select a credential for a better user experience
13 return credentials
14 // example: [{ id: '...' }]
15 },
16 async getCredential(event, credentialId) {
17 // Look for the credential in our database
18 const credential = await useDatabase().sql`...`
19
20 // If the credential is not found, there is no account to log in to
21 if (!credential)
22 throw createError({ statusCode: 400, message: 'Credential not found' })
23
24 return credential
25 },
26 async onSuccess(event, { credential, authenticationInfo }) {
27 // The credential authentication has been successful
28 // We can look it up in our database and get the corresponding user
29 const db = useDatabase()
30 const user = await db.sql`...`
31
32 // Update the counter in the database (authenticationInfo.newCounter)
33 await db.sql`...`
34
35 // Set the user session
36 await setUserSession(event, {
37 user: {
38 id: user.id
39 },
40 loggedInAt: Date.now(),
41 })
42 },
43})
[!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
andgetChallenge
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.
1export default defineWebAuthnAuthenticateEventHandler({
2 async storeChallenge(event, challenge, attemptId) {
3 // Store the challenge in a KV store or DB
4 await useStorage().setItem(`attempt:${attemptId}`, challenge)
5 },
6 async getChallenge(event, attemptId) {
7 const challenge = await useStorage().getItem(`attempt:${attemptId}`)
8
9 // Make sure to always remove the attempt because they are single use only!
10 await useStorage().removeItem(`attempt:${attemptId}`)
11
12 if (!challenge)
13 throw createError({ statusCode: 400, message: 'Challenge expired' })
14
15 return challenge
16 },
17 async onSuccess(event, { authenticator }) {
18 // ...
19 },
20})
On the frontend it is as simple as:
1<script setup lang="ts"> 2const { register, authenticate } = useWebAuthn({ 3 registerEndpoint: '/api/webauthn/register', // Default 4 authenticateEndpoint: '/api/webauthn/authenticate', // Default 5}) 6const { fetch: fetchUserSession } = useUserSession() 7 8const userName = ref('') 9async function signUp() { 10 await register({ userName: userName.value }) 11 .then(fetchUserSession) // refetch the user session 12} 13 14async function signIn() { 15 await authenticate(userName.value) 16 .then(fetchUserSession) // refetch the user session 17} 18</script> 19 20<template> 21 <form @submit.prevent="signUp"> 22 <input v-model="userName" placeholder="Email or username" /> 23 <button type="submit">Sign up</button> 24 </form> 25 <form @submit.prevent="signIn"> 26 <input v-model="userName" placeholder="Email or username" /> 27 <button type="submit">Sign in</button> 28 </form> 29</template>
Take a look at the WebAuthnModal.vue
for a full example.
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.
We leverage hooks to let you extend the session data with your own data or log when the user clears the session.
1// server/plugins/session.ts 2export default defineNitroPlugin(() => { 3 // Called when the session is fetched during SSR for the Vue composable (/api/_auth/session) 4 // Or when we call useUserSession().fetch() 5 sessionHooks.hook('fetch', async (session, event) => { 6 // extend User Session by calling your database 7 // or 8 // throw createError({ ... }) if session is invalid for example 9 }) 10 11 // Called when we call useUserSession().clear() or clearUserSession(event) 12 sessionHooks.hook('clear', async (session, event) => { 13 // Log that user logged out 14 }) 15})
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()
1<script setup lang="ts"> 2// When using useAsyncData 3const { data } = await useAsyncData('team', () => useRequestFetch()('/api/protected-endpoint')) 4 5// useFetch will automatically use useRequestFetch during SSR 6const { data } = await useFetch('/api/protected-endpoint') 7</script>
There's an open issue to include credentials in
$fetch
in Nuxt.
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.
<AuthState>
componentYou 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:
1<template> 2 <header> 3 <AuthState v-slot="{ loggedIn, clear }"> 4 <button v-if="loggedIn" @click="clear">Logout</button> 5 <NuxtLink v-else to="/login">Login</NuxtLink> 6 </AuthState> 7 </header> 8</template>
If the page is cached or prerendered, 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:
1<template> 2 <header> 3 <AuthState> 4 <template #default="{ loggedIn, clear }"> 5 <button v-if="loggedIn" @click="clear">Logout</button> 6 <NuxtLink v-else to="/login">Login</NuxtLink> 7 </template> 8 <template #placeholder> 9 <button disabled>Loading...</button> 10 </template> 11 </AuthState> 12 </header> 13</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.
We leverage runtimeConfig.session
to give the defaults option to h3 useSession
.
You can overwrite the options in your nuxt.config.ts
:
1export default defineNuxtConfig({ 2 modules: ['nuxt-auth-utils'], 3 runtimeConfig: { 4 session: { 5 maxAge: 60 * 60 * 24 * 7 // 1 week 6 } 7 } 8})
Our defaults are:
1{ 2 name: 'nuxt-session', 3 password: process.env.NUXT_SESSION_PASSWORD || '', 4 cookie: { 5 sameSite: 'lax' 6 } 7}
You can also overwrite the session config by passing it as 3rd argument of the setUserSession
and replaceUserSession
functions:
1await setUserSession(event, { ... } , { 2 maxAge: 60 * 60 * 24 * 7 // 1 week 3})
Checkout the SessionConfig
for all options.
nuxt-auth-utils
1# Install dependencies 2npm install 3 4# Generate type stubs 5npm run dev:prepare 6 7# Develop with the playground 8npm run dev 9 10# Build the playground 11npm run dev:build 12 13# Run ESLint 14npm run lint 15 16# Run Vitest 17npm run test 18npm run test:watch 19 20# Release new version 21npm run release
No vulnerabilities found.
No security vulnerabilities found.