npx skills add https://github.com/auth0/agent-skills --skill auth0-nuxt适用于 Nuxt 3/4 的服务端会话认证。不同于 @auth0/auth0-vue(客户端 SPA 认证)。
核心原则: 使用服务端加密的 Cookie 会话,而非客户端令牌。
在以下情况使用此 SDK:
在以下情况不要使用此 SDK:
| 错误 | 解决方案 |
|---|---|
安装 @auth0/auth0-vue 或 @auth0/auth0-spa-js | 使用 @auth0/auth0-nuxt |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| Auth0 应用类型选择 "Single Page Application" | 使用 "Regular Web Application" |
环境变量使用 VITE_AUTH0_* 或 VUE_APP_AUTH0_* | 使用 NUXT_AUTH0_* 前缀 |
使用 useUser() 进行安全检查 | 在服务端使用 useAuth0(event).getSession() |
| 在 Auth0 仪表板中缺少回调 URL | 添加 http://localhost:3000/auth/callback |
| 会话密钥强度弱或缺失 | 使用命令生成:openssl rand -hex 64 |
# 1. 安装
npm install @auth0/auth0-nuxt
# 2. 生成密钥
openssl rand -hex 64
# 3. .env
NUXT_AUTH0_DOMAIN=your-tenant.auth0.com
NUXT_AUTH0_CLIENT_ID=your-client-id
NUXT_AUTH0_CLIENT_SECRET=your-client-secret
NUXT_AUTH0_SESSION_SECRET=<from-openssl>
NUXT_AUTH0_APP_BASE_URL=http://localhost:3000
NUXT_AUTH0_AUDIENCE=https://your-api # 可选
// 4. nuxt.config.ts
export default defineNuxtConfig({
modules: ['@auth0/auth0-nuxt'],
runtimeConfig: {
auth0: {
domain: '',
clientId: '',
clientSecret: '',
sessionSecret: '',
appBaseUrl: 'http://localhost:3000',
audience: '', // 可选
},
},
})
SDK 会自动挂载以下路由:
| 路由 | 方法 | 用途 |
|---|---|---|
/auth/login | GET | 发起登录流程。支持 ?returnTo=/path 参数 |
/auth/callback | GET | 处理登录后的 Auth0 回调 |
/auth/logout | GET | 注销用户并重定向到 Auth0 注销端点 |
/auth/backchannel-logout | POST | 接收用于后通道注销的注销令牌 |
自定义: 向模块配置传递 routes: { login, callback, logout, backchannelLogout } 或设置 mountRoutes: false。
| 组合式函数 | 上下文 | 用途 |
|---|---|---|
useAuth0(event) | 服务端 | 访问 getUser(), getSession(), getAccessToken(), logout() |
useUser() | 客户端 | 仅用于显示用户数据。切勿用于安全检查 |
// 服务端示例
const auth0 = useAuth0(event);
const session = await auth0.getSession();
<script setup>
const user = useUser();
</script>
<template>
<div v-if="user">欢迎 {{ user.name }}</div>
<template>
三层防护: 路由中间件(客户端)、服务端中间件(SSR)、API 守卫。
// middleware/auth.ts - 客户端导航
export default defineNuxtRouteMiddleware((to) => {
if (!useUser().value) return navigateTo(`/auth/login?returnTo=${to.path}`);
});
// server/middleware/auth.server.ts - SSR 保护
export default defineEventHandler(async (event) => {
const url = getRequestURL(event);
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
return sendRedirect(event, `/auth/login?returnTo=${url.pathname}`);
}
});
// server/api/protected.ts - API 端点保护
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
throw createError({
statusCode: 401,
statusMessage: '未经授权'
});
}
return { data: '受保护的数据' };
});
关于基于角色、基于权限和高级模式的保护,请参阅: route-protection.md
使用加密的、分块的 Cookie。无需额外配置。
适用于较大的会话或分布式系统:
// nuxt.config.ts
modules: [
['@auth0/auth0-nuxt', {
sessionStoreFactoryPath: '~/server/utils/session-store-factory.ts'
}]
]
完整的会话存储实现,请参阅: session-stores.md
配置 audience 以获取 API 访问令牌:
// nuxt.config.ts
runtimeConfig: {
auth0: {
audience: 'https://your-api-identifier',
}
}
在服务端获取令牌:
// server/api/call-api.ts
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const { accessToken } = await auth0Client.getAccessToken();
return await $fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
});
useUser())openssl rand -hex 64).env 文件| 错误 | 解决方案 |
|---|---|
| "Module not found" | 安装 @auth0/auth0-nuxt,而不是 @auth0/auth0-vue |
| "Missing domain/clientId/clientSecret" | 检查 NUXT_AUTH0_ 前缀、.env 文件位置、runtimeConfig 配置 |
| "Redirect URI mismatch" | 确保 Auth0 仪表板中的回调 URL 与 appBaseUrl + /auth/callback 匹配 |
| "useAuth0 is not defined" | 仅在服务端上下文中与 H3 事件对象一起使用 |
| Cookies too large | 使用有状态会话或减少请求的作用域 |
链接: Auth0-Nuxt GitHub • Auth0 文档 • Nuxt 模块
每周安装量
48
代码仓库
GitHub 星标数
10
首次出现
2026年2月6日
安全审计
安装于
opencode43
codex43
github-copilot42
gemini-cli42
amp39
kimi-cli39
Server-side session authentication for Nuxt 3/4. NOT the same as @auth0/auth0-vue (client-side SPA).
Core principle: Uses server-side encrypted cookie sessions, not client-side tokens.
Use this when:
Don't use this when:
| Mistake | Solution |
|---|---|
Installing @auth0/auth0-vue or @auth0/auth0-spa-js | Use @auth0/auth0-nuxt |
| Auth0 app type "Single Page Application" | Use "Regular Web Application" |
Env vars: VITE_AUTH0_* or VUE_APP_AUTH0_* | Use NUXT_AUTH0_* prefix |
Using useUser() for security checks | Use useAuth0(event).getSession() server-side |
| Missing callback URLs in Auth0 Dashboard | Add http://localhost:3000/auth/callback |
| Weak/missing session secret | Generate: openssl rand -hex 64 |
# 1. Install
npm install @auth0/auth0-nuxt
# 2. Generate secret
openssl rand -hex 64
# 3. .env
NUXT_AUTH0_DOMAIN=your-tenant.auth0.com
NUXT_AUTH0_CLIENT_ID=your-client-id
NUXT_AUTH0_CLIENT_SECRET=your-client-secret
NUXT_AUTH0_SESSION_SECRET=<from-openssl>
NUXT_AUTH0_APP_BASE_URL=http://localhost:3000
NUXT_AUTH0_AUDIENCE=https://your-api # optional
// 4. nuxt.config.ts
export default defineNuxtConfig({
modules: ['@auth0/auth0-nuxt'],
runtimeConfig: {
auth0: {
domain: '',
clientId: '',
clientSecret: '',
sessionSecret: '',
appBaseUrl: 'http://localhost:3000',
audience: '', // optional
},
},
})
The SDK automatically mounts these routes:
| Route | Method | Purpose |
|---|---|---|
/auth/login | GET | Initiates login flow. Supports ?returnTo=/path parameter |
/auth/callback | GET | Handles Auth0 callback after login |
/auth/logout | GET | Logs user out and redirects to Auth0 logout |
/auth/backchannel-logout | POST | Receives logout tokens for back-channel logout |
Customize: Pass routes: { login, callback, logout, backchannelLogout } or mountRoutes: false to module config.
| Composable | Context | Usage |
|---|---|---|
useAuth0(event) | Server-side | Access getUser(), getSession(), getAccessToken(), logout() |
useUser() | Client-side | Display user data only. Never use for security checks |
// Server example
const auth0 = useAuth0(event);
const session = await auth0.getSession();
<script setup>
const user = useUser();
</script>
<template>
<div v-if="user">Welcome {{ user.name }}</div>
<template>
Three layers: Route middleware (client), server middleware (SSR), API guards.
// middleware/auth.ts - Client navigation
export default defineNuxtRouteMiddleware((to) => {
if (!useUser().value) return navigateTo(`/auth/login?returnTo=${to.path}`);
});
// server/middleware/auth.server.ts - SSR protection
export default defineEventHandler(async (event) => {
const url = getRequestURL(event);
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
return sendRedirect(event, `/auth/login?returnTo=${url.pathname}`);
}
});
// server/api/protected.ts - API endpoint protection
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized'
});
}
return { data: 'protected data' };
});
For role-based, permission-based, and advanced patterns: route-protection.md
Uses encrypted, chunked cookies. No configuration needed.
For larger sessions or distributed systems:
// nuxt.config.ts
modules: [
['@auth0/auth0-nuxt', {
sessionStoreFactoryPath: '~/server/utils/session-store-factory.ts'
}]
]
For complete session store implementations, see: session-stores.md
Configure audience for API access tokens:
// nuxt.config.ts
runtimeConfig: {
auth0: {
audience: 'https://your-api-identifier',
}
}
Retrieve tokens server-side:
// server/api/call-api.ts
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const { accessToken } = await auth0Client.getAccessToken();
return await $fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
});
useUser())openssl rand -hex 64).env files| Error | Solution |
|---|---|
| "Module not found" | Install @auth0/auth0-nuxt, not @auth0/auth0-vue |
| "Missing domain/clientId/clientSecret" | Check NUXT_AUTH0_ prefix, .env location, runtimeConfig |
| "Redirect URI mismatch" | Match Auth0 Dashboard callback to appBaseUrl + /auth/callback |
| "useAuth0 is not defined" | Use only in server context with H3 event object |
| Cookies too large | Use stateful sessions or reduce scopes |
Guides: Route Protection Patterns • Custom Session Stores • Common Examples
Links: Auth0-Nuxt GitHub • Auth0 Docs • Nuxt Modules
Weekly Installs
48
Repository
GitHub Stars
10
First Seen
Feb 6, 2026
Security Audits
Gen Agent Trust HubWarnSocketPassSnykPass
Installed on
opencode43
codex43
github-copilot42
gemini-cli42
amp39
kimi-cli39
Azure PostgreSQL 无密码身份验证配置指南:Entra ID 迁移与访问管理
34,800 周安装