auth0-nextjs by auth0/agent-skills
npx skills add https://github.com/auth0/agent-skills --skill auth0-nextjs使用 @auth0/nextjs-auth0 为 Next.js 应用程序添加身份验证。同时支持 App Router 和 Pages Router。
auth0-quickstart 技能auth0-reactauth0-react-nativenpm install @auth0/nextjs-auth0
对于使用 Auth0 CLI 的自动化设置,请参阅获取完整脚本。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
对于手动设置:
创建 .env.local:
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-secret
生成密钥:openssl rand -hex 32
重要提示: 将 .env.local 添加到 .gitignore
创建 lib/auth0.ts:
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 与 16):
Next.js 15 - 在项目根目录创建 middleware.ts:
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: 使用 middleware.ts(与 Next.js 15 相同):
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.ts:
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 - 登出/auth/callback - OAuth 回调/auth/profile - 用户资料注意: 在 v4 中,使用 <Auth0Provider> 包装是可选的。仅当您希望在服务器渲染期间将初始用户传递给 useUser() 时才需要。
App Router - 可选择在 app/layout.tsx 中包装应用:
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.tsx 中包装应用:
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>
);
}
客户端组件(适用于两种路由器):
'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>;
}
启动开发服务器:
npm run dev
访问 http://localhost:3000 并测试登录流程。
| 错误 | 修复方法 |
|---|---|
| 使用 v3 环境变量 | v4 使用 APP_BASE_URL 和 AUTH0_DOMAIN(而不是 AUTH0_BASE_URL 或 AUTH0_ISSUER_BASE_URL) |
| 忘记在 Auth0 仪表板中添加回调 URL | 将 /auth/callback 添加到允许的回调 URL(例如,http://localhost:3000/auth/callback) |
| 缺少中间件配置 | v4 需要中间件来挂载身份验证路由 - 创建包含 auth0.middleware() 的 middleware.ts(Next.js 15+16)或 proxy.ts(仅 Next.js 16) |
| 路由路径错误 | v4 使用 /auth/login 而不是 /api/auth/login - 路由去掉了 /api 前缀 |
| 缺少或强度不足的 AUTH0_SECRET | 使用 openssl rand -hex 32 生成安全密钥并存储在 .env.local 中 |
| 使用 .env 而不是 .env.local | Next.js 要求使用 .env.local 存储本地密钥,并且 .env.local 应位于 .gitignore 中 |
| 在 Auth0 中创建为 SPA 类型 | Next.js 必须使用常规 Web 应用程序类型 |
| 使用已移除的 v3 辅助函数 | v4 移除了 withPageAuthRequired 和 withApiAuthRequired - 改用 getSession() |
| 在服务器组件中使用 useUser | useUser 仅限客户端使用,对于服务器组件请使用 auth0.getSession() |
| AUTH0_DOMAIN 包含 https:// | v4 的 AUTH0_DOMAIN 应仅为域名(例如,example.auth0.com),不包含协议 |
auth0-quickstart - 基础 Auth0 设置auth0-migration - 从其他身份验证提供商迁移auth0-mfa - 添加多因素身份验证V4 设置:
Auth0Client 实例创建 lib/auth0.tsmiddleware() 函数的 middleware.tsmiddleware() 函数的 middleware.ts 或包含 proxy() 函数的 proxy.ts<Auth0Provider> 包装以支持 SSR 用户客户端钩子:
useUser() - 在客户端组件中获取用户user - 用户资料对象isLoading - 加载状态服务器端方法:
auth0.getSession() - 在服务器组件/API 路由/中间件中获取会话auth0.getAccessToken() - 获取用于调用 API 的访问令牌常见用例:
每周安装次数
269
仓库
GitHub 星标数
10
首次出现
2026年2月6日
安全审计
安装于
opencode256
codex255
github-copilot250
gemini-cli248
amp243
kimi-cli243
Add authentication to Next.js applications using @auth0/nextjs-auth0. Supports both App Router and Pages Router.
auth0-quickstart skill firstauth0-react for Vite/CRA SPAsauth0-react-native for iOS/Androidnpm install @auth0/nextjs-auth0
For automated setup with Auth0 CLI , see Setup Guide for complete scripts.
For manual setup:
Create .env.local:
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-secret
Generate secret: openssl rand -hex 32
Important: Add .env.local to .gitignore
Create lib/auth0.ts:
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 middleware.ts at project root:
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 middleware.ts (same as Next.js 15):
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 proxy.ts at project root:
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:
/auth/login - Login/auth/logout - Logout/auth/callback - OAuth callback/auth/profile - User profileNote: In v4, wrapping with <Auth0Provider> is optional. Only needed if you want to pass an initial user during server rendering to useUser().
App Router - Optionally wrap app in app/layout.tsx:
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.tsx:
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>
);
}
Client Component (works in both routers):
'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>;
}
Start your dev server:
npm run dev
Visit http://localhost:3000 and test the login flow.
| Mistake | Fix |
|---|---|
| Using v3 environment variables | v4 uses APP_BASE_URL and AUTH0_DOMAIN (not AUTH0_BASE_URL or AUTH0_ISSUER_BASE_URL) |
| Forgot to add callback URL in Auth0 Dashboard | Add /auth/callback to Allowed Callback URLs (e.g., http://localhost:3000/auth/callback) |
| Missing middleware configuration | v4 requires middleware to mount auth routes - create middleware.ts (Next.js 15+16) or proxy.ts (Next.js 16 only) with |
auth0-quickstart - Basic Auth0 setupauth0-migration - Migrate from another auth providerauth0-mfa - Add Multi-Factor AuthenticationV4 Setup:
lib/auth0.ts with Auth0Client instancemiddleware.ts with middleware() functionmiddleware.ts with middleware() OR proxy.ts with proxy() function<Auth0Provider> for SSR userClient-Side Hooks:
useUser() - Get user in client componentsuser - User profile objectisLoading - Loading stateServer-Side Methods:
auth0.getSession() - Get session in Server Components/API routes/middlewareauth0.getAccessToken() - Get access token for calling APIsCommon Use Cases:
/auth/login and /auth/logout paths (see Step 5)Weekly Installs
269
Repository
GitHub Stars
10
First Seen
Feb 6, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
opencode256
codex255
github-copilot250
gemini-cli248
amp243
kimi-cli243
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装
auth0.middleware()| Wrong route paths | v4 uses /auth/login not /api/auth/login - routes drop the /api prefix |
| Missing or weak AUTH0_SECRET | Generate secure secret with openssl rand -hex 32 and store in .env.local |
| 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 withPageAuthRequired and withApiAuthRequired - use getSession() instead |
| Using useUser in Server Component | useUser is client-only, use auth0.getSession() for Server Components |
| AUTH0_DOMAIN includes https:// | v4 AUTH0_DOMAIN should be just the domain (e.g., example.auth0.com), no scheme |