auth0-nuxt

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Nuxt SDK

Auth0 Nuxt SDK

Overview

概述

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.
为Nuxt 3/4提供服务端会话认证。与@auth0/auth0-vue(客户端SPA专用)不同。
核心原则: 使用服务端加密Cookie会话,而非客户端令牌。

When to Use

适用场景

Use this when:
  • Building Nuxt 3/4 applications with server-side rendering (Node.js 20 LTS+)
  • Need secure session management with encrypted cookies
  • Protecting server routes and API endpoints
  • Accessing Auth0 Management API or custom APIs
Don't use this when:
  • Using Nuxt 2 (not supported - use different Auth0 SDK)
  • Building pure client-side SPA without server (use @auth0/auth0-vue instead)
  • Using non-Auth0 authentication provider
  • Static site generation only (SSG) without server runtime
在以下场景使用:
  • 构建基于服务端渲染的Nuxt 3/4应用(要求Node.js 20 LTS+)
  • 需要通过加密Cookie实现安全的会话管理
  • 保护服务端路由与API端点
  • 访问Auth0管理API或自定义API
请勿在以下场景使用:
  • 使用Nuxt 2(不支持,请使用其他Auth0 SDK)
  • 构建无服务端的纯客户端SPA(请改用@auth0/auth0-vue)
  • 使用非Auth0的认证提供商
  • 仅进行静态站点生成(SSG)且无服务端运行时

Critical Mistakes to Avoid

需避免的常见错误

MistakeSolution
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 DashboardAdd
http://localhost:3000/auth/callback
Weak/missing session secretGenerate:
openssl rand -hex 64
错误解决方案
安装
@auth0/auth0-vue
@auth0/auth0-spa-js
使用
@auth0/auth0-nuxt
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

Quick Setup

快速设置

bash
undefined
bash
undefined

1. Install

1. 安装

npm install @auth0/auth0-nuxt
npm install @auth0/auth0-nuxt

2. Generate secret

2. 生成密钥

openssl rand -hex 64

```bash
openssl rand -hex 64

```bash

3. .env

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

```typescript
// 4. nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@auth0/auth0-nuxt'],
  runtimeConfig: {
    auth0: {
      domain: '',
      clientId: '',
      clientSecret: '',
      sessionSecret: '',
      appBaseUrl: 'http://localhost:3000',
      audience: '',  // optional
    },
  },
})
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 # 可选

```typescript
// 4. nuxt.config.ts配置
export default defineNuxtConfig({
  modules: ['@auth0/auth0-nuxt'],
  runtimeConfig: {
    auth0: {
      domain: '',
      clientId: '',
      clientSecret: '',
      sessionSecret: '',
      appBaseUrl: 'http://localhost:3000',
      audience: '',  // 可选
    },
  },
})

Built-in Routes

内置路由

The SDK automatically mounts these routes:
RouteMethodPurpose
/auth/login
GETInitiates login flow. Supports
?returnTo=/path
parameter
/auth/callback
GETHandles Auth0 callback after login
/auth/logout
GETLogs user out and redirects to Auth0 logout
/auth/backchannel-logout
POSTReceives logout tokens for back-channel logout
Customize: Pass
routes: { login, callback, logout, backchannelLogout }
or
mountRoutes: false
to module config.
该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

Composables

组合式函数

ComposableContextUsage
useAuth0(event)
Server-sideAccess
getUser()
,
getSession()
,
getAccessToken()
,
logout()
useUser()
Client-sideDisplay user data only. Never use for security checks
typescript
// Server example
const auth0 = useAuth0(event);
const session = await auth0.getSession();
vue
<script setup>
const user = useUser();
</script>

<template>
  <div v-if="user">Welcome {{ user.name }}</div>
<template>
组合式函数上下文用途
useAuth0(event)
服务端调用
getUser()
getSession()
getAccessToken()
logout()
useUser()
客户端仅用于展示用户数据。绝不能用于安全校验
typescript
// 服务端示例
const auth0 = useAuth0(event);
const session = await auth0.getSession();
vue
<script setup>
const user = useUser();
</script>

<template>
  <div v-if="user">Welcome {{ user.name }}</div>
<template>

Protecting Routes

路由保护

Three layers: Route middleware (client), server middleware (SSR), API guards.
typescript
// middleware/auth.ts - Client navigation
export default defineNuxtRouteMiddleware((to) => {
  if (!useUser().value) return navigateTo(`/auth/login?returnTo=${to.path}`);
});
typescript
// 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}`);
  }
});
typescript
// 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
三层保护: 路由中间件(客户端)、服务端中间件(SSR)、API守卫。
typescript
// middleware/auth.ts - 客户端导航保护
export default defineNuxtRouteMiddleware((to) => {
  if (!useUser().value) return navigateTo(`/auth/login?returnTo=${to.path}`);
});
typescript
// 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}`);
  }
});
typescript
// 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: 'Unauthorized'
    });
  }

  return { data: 'protected data' };
});
如需基于角色、权限的高级保护模式: 参考route-protection.md

Session Management

会话管理

Stateless (Default)

无状态(默认)

Uses encrypted, chunked cookies. No configuration needed.
使用加密的分块Cookie,无需额外配置。

Stateful (Redis, MongoDB, etc.)

有状态(Redis、MongoDB等)

For larger sessions or distributed systems:
typescript
// nuxt.config.ts
modules: [
  ['@auth0/auth0-nuxt', {
    sessionStoreFactoryPath: '~/server/utils/session-store-factory.ts'
  }]
]
For complete session store implementations, see: session-stores.md
适用于会话数据较大或分布式系统:
typescript
// nuxt.config.ts
modules: [
  ['@auth0/auth0-nuxt', {
    sessionStoreFactoryPath: '~/server/utils/session-store-factory.ts'
  }]
]
完整的会话存储实现示例,请参考: session-stores.md

API Integration

API集成

Configure audience for API access tokens:
typescript
// nuxt.config.ts
runtimeConfig: {
  auth0: {
    audience: 'https://your-api-identifier',
  }
}
Retrieve tokens server-side:
typescript
// 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}`
    }
  });
});
配置受众以获取API访问令牌:
typescript
// nuxt.config.ts
runtimeConfig: {
  auth0: {
    audience: 'https://your-api-identifier',
  }
}
在服务端获取令牌:
typescript
// 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}`
    }
  });
});

Security Checklist

安全检查清单

  • ✅ Server-side validation only (never trust
    useUser()
    )
  • ✅ HTTPS in production
  • ✅ Strong session secret (
    openssl rand -hex 64
    )
  • ✅ Never commit
    .env
    files
  • ✅ Stateful sessions for PII/large data
  • ✅ 仅在服务端进行校验(绝不要信任
    useUser()
  • ✅ 生产环境使用HTTPS
  • ✅ 使用高强度会话密钥(
    openssl rand -hex 64
    生成)
  • ✅ 绝不提交
    .env
    文件到版本控制
  • ✅ 对于包含个人身份信息(PII)或较大数据的会话,使用有状态会话存储

Troubleshooting

故障排查

ErrorSolution
"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 largeUse stateful sessions or reduce scopes
错误解决方案
"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 event对象时使用
Cookies过大使用有状态会话或减少授权范围(scopes)

Additional Resources

额外资源

Guides: Route Protection PatternsCustom Session StoresCommon Examples
指南: 路由保护模式自定义会话存储常见示例