Gathering detailed insights and metrics for @inkbird-io/nuxt-auth-utils
Gathering detailed insights and metrics for @inkbird-io/nuxt-auth-utils
Gathering detailed insights and metrics for @inkbird-io/nuxt-auth-utils
Gathering detailed insights and metrics for @inkbird-io/nuxt-auth-utils
npm install @inkbird-io/nuxt-auth-utils
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last day
0%
1
Compared to previous day
Last week
0%
3
Compared to previous week
Last month
400%
5
Compared to previous month
Last year
0%
198
Compared to previous year
Minimalist Authentication module for Nuxt exposing Vue composables and server utils.
This module only works with SSR (server-side rendering) enabled as it uses server API routes. You cannot use this module with nuxt generate
.
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, 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>
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 defu() 4await setUserSession(event, { 5 user: { 6 // ... user data 7 }, 8 loggedInAt: new Date() 9 // Any extra fields 10}) 11 12// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data 13await replaceUserSession(event, data) 14 15// Get the current user session 16const session = await getUserSession(event) 17 18// Clear the current user session 19await clearUserSession(event) 20 21// Require a user session (send back 401 if no `user` key in session) 22const 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 12export {}
All helpers are exposed from the oauth
global variable and can be used in your server routes or API routes.
The pattern is oauth.<provider>EventHandler({ onSuccess, config?, onError? })
, example: oauth.githubEventHandler
.
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>: { 5 clientId: '...', 6 clientSecret: '...' 7 } 8 } 9 } 10})
It can also be set using environment variables:
NUXT_OAUTH_<PROVIDER>_CLIENT_ID
NUXT_OAUTH_<PROVIDER>_CLIENT_SECRET
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 oauth.githubEventHandler({
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
.
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 useServerSession().clear() or clearUserSession(event) 12 sessionHooks.hook('clear', async (session, event) => { 13 // Log that user logged out 14 }) 15})
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}
Checkout the SessionConfig
for all options.
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.