← 返回 Skills 市场
auth0

Auth0 Nextjs

作者 Auth0 · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
77
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install auth0-nextjs
功能描述
Use when adding authentication to Next.js applications (login, logout, protected pages, middleware, server components) - supports App Router and Pages Router...
使用说明 (SKILL.md)

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-quickstart skill first

When NOT to Use

  • Client-side only React apps - Use auth0-react for Vite/CRA SPAs
  • React Native mobile apps - Use auth0-react-native for 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=\x3Cgenerate-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 (or src/proxy.ts for Next.js 16)
  • Without 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 profile

4. Add User Context (Optional)

Note: In v4, wrapping with \x3CAuth0Provider> 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 (
    \x3Chtml>
      \x3Cbody>
        \x3CAuth0Provider user={session?.user}>{children}\x3C/Auth0Provider>
      \x3C/body>
    \x3C/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 (
    \x3CAuth0Provider user={pageProps.user}>
      \x3CComponent {...pageProps} />
    \x3C/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 \x3Cdiv>Loading...\x3C/div>;

  if (user) {
    return (
      \x3Cdiv>
        \x3Cimg src={user.picture} alt={user.name} />
        \x3Ch2>Welcome, {user.name}!\x3C/h2>
        \x3Ca href="/auth/logout">Logout\x3C/a>
      \x3C/div>
    );
  }

  return \x3Ca href="/auth/login">Login\x3C/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 setup
  • auth0-migration - Migrate from another auth provider
  • auth0-mfa - Add Multi-Factor Authentication

Quick Reference

V4 Setup:

  • Detect src/ convention: check if src/app/ or src/pages/ exists — place all files inside src/ if so
  • Create lib/auth0.ts (or src/lib/auth0.ts) with Auth0Client instance
  • Create middleware configuration (required):
    • Next.js 15: middleware.ts (or src/middleware.ts) with middleware() function
    • Next.js 16: middleware.ts with middleware() OR proxy.ts with proxy() function (same src/ rules)
  • Optional: Wrap with \x3CAuth0Provider> for SSR user

Client-Side Hooks:

  • useUser() - Get user in client components
  • user - User profile object
  • isLoading - Loading state

Server-Side Methods:

  • auth0.getSession() - Get session in Server Components/API routes/middleware
  • auth0.getAccessToken() - Get access token for calling APIs

Common Use Cases:


References

安全使用建议
This appears to be a legitimate Auth0 Next.js setup guide. Before you run any automated steps: (1) review the provided install script (the curl | sh installer) instead of executing it blindly; (2) back up existing .env/.env.local and confirm any append operations (the guide itself says to ask the user); (3) ensure .env.local is in .gitignore so secrets aren't committed; (4) prefer running CLI steps yourself interactively rather than giving the agent permission to run them autonomously; and (5) never paste secrets into chat — the skill already warns agents not to read env files without explicit user permission.
功能分析
Type: OpenClaw Skill Name: auth0-nextjs Version: 1.0.0 The skill bundle provides a legitimate and well-documented integration for Auth0 in Next.js applications. It includes safety instructions in `references/setup.md` that explicitly forbid the AI agent from reading sensitive environment files without user permission, mitigating the risk of secret exposure in the LLM context. The automated setup script uses the official Auth0 CLI and standard installation patterns (e.g., fetching from `raw.githubusercontent.com/auth0/auth0-cli`).
能力标签
requires-oauth-tokenrequires-sensitive-credentials
能力评估
Purpose & Capability
The name/description (Auth0 + Next.js) matches the content: the SKILL.md and references show step-by-step setup, middleware, API examples and SDK usage. All env variables and files mentioned (AUTH0_* and .env.local, lib/auth0.ts, middleware) are expected for this purpose.
Instruction Scope
The instructions will read project layout, create files (lib/auth0.ts, middleware/proxy), and append or create .env.local containing sensitive secrets. The SKILL.md explicitly warns not to read existing env files and requires explicit user confirmation before writing — a good safeguard. Still, the agent instructions include file I/O and interactive CLI use, so the user should confirm before allowing automated execution.
Install Mechanism
This is an instruction-only skill (no code files). The provided automated setup script may install the Auth0 CLI; on non-macOS it suggests piping an install script from raw.githubusercontent.com to sh. Using curl | sh is common for CLIs but is higher risk than package-manager installs — review the install script before executing it.
Credentials
Environment variables referenced (AUTH0_SECRET, AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, APP_BASE_URL, AUTH0_AUDIENCE) are appropriate and necessary for Auth0 integration. The skill does not itself request credentials in metadata; it instructs the user to create/append them to project env files, and warns about not exposing secrets.
Persistence & Privilege
The skill is not always-enabled and does not request system-wide privileges or modify other skills. It is agent-invokable by default, which is normal for skills. It does write to project files when the user consents, which is expected for a setup helper.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install auth0-nextjs
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /auth0-nextjs 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release of Auth0 integration for Next.js apps using @auth0/nextjs-auth0 SDK. - Supports both App Router and Pages Router in Next.js 13+ projects. - Guides setup for authentication (login, logout, protected routes, user context). - Dual middleware approach for Next.js 15 and Next.js 16 (supports both `middleware.ts` and `proxy.ts` patterns). - Usage notes for file placement depending on `src/` structure. - Includes troubleshooting tips for common environment/configuration mistakes. - References detailed guides and related skills for further customization.
元数据
Slug auth0-nextjs
版本 1.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Auth0 Nextjs 是什么?

Use when adding authentication to Next.js applications (login, logout, protected pages, middleware, server components) - supports App Router and Pages Router... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 77 次。

如何安装 Auth0 Nextjs?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install auth0-nextjs」即可一键安装,无需额外配置。

Auth0 Nextjs 是免费的吗?

是的,Auth0 Nextjs 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Auth0 Nextjs 支持哪些平台?

Auth0 Nextjs 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Auth0 Nextjs?

由 Auth0(@auth0)开发并维护,当前版本 v1.0.0。

💬 留言讨论