auth0-nextjs
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Next.js Integration
Auth0 Next.js 集成方案
Add authentication to Next.js applications using @auth0/nextjs-auth0. Supports both App Router and Pages Router.
使用@auth0/nextjs-auth0为Next.js应用添加认证功能,同时支持App Router和Pages Router。
Prerequisites
前置条件
- Next.js 13+ application (App Router or Pages Router)
- Auth0 account and application configured
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- Next.js 13+版本的应用(支持App Router或Pages Router)
- 已完成配置的Auth0账号和应用
- 若尚未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用场景
- Client-side only React apps - Use for Vite/CRA SPAs
auth0-react - React Native mobile apps - Use for iOS/Android
auth0-react-native - Non-Next.js frameworks - Use framework-specific SDKs (Express, Vue, Angular, etc.)
- Stateless APIs only - Use JWT validation middleware if you don't need session management
- 纯客户端React应用 - 对于Vite/CRA单页应用,请使用
auth0-react - React Native移动应用 - 针对iOS/Android平台,请使用
auth0-react-native - 非Next.js框架 - 使用对应框架的专属SDK(Express、Vue、Angular等)
- 仅无状态API - 若无需会话管理,请使用JWT验证中间件
Quick Start Workflow
快速开始流程
1. Install SDK
1. 安装SDK
bash
npm install @auth0/nextjs-auth0bash
npm install @auth0/nextjs-auth02. Configure Environment
2. 配置环境变量
For automated setup with Auth0 CLI, see Setup Guide for complete scripts.
For manual setup:
Create :
.env.localbash
AUTH0_SECRET=<generate-a-32-character-secret>
APP_BASE_URL=http://localhost:3000
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secretGenerate secret:
openssl rand -hex 32Important: Add to
.env.local.gitignore使用Auth0 CLI自动配置,请查看设置指南获取完整脚本。
手动配置:
创建文件:
.env.localbash
AUTH0_SECRET=<生成32位字符的密钥>
APP_BASE_URL=http://localhost:3000
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret生成密钥:
openssl rand -hex 32重要提示: 将添加至文件中
.env.local.gitignore3. Create Auth0 Client and Middleware
3. 创建Auth0客户端与中间件
Create :
lib/auth0.tstypescript
import { Auth0Client } from '@auth0/nextjs-auth0/server';
export const auth0 = new Auth0Client({
domain: process.env.AUTH0_DOMAIN!,
clientId: process.env.AUTH0_CLIENT_ID!,
clientSecret: process.env.AUTH0_CLIENT_SECRET!,
secret: process.env.AUTH0_SECRET!,
appBaseUrl: process.env.APP_BASE_URL!,
});Middleware Configuration (Next.js 15 vs 16):
Next.js 15 - Create at project root:
middleware.tstypescript
import { NextRequest } from 'next/server';
import { auth0 } from './lib/auth0';
export async function middleware(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
};Next.js 16 - You have two options:
Option 1: Use (same as Next.js 15):
middleware.tstypescript
import { NextRequest } from 'next/server';
import { auth0 } from './lib/auth0';
export async function middleware(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
};Option 2: Use at project root:
proxy.tstypescript
import { NextRequest } from 'next/server';
import { auth0 } from './lib/auth0';
export async function proxy(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
};This automatically creates endpoints:
- - Login
/auth/login - - Logout
/auth/logout - - OAuth callback
/auth/callback - - User profile
/auth/profile
创建文件:
lib/auth0.tstypescript
import { Auth0Client } from '@auth0/nextjs-auth0/server';
export const auth0 = new Auth0Client({
domain: process.env.AUTH0_DOMAIN!,
clientId: process.env.AUTH0_CLIENT_ID!,
clientSecret: process.env.AUTH0_CLIENT_SECRET!,
secret: process.env.AUTH0_SECRET!,
appBaseUrl: process.env.APP_BASE_URL!,
});中间件配置(Next.js 15 vs 16):
Next.js 15 - 在项目根目录创建:
middleware.tstypescript
import { NextRequest } from 'next/server';
import { auth0 } from './lib/auth0';
export async function middleware(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
};Next.js 16 - 有两种配置选项:
选项1: 使用(与Next.js 15配置一致):
middleware.tstypescript
import { NextRequest } from 'next/server';
import { auth0 } from './lib/auth0';
export async function middleware(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
};选项2: 在项目根目录创建:
proxy.tstypescript
import { NextRequest } from 'next/server';
import { auth0 } from './lib/auth0';
export async function proxy(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
};配置完成后会自动创建以下端点:
- - 登录接口
/auth/login - - 登出接口
/auth/logout - - OAuth回调接口
/auth/callback - - 用户信息接口
/auth/profile
4. Add User Context (Optional)
4. 添加用户上下文(可选)
Note: In v4, wrapping with is optional. Only needed if you want to pass an initial user during server rendering to .
<Auth0Provider>useUser()App Router - Optionally wrap app in :
app/layout.tsxtypescript
import { Auth0Provider } from '@auth0/nextjs-auth0/client';
import { auth0 } from './lib/auth0';
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const session = await auth0.getSession();
return (
<html>
<body>
<Auth0Provider user={session?.user}>{children}</Auth0Provider>
</body>
</html>
);
}Pages Router - Optionally wrap app in :
pages/_app.tsxtypescript
import { Auth0Provider } from '@auth0/nextjs-auth0/client';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return (
<Auth0Provider user={pageProps.user}>
<Component {...pageProps} />
</Auth0Provider>
);
}注意: 在v4版本中,无需强制使用包裹应用。仅当需要在服务端渲染时将初始用户信息传递给时才需要配置。
<Auth0Provider>useUser()App Router - 可选择在中包裹应用:
app/layout.tsxtypescript
import { Auth0Provider } from '@auth0/nextjs-auth0/client';
import { auth0 } from './lib/auth0';
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const session = await auth0.getSession();
return (
<html>
<body>
<Auth0Provider user={session?.user}>{children}</Auth0Provider>
</body>
</html>
);
}Pages Router - 可选择在中包裹应用:
pages/_app.tsxtypescript
import { Auth0Provider } from '@auth0/nextjs-auth0/client';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return (
<Auth0Provider user={pageProps.user}>
<Component {...pageProps} />
</Auth0Provider>
);
}5. Add Authentication UI
5. 添加认证UI组件
Client Component (works in both routers):
typescript
'use client'; // Only needed for App Router
import { useUser } from '@auth0/nextjs-auth0/client';
export default function Profile() {
const { user, isLoading } = useUser();
if (isLoading) return <div>Loading...</div>;
if (user) {
return (
<div>
<img src={user.picture} alt={user.name} />
<h2>Welcome, {user.name}!</h2>
<a href="/auth/logout">Logout</a>
</div>
);
}
return <a href="/auth/login">Login</a>;
}客户端组件(同时支持两种路由):
typescript
'use client'; // 仅App Router需要添加
import { useUser } from '@auth0/nextjs-auth0/client';
export default function Profile() {
const { user, isLoading } = useUser();
if (isLoading) return <div>加载中...</div>;
if (user) {
return (
<div>
<img src={user.picture} alt={user.name} />
<h2>欢迎回来,{user.name}!</h2>
<a href="/auth/logout">登出</a>
</div>
);
}
return <a href="/auth/login">登录</a>;
}6. Test Authentication
6. 测试认证流程
Start your dev server:
bash
npm run devVisit and test the login flow.
http://localhost:3000启动开发服务器:
bash
npm run dev访问并测试登录流程。
http://localhost:3000Detailed Documentation
详细文档
- Setup Guide - Automated setup scripts, environment configuration, Auth0 CLI usage
- Integration Guide - Server-side auth, protected routes, API routes, middleware
- API Reference - Complete SDK API, hooks, helpers, session management
- 设置指南 - 自动配置脚本、环境变量配置、Auth0 CLI使用说明
- 集成指南 - 服务端认证、受保护路由、API路由、中间件
- API参考 - 完整SDK API、钩子函数、辅助工具、会话管理
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
| Using v3 environment variables | v4 uses |
| Forgot to add callback URL in Auth0 Dashboard | Add |
| Missing middleware configuration | v4 requires middleware to mount auth routes - create |
| Wrong route paths | v4 uses |
| Missing or weak AUTH0_SECRET | Generate secure secret with |
| Using .env instead of .env.local | Next.js requires .env.local for local secrets, and .env.local should be in .gitignore |
| App created as SPA type in Auth0 | Must be Regular Web Application type for Next.js |
| Using removed v3 helpers | v4 removed |
| Using useUser in Server Component | useUser is client-only, use |
| AUTH0_DOMAIN includes https:// | v4 |
| 错误 | 修复方案 |
|---|---|
| 使用v3版本的环境变量 | v4版本使用 |
| 忘记在Auth0控制台添加回调URL | 将 |
| 缺少中间件配置 | v4版本需要中间件来挂载认证路由 - 创建 |
| 路由路径错误 | v4版本使用 |
| 缺失或弱密码强度的AUTH0_SECRET | 使用 |
| 使用.env而非.env.local | Next.js要求使用.env.local存储本地密钥,且.env.local需加入.gitignore |
| 在Auth0中创建的应用类型为SPA | Next.js应用必须选择“常规Web应用”类型 |
| 使用已移除的v3版本辅助函数 | v4版本已移除 |
| 在服务端组件中使用useUser | useUser仅适用于客户端组件,服务端组件请使用 |
| AUTH0_DOMAIN包含https:// | v4版本的 |
Related Skills
相关技能
- - Basic Auth0 setup
auth0-quickstart - - Migrate from another auth provider
auth0-migration - - Add Multi-Factor Authentication
auth0-mfa
- - Auth0基础设置
auth0-quickstart - - 从其他认证服务商迁移
auth0-migration - - 添加多因素认证
auth0-mfa
Quick Reference
快速参考
V4 Setup:
- Create with
lib/auth0.tsinstanceAuth0Client - Create middleware configuration (required):
- Next.js 15: with
middleware.tsfunctionmiddleware() - Next.js 16: with
middleware.tsORmiddleware()withproxy.tsfunctionproxy()
- Next.js 15:
- Optional: Wrap with for SSR user
<Auth0Provider>
Client-Side Hooks:
- - Get user in client components
useUser() - - User profile object
user - - Loading state
isLoading
Server-Side Methods:
- - Get session in Server Components/API routes/middleware
auth0.getSession() - - Get access token for calling APIs
auth0.getAccessToken()
Common Use Cases:
- Login/Logout links → Use and
/auth/loginpaths (see Step 5)/auth/logout - Protected pages (App Router) → Integration Guide
- Protected pages (Pages Router) → Integration Guide
- API routes with auth → Integration Guide
- Middleware protection → Integration Guide
V4版本设置要点:
- 创建并实例化
lib/auth0.tsAuth0Client - 必须配置中间件:
- Next.js 15:创建并实现
middleware.ts函数middleware() - Next.js 16:创建实现
middleware.ts函数 或 创建middleware()实现proxy.ts函数proxy()
- Next.js 15:创建
- 可选:使用包裹应用以支持服务端渲染用户信息
<Auth0Provider>
客户端钩子函数:
- - 在客户端组件中获取用户信息
useUser() - - 用户信息对象
user - - 加载状态
isLoading
服务端方法:
- - 在服务端组件/API路由/中间件中获取会话信息
auth0.getSession() - - 获取调用API所需的访问令牌
auth0.getAccessToken()
常见使用场景:
- 登录/登出链接 → 使用和
/auth/login路径(详见步骤5)/auth/logout - 受保护页面(App Router) → 集成指南
- 受保护页面(Pages Router) → 集成指南
- 带认证的API路由 → 集成指南
- 中间件保护 → 集成指南