Gathering detailed insights and metrics for nuxt-auth-utils-x
Gathering detailed insights and metrics for nuxt-auth-utils-x
Gathering detailed insights and metrics for nuxt-auth-utils-x
Gathering detailed insights and metrics for nuxt-auth-utils-x
Add Authentication to Nuxt applications with secured & sealed cookies sessions.
npm install nuxt-auth-utils-x
Typescript
Module System
Node Version
NPM Version
46.6
Supply Chain
91.7
Quality
84.2
Maintenance
100
Vulnerability
99.3
License
TypeScript (92.65%)
Vue (7.2%)
JavaScript (0.15%)
Total Downloads
2,204
Last Day
1
Last Week
3
Last Month
32
Last Year
2,204
1,044 Stars
246 Commits
99 Forks
13 Watching
4 Branches
55 Contributors
Latest Version
0.1.27
Package Id
nuxt-auth-utils-x@0.1.27
Unpacked Size
87.69 kB
Size
17.64 kB
File Count
62
NPM Version
10.5.2
Node Version
20.13.1
Publised On
21 Jul 2024
Cumulative downloads
Total Downloads
Last day
0%
1
Compared to previous day
Last week
-88.5%
3
Compared to previous week
Last month
100%
32
Compared to previous month
Last year
0%
2,204
Compared to previous year
Add Authentication to Nuxt applications with secured & sealed cookies sessions.
<AuthState>
componentThis 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, 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})
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-nightly
or Nitro >= 2.10.0
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}
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.