A Nuxt integration for auth that provides seamless authentication with multiple providers, session management, and route protection using Nuxt patterns.
This integration brings the power and flexibility of OAuth to Nuxt applications with full TypeScript support, SSR-friendly session handling, and Nuxt-native patterns including composables, middleware, and plugins.
Modern web applications require robust, secure, and flexible authentication systems. Integrating OAuth and session management with Nuxt applications requires careful consideration of framework patterns, server-side rendering, and TypeScript integration.
However, a direct integration isn't always straightforward. Different types of applications or deployment scenarios might warrant different approaches:
- Framework Integration: OAuth and auth flows operate at the HTTP level, while Nuxt uses composables, middleware, and plugins. A proper integration should bridge this gap by providing Nuxt-native primitives for authentication and authorization while maintaining the full OAuth provider ecosystem compatibility.
- HTTP Request Handling: Nuxt's universal rendering and server engine (Nitro) require clean request handling across SSR and client-side navigation. Teams need a unified approach that maintains performance while providing seamless OAuth integration.
- Session and Request Lifecycle: Proper session handling in Nuxt requires SSR-friendly composables and state management that work across server-rendered pages, client hydration, and client-side navigations.
- Route Protection: Many applications need fine-grained authorization beyond simple authentication. This integration provides global middleware, per-page overrides, and guest-only pages for protecting routes.
This integration, @zitadel/nuxt-auth, aims to provide the flexibility to
handle such scenarios. It allows you to leverage the full OAuth provider ecosystem
while maintaining Nuxt best practices, ultimately leading to a more
effective and less burdensome authentication implementation.
Install using NPM by using the following command:
npm install @zitadel/nuxt-authTo use this integration, add the @zitadel/nuxt-auth module to your Nuxt application.
The module provides authentication infrastructure with configurable
routes, middleware, and composables.
You'll need to configure it with your OAuth providers and options. The integration will then be available throughout your application via Nuxt's module system.
First, add the module to your Nuxt config:
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@zitadel/nuxt-auth'],
auth: {
originEnvKey: 'AUTH_URL',
baseURL: '/api/auth',
provider: {
type: 'authjs',
trustHost: false,
defaultProvider: 'github',
},
sessionRefresh: {
enablePeriodically: false,
enableOnWindowFocus: true,
},
},
});Then, create the auth handler in your server directory:
// server/api/auth/[...].ts
import { NuxtAuth } from '#auth';
import Zitadel from '@auth/core/providers/zitadel';
export const { handlers, getSession } = NuxtAuth({
secret: process.env.AUTH_SECRET,
providers: [
Zitadel({
clientId: process.env.ZITADEL_CLIENT_ID,
clientSecret: process.env.ZITADEL_CLIENT_SECRET,
issuer: process.env.ZITADEL_DOMAIN,
}),
],
});
export default handlers;The integration provides several functions and hooks for handling authentication:
Server Utilities:
useAuth(): Client-side composable providing reactive session state and auth methodsgetSession(event): Server-side utility to retrieve the session in API routesNuxtAuth(config): Server handler factory returning{ handlers, getSession }definePageMeta({ auth }): Per-page route protection configuration
Basic Usage:
<script setup>
const { status, data, signIn, signOut } = useAuth();
const user = computed(() => data.value?.user);
const isLoggedIn = computed(() => status.value === 'authenticated');
</script>
<template>
<div v-if="status === 'loading'">Loading...</div>
<div v-else-if="isLoggedIn">
<p>Welcome, {{ user?.name }}!</p>
<button @click="signOut()">Sign out</button>
</div>
<div v-else>
<button @click="signIn('github')">Sign in with GitHub</button>
</div>
</template>Server-side session access in API routes:
// server/api/profile.ts
import { getSession } from '#auth';
export default eventHandler(async (event) => {
const session = await getSession(event);
if (!session) {
throw createError({ statusCode: 401, message: 'Unauthorized' });
}
return { user: session.user };
});This example shows how to use the integration with multiple OAuth providers and custom session configuration:
// server/api/auth/[...].ts
import { NuxtAuth } from '#auth';
import Zitadel from '@auth/core/providers/zitadel';
import Google from '@auth/core/providers/google';
export const { handlers, getSession } = NuxtAuth({
secret: process.env.AUTH_SECRET,
providers: [
Zitadel({
clientId: process.env.ZITADEL_CLIENT_ID,
clientSecret: process.env.ZITADEL_CLIENT_SECRET,
issuer: process.env.ZITADEL_DOMAIN,
}),
Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60, // 30 days
},
callbacks: {
async jwt({ token, user }) {
if (user) (token as any).roles = (user as any).roles;
return token;
},
async session({ session, token }) {
(session.user as any).roles = (token as any).roles as
| string[]
| undefined;
return session;
},
},
});
export default handlers;- Nuxt Module Required: The integration is delivered as a Nuxt module and
must be registered via the
modulesarray innuxt.config.ts. Without this, the auto-imported composables (useAuth) and server utilities (#auth) will not be available. - Environment Configuration: The integration relies on
AUTH_SECRETfor signing sessions, and onAUTH_URL(or a customoriginEnvKey) to determine the application origin in production. Ensure both are correctly set in your environment. During development, the origin is inferred automatically from incoming requests. - Callback URLs: OAuth providers must be configured with the correct
callback URL:
[origin]/api/auth/callback/[provider](or your custombaseURLpath). - Type Augmentation: If you attach additional properties (e.g., roles) to
the user session object, extend your app's types accordingly so consumers of
session.userremain type-safe. - Credentials Provider: The credentials provider silently ignores
callbackUrl. The integration accounts for this by disablingaddDefaultCallbackUrlwhendefaultProvideris set to'credentials'. - Caching Compatibility: When using Nuxt's route caching (SWR), set
disableServerSideAuth: trueon cached routes to prevent stale session data from being served from the cache.
- Nuxt: The framework this integration targets.
If you have suggestions for how this integration could be improved, or want to report a bug, open an issue — we'd love all and any contributions.
This project is a fork of
@sidebase/nuxt-auth, originally
created by SIDESTREAM GmbH. The original work
is licensed under the MIT License. See the NOTICE file for details.
Apache-2.0