auth0-nextjs
Original:🇺🇸 English
Translated
Use when adding authentication to Next.js applications with both server and client-side auth - supports App Router and Pages Router with @auth0/nextjs-auth0 SDK
4installs
Sourceauth0/agent-skills
Added on
NPX Install
npx skill4agent add auth0/agent-skills auth0-nextjsTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →Auth0 Next.js Integration
Add authentication to Next.js applications using @auth0/nextjs-auth0. Supports both App Router and 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
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
Quick Start Workflow
1. Install SDK
bash
npm install @auth0/nextjs-auth02. Configure Environment
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.gitignore3. Create Auth0 Client and Middleware
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
4. Add User Context (Optional)
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>
);
}5. Add Authentication 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>;
}6. Test Authentication
Start your dev server:
bash
npm run devVisit and test the login flow.
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
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 |
Related Skills
- - Basic Auth0 setup
auth0-quickstart - - Migrate from another auth provider
auth0-migration - - Add Multi-Factor Authentication
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