次のような場合に使用: Next.js アプリケーションにAuth0(認証サービス)によるログイン、ログアウト、保護されたページ、またはミドルウェア(処理の中間段階で動作するプログラム)を追加する場合。App Router と Pages Router の両方に対応しており、@auth0/nextjs-auth0 ライブラリを使用します。ユーザーが「Next.js アプリにログイン機能を追加したい」や「Next.js のページを保護したい」と言った場合でも使用してください。
Use when adding Auth0 login, logout, protected pages, or middleware to a Next.js application. Supports App Router and Pages Router with @auth0/nextjs-auth0 — use even if the user says "add login to my Next.js app" or "protect my Next.js routes".
@auth0/nextjs-auth0 を使用して Next.js アプリケーションに認証を追加します。 App Router と Pages Router の両方に対応しています。
auth0-quickstart スキルを使用してくださいauth0-react を使用auth0-react-native を使用npm install @auth0/nextjs-auth0
Auth0 CLI を使った自動セットアップ の場合は、セットアップガイド で完全なスクリプトを確認してください。
手動セットアップ の場合:
.env.local を作成します:
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 を .gitignore に追加してください。
まずプロジェクト構成を確認: src/ ディレクトリが使用されているか確認します
(src/app/ または src/pages/ が存在するか)。
これによりファイルの配置場所が決まります:
src/ あり: src/lib/auth0.ts、src/middleware.ts(Next.js 16 の場合は src/proxy.ts)src/ なし: lib/auth0.ts、middleware.ts(Next.js 16 の場合は proxy.ts)lib/auth0.ts(src/ 構成の場合は src/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 の設定(Next.js 15 と 16 の違い):
Next.js 15 — middleware.ts を作成します
(プロジェクトルート、または src/ 構成の場合は src/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 — 以下の 2 つのオプションがあります:
オプション 1: middleware.ts を使用する(Next.js 15 と同じ内容・同じ src/ 配置ルール):
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 を使用する
(プロジェクトルート、または src/ 構成の場合は src/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>
);
}
クライアントコンポーネント(両方の Router で動作):
'use client'; // 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>;
}
開発サーバーを起動します:
npm run dev
http://localhost:3000 にアクセスし、ログインフローを確認してください。
| 間違い | 対処法 |
|---|---|
| v3 の環境変数を使用している | v4 では APP_BASE_URL と AUTH0_DOMAIN を使用(AUTH0_BASE_URL や AUTH0_ISSUER_BASE_URL ではない) |
| Auth0 Dashboard へのコールバック URL の追加を忘れた | Allowed Callback URLs に /auth/callback を追加(例: http://localhost:3000/auth/callback) |
| Middleware の設定がない | v4 では認証ルートのマウントに Middleware が必要 — middleware() を使用した middleware.ts(Next.js 15・16)または proxy() を使用した proxy.ts(Next.js 16 のみ)を作成 |
| ルートパスが間違っている | v4 では /api/auth/login ではなく /auth/login を使用(/api プレフィックスが廃止) |
| AUTH0_SECRET が未設定または脆弱 | openssl rand -hex 32 でセキュアなシークレットを生成し .env.local に保存 |
.env.local ではなく .env を使用している |
Next.js ではローカルのシークレットに .env.local が必要。また .env.local は .gitignore に含めること |
| Auth0 でアプリの種類を SPA に設定している | Next.js では Regular Web Application タイプを使用する必要がある |
| 削除済みの v3 ヘルパーを使用している | v4 では withPageAuthRequired と withApiAuthRequired が削除 — 代わりに getSession() を使用 |
Server Component で useUser を使用している |
useUser はクライアント専用。Server Component では auth0.getSession() を使用 |
AUTH0_DOMAIN に https:// が含まれている |
v4 の AUTH0_DOMAIN はドメインのみを指定(例: example.auth0.com)。スキームは不要 |
auth0-quickstart — Auth0 の基本セットアップauth0-migration — 別の認証プロバイダーからの移行auth0-mfa — 多要素認証(MFA)の追加auth0-cli — ターミナルから Auth0 リソースを管理V4 セットアップ:
src/ 構成の検出: src/app/ または src/pages/ が存在するか確認 — 存在する場合はすべてのファイルを src/ 内に配置Auth0Client インスタンスを使用した lib/auth0.ts(または src/lib/auth0.ts)を作成middleware() 関数を含む middleware.ts(または src/middleware.ts)middleware() を含む middleware.ts、または proxy() を含む proxy.ts(同じ src/ ルールが適用)<Auth0Provider> でラップクライアントサイドフック:
useUser() — クライアントコンポーネントでユーザーを取得user — ユーザープロフィールオブジェクトisLoading — ローディング状態サーバーサイドメソッド:
auth0.getSession() — Server Component / API ルート / Middleware でセッションを取得auth0.getAccessToken() — API 呼び出し用のアクセストークンを取得一般的なユースケース:
/auth/login および /auth/logout パスを使用(手順 5 参照)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
Detect project structure first: Check whether the project uses a src/ directory (i.e. src/app/ or src/pages/ exists). This determines where to place files:
src/: src/lib/auth0.ts, src/middleware.ts (or src/proxy.ts for Next.js 16)src/: lib/auth0.ts, middleware.ts (or proxy.ts for Next.js 16)Create lib/auth0.ts (or src/lib/auth0.ts if using the src/ convention):
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, or src/middleware.ts if using src/):
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, same src/ placement rules):
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, or src/proxy.ts if using src/):
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.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 |
auth0-quickstart - Basic Auth0 setupauth0-migration - Migrate from another auth providerauth0-mfa - Add Multi-Factor Authenticationauth0-cli - Manage Auth0 resources from the terminalV4 Setup:
src/ convention: check if src/app/ or src/pages/ exists — place all files inside src/ if solib/auth0.ts (or src/lib/auth0.ts) with Auth0Client instancemiddleware.ts (or src/middleware.ts) with middleware() functionmiddleware.ts with middleware() OR proxy.ts with proxy() function (same src/ rules)<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)原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。