🔐auth0-nextjs
- プラグイン
- auth0
- ライセンス
- Apache-2.0
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: 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".
ユースケース
- ✓Next.jsアプリにログイン機能を追加する
- ✓Next.jsアプリにログアウト機能を追加する
- ✓Next.jsのルートを保護したい
- ✓Auth0でミドルウェアを設定する
本文(日本語訳)
Auth0 Next.js インテグレーション
@auth0/nextjs-auth0 を使用して Next.js アプリケーションに認証を追加します。 App Router と Pages Router の両方に対応しています。
前提条件
- Next.js 13 以上のアプリケーション(App Router または Pages Router)
- Auth0 アカウントおよびアプリケーションの設定が完了していること
- Auth0 のセットアップがまだの場合は、先に
auth0-quickstartスキルを使用してください
使用しない場合
- クライアントサイドのみの React アプリ — Vite / CRA の SPA には
auth0-reactを使用 - React Native モバイルアプリ — iOS / Android には
auth0-react-nativeを使用 - Next.js 以外のフレームワーク — フレームワーク固有の SDK を使用(Express、Vue、Angular など)
- ステートレス API のみの構成 — セッション管理が不要な場合は JWT バリデーション Middleware を使用
クイックスタート手順
1. SDK のインストール
npm install @auth0/nextjs-auth0
2. 環境設定
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 に追加してください。
3. Auth0 クライアントと Middleware の作成
まずプロジェクト構成を確認: 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— ユーザープロフィール
4. ユーザーコンテキストの追加(任意)
注意: 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>
);
}
5. 認証 UI の追加
クライアントコンポーネント(両方の 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>;
}
6. 認証のテスト
開発サーバーを起動します:
npm run dev
http://localhost:3000 にアクセスし、ログインフローを確認してください。
詳細ドキュメント
- セットアップガイド — 自動セットアップスクリプト、環境設定、Auth0 CLI の使用方法
- インテグレーションガイド — サーバーサイド認証、保護されたルート、API ルート、Middleware
- API リファレンス — SDK の完全な API、フック、ヘルパー、セッション管理
よくある間違い
| 間違い | 対処法 |
|---|---|
| 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 の設定を作成(必須):
- Next.js 15:
middleware()関数を含むmiddleware.ts(またはsrc/middleware.ts) - Next.js 16:
middleware()を含むmiddleware.ts、またはproxy()を含むproxy.ts(同じsrc/ルールが適用)
- Next.js 15:
- 任意: SSR 時のユーザー情報提供のために
<Auth0Provider>でラップ
クライアントサイドフック:
useUser()— クライアントコンポーネントでユーザーを取得user— ユーザープロフィールオブジェクトisLoading— ローディング状態
サーバーサイドメソッド:
auth0.getSession()— Server Component / API ルート / Middleware でセッションを取得auth0.getAccessToken()— API 呼び出し用のアクセストークンを取得
一般的なユースケース:
- ログイン・ログアウトリンク →
/auth/loginおよび/auth/logoutパスを使用(手順 5 参照) - 保護されたページ(App Router) → インテグレーションガイド
- 保護されたページ(Pages Router) → インテグレーションガイド
- 認証付き API ルート → インテグレーションガイド
- Middleware による保護 → インテグレーションガイド
参考リンク
原文(English)を表示
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
auth0-quickstartskill first
When NOT to Use
- Client-side only React apps - Use
auth0-reactfor Vite/CRA SPAs - React Native mobile apps - Use
auth0-react-nativefor iOS/Android - 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
npm install @auth0/nextjs-auth0
2. Configure Environment
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
3. Create Auth0 Client and Middleware
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:
- With
src/:src/lib/auth0.ts,src/middleware.ts(orsrc/proxy.tsfor Next.js 16) - Without
src/:lib/auth0.ts,middleware.ts(orproxy.tsfor 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 profile
4. Add User Context (Optional)
Note: 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>
);
}
5. Add Authentication UI
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>;
}
6. Test Authentication
Start your dev server:
npm run dev
Visit http://localhost:3000 and test the login flow.
Detailed 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 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 |
Related Skills
auth0-quickstart- Basic Auth0 setupauth0-migration- Migrate from another auth providerauth0-mfa- Add Multi-Factor Authenticationauth0-cli- Manage Auth0 resources from the terminal
Quick Reference
V4 Setup:
- Detect
src/convention: check ifsrc/app/orsrc/pages/exists — place all files insidesrc/if so - Create
lib/auth0.ts(orsrc/lib/auth0.ts) withAuth0Clientinstance - Create middleware configuration (required):
- Next.js 15:
middleware.ts(orsrc/middleware.ts) withmiddleware()function - Next.js 16:
middleware.tswithmiddleware()ORproxy.tswithproxy()function (samesrc/rules)
- Next.js 15:
- Optional: Wrap with
<Auth0Provider>for SSR user
Client-Side Hooks:
useUser()- Get user in client componentsuser- User profile objectisLoading- Loading state
Server-Side Methods:
auth0.getSession()- Get session in Server Components/API routes/middlewareauth0.getAccessToken()- Get access token for calling APIs
Common Use Cases:
- Login/Logout links → Use
/auth/loginand/auth/logoutpaths (see Step 5) - Protected pages (App Router) → Integration Guide
- Protected pages (Pages Router) → Integration Guide
- API routes with auth → Integration Guide
- Middleware protection → Integration Guide
References
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。