Auth0 Integration Guide

Technology: auth0 · Category: auth · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/auth0

Insight:

Auth0 is advertised on motionstackstudios.com, but it is not a house default — the dashboard ships custom Argon2 + session auth, and Clerk is the managed-auth default. Reach for Auth0 only when a client specifically requires it: enterprise SSO/SAML, B2B Organizations, an existing Auth0 tenant, or Token Vault for an AI agent that acts in users' Google/GitHub/Slack accounts. Before adopting it, consult the codeAmani-tech-stack MCP and confirm the house defaults won't do.

 █████╗ ██╗   ██╗████████╗██╗  ██╗ ██████╗
██╔══██╗██║   ██║╚══██╔══╝██║  ██║██╔═████╗
███████║██║   ██║   ██║   ███████║██║██╔██║
██╔══██║██║   ██║   ██║   ██╔══██║████╔╝██║
██║  ██║╚██████╔╝   ██║   ██║  ██║╚██████╔╝
╚═╝  ╚═╝ ╚═════╝    ╚═╝   ╚═╝  ╚═╝ ╚═════╝

Auth0 Integration Guide

Focus: When and how codeAmani uses Auth0 for client projects that specifically need it: enterprise SSO/SAML, B2B Organizations, an inherited Auth0 tenant, or Auth0 for AI Agents (Token Vault). Covers the @auth0/nextjs-auth0 4.32 App Router SDK on Next.js 15/16 (proxy.ts, auth0.getSession()), RBAC, the Management API via the auth0 node SDK v7, JWT verification with jose, and Token Vault tools for agents.

Overview

Auth0 (an Okta company, branded "Auth0 by Okta") is an identity platform built on OAuth 2.0 / OIDC. Universal Login hosts the sign-in page. The app receives an authorization code at a callback, exchanges it for an encrypted session cookie, and reads the user from that session after that. Auth0 also covers social and enterprise connections, RBAC with permissions, post-login Actions, a Management API for user and role admin, Organizations for B2B multi-tenancy, and, since 2025, Auth0 for AI Agents: Token Vault, Async Authorization (CIBA), FGA for RAG, and Auth for MCP.

Auth0 is listed as an auth option on motionstackstudios.com, but it is not a house default. The agency's own dashboard runs custom Argon2id password hashing + server-side sessions, and Clerk (see the clerk guide) is the managed-auth default for most builds: drop-in components, Svix-verified webhooks, simpler pricing. Auth0 only earns a place when a client needs one of the things it does best:

flowchart TD
    A["New client build<br/>needs authentication"] --> B{"Hard requirement for Auth0?<br/>(enterprise SSO/SAML, B2B orgs,<br/>existing tenant, Token Vault)"}
    B -->|No| C["House defaults<br/>custom Argon2 + sessions · Clerk"]
    B -->|Yes| D["Auth0 tenant<br/>(per-client, isolated)"]
    D --> E["@auth0/nextjs-auth0 4.32<br/>Universal Login · proxy.ts"]
    E --> F["RBAC · Actions · Organizations"]
    E --> H["Auth0 for AI Agents<br/>Token Vault · CIBA"]
    F --> G["Management API (auth0 v7)<br/>JWT verify (jose) for APIs"]

Check first. Before adopting Auth0, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm a cheaper option won't satisfy the requirement: Clerk (the managed default), the dashboard's custom Argon2 + sessions, or self-hosted Better Auth (see the better-auth guide: no per-MAU bill, a JOIN-able user table you own). Auth0 adds a vendor, per-MAU cost, and an extra tenant to operate. Prefer one of those unless the client specifically needs Auth0's enterprise SSO/SAML, B2B Organizations, or Token Vault.

The OAuth/OIDC login flow the SDK wires up:

sequenceDiagram
  participant U as "User"
  participant App as "Next.js app"
  participant PX as "proxy.ts (auth0.middleware)"
  participant A0 as "Auth0 (Universal Login)"
  U->>App: "Visit /dashboard (protected)"
  App->>PX: "Request hits proxy"
  PX->>A0: "No session → redirect to /authorize"
  A0->>U: "Universal Login (social / DB / enterprise)"
  U->>A0: "Authenticate (+ MFA if enforced)"
  A0->>App: "Redirect to /auth/callback?code=..."
  App->>A0: "Exchange code for ID + access + refresh tokens"
  A0-->>App: "Tokens → set encrypted session cookie"
  App-->>U: "Render /dashboard (auth0.getSession())"

Official Documentation

Resource URL
Auth0 Docs (root) https://auth0.com/docs
Next.js SDK (@auth0/nextjs-auth0 v4) https://github.com/auth0/nextjs-auth0
Next.js SDK examples (EXAMPLES.md) https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md
Management API v2 https://auth0.com/docs/api/management/v2
auth0 node SDK v7 migration guide https://github.com/auth0/node-auth0/blob/master/v7_MIGRATION_GUIDE.md
Actions (post-login triggers) https://auth0.com/docs/customize/actions
RBAC (roles & permissions) https://auth0.com/docs/manage-users/access-control/rbac
Organizations (B2B) https://auth0.com/docs/manage-users/organizations
Token Vault https://auth0.com/docs/secure/call-apis-on-users-behalf/token-vault
Auth0 for AI Agents docs https://auth0.com/ai/docs/intro/overview
Pricing https://auth0.com/pricing

No house Auth0 MCP server. Auth0 publishes @auth0/auth0-mcp-server (tenant management from an AI client), but it is still beta (0.1.0-beta.19), so it isn't in the house stack. This Claude Code environment has the auth0 plugin skills (auth0:auth0-nextjs, auth0:auth0-migration, auth0:auth0-mfa, …), and @auth0/nextjs-auth0 ≥ 4.31.1 ships agent skills inside the package. When unsure about a current API, query Context7 (/auth0/nextjs-auth0, /websites/auth0_ai) rather than recalling v3 patterns.


Next.js App Router Setup (@auth0/nextjs-auth0 v4)

The v4 SDK (current: 4.32.1, peer next ^14.2.35 || ~15.x patched || ^16.0.10, React ^18 || ^19.2.1) is a clean break from v3. There is no handleAuth() catch-all route and no UserProvider wrapper you need. You instantiate a single Auth0Client, mount it in proxy.ts (Next.js 16) or middleware.ts (Next.js 15), and the SDK serves /auth/login, /auth/logout, /auth/callback, /auth/profile, /auth/access-token, /auth/backchannel-logout, and /auth/connect if you turn it on.

npm install @auth0/nextjs-auth0   # 4.32.1 at last review — use ≥ 4.32.0 (open-redirect fix)

A complete, type-checked app lives in examples/nextjs-app-router/.

1. The Auth0 client

lib/auth0.ts:

import { Auth0Client } from "@auth0/nextjs-auth0/server";

// Reads AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, AUTH0_SECRET,
// and APP_BASE_URL from the environment automatically.
export const auth0 = new Auth0Client({
  authorizationParameters: {
    scope: "openid profile email offline_access",
    // Set an audience to receive a JWT access token for your own API.
    audience: process.env.AUTH0_AUDIENCE,
  },
  // Only if you use Token Vault: mounts /auth/connect for connected accounts.
  // enableConnectAccountEndpoint: true,
});

2. proxy.ts mounts the routes

Next.js 16 renamed middleware.ts to proxy.ts and the export from middleware to proxy. middleware.ts still works on the Edge runtime in Next 16, but it is deprecated for Node and will be removed later.

proxy.ts (project root):

import { auth0 } from "./lib/auth0";

export async function proxy(request: Request) {
  // Serves /auth/* and rolls the session cookie on every request.
  return await auth0.middleware(request);
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
};

Next.js 15: name the file middleware.ts and export async function middleware(request: NextRequest). The body is identical. All helpers (getSession, updateSession, getAccessToken) work the same on both.

3. The login / logout UI

The SDK exposes the auth actions as plain links. No client component is needed.

app/layout.tsx:

import type { ReactNode } from "react";
import { auth0 } from "@/lib/auth0";

export default async function RootLayout({ children }: { children: ReactNode }) {
  const session = await auth0.getSession();

  return (
    <html lang="en">
      <body>
        <header style={{ display: "flex", justifyContent: "flex-end", gap: 12, padding: 16 }}>
          {session ? (
            <a href="/auth/logout">Log out ({session.user.name})</a>
          ) : (
            <a href="/auth/login?returnTo=/dashboard">Log in</a>
          )}
        </header>
        {children}
      </body>
    </html>
  );
}

Gotcha: In v4 the login route is /auth/login, not /api/auth/login (that was v3). Use plain <a> tags, not <Link>, because the auth routes need full navigations. If you rename routes with the routes option on Auth0Client, update these links to match.


Protecting Routes

There are two layers. The proxy refreshes and attaches the session, and each protected page or API route reads it.

Server Components

app/dashboard/page.tsx:

import { redirect } from "next/navigation";
import { auth0 } from "@/lib/auth0";

export default async function DashboardPage() {
  const session = await auth0.getSession();

  if (!session) {
    // Bounce through Universal Login, then return here.
    redirect("/auth/login?returnTo=/dashboard");
  }

  return <h1>Welcome, {session.user.name}</h1>;
}

Or wrap it with the helper. returnTo is required in the App Router because Server Components don't know their own URL:

import { auth0 } from "@/lib/auth0";

export default auth0.withPageAuthRequired(
  async function Profile() {
    const session = await auth0.getSession();
    return <div>Hello {session?.user.name}</div>;
  },
  { returnTo: "/profile" }
);

API Route Handlers

app/api/me/route.ts:

import { NextResponse } from "next/server";
import { auth0 } from "@/lib/auth0";

export async function GET() {
  const session = await auth0.getSession();

  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // Never return session.tokenSet to the browser.
  return NextResponse.json({ user: session.user });
}

RBAC (Roles & Permissions)

Enable RBAC on the API in the Auth0 dashboard (APIs → your API → RBAC Settings → "Enable RBAC" + "Add Permissions in the Access Token"). Then assign roles to users. The role's permissions land in the access token's permissions claim. On B2C plans, Role Management needs Essentials or above (it isn't on Free).

Roles don't appear in the ID token by default. Surface them with a post-login Action under a namespaced custom claim, because Auth0 silently drops non-namespaced claims:

// Auth0 Dashboard → Actions → Library → Post Login
exports.onExecutePostLogin = async (event, api) => {
  const namespace = "https://motionstack.app";
  const roles = event.authorization?.roles ?? [];

  api.idToken.setCustomClaim(`${namespace}/roles`, roles);
  api.accessToken.setCustomClaim(`${namespace}/roles`, roles);
};

Read roles from the session:

// lib/rbac.ts
import { auth0 } from "@/lib/auth0";

const NS = "https://motionstack.app";

export async function getRoles(): Promise<string[]> {
  const session = await auth0.getSession();
  const claim: unknown = session?.user?.[`${NS}/roles`];
  return Array.isArray(claim) ? claim.filter((r): r is string => typeof r === "string") : [];
}

Gotcha: Custom claims must be fully-qualified URLs (a namespace you control). Auth0 strips a bare roles claim, so it will silently never appear in the token.


Management API (the auth0 node SDK, v7)

For server-side user and role admin (listing users, assigning roles, updating metadata), use the auth0 node SDK's ManagementClient. Create a Machine-to-Machine application in the dashboard, authorize it for the Auth0 Management API, and grant only the scopes you need (read:users, update:users, create:role_members, …). The SDK fetches and caches its own token with client credentials.

npm install auth0   # 7.6.0 at last review — Node ^20.19 || ^22.12 || ^24 || ^26
// lib/auth0-management.ts
import { ManagementClient } from "auth0";

export const management = new ManagementClient({
  domain: process.env.AUTH0_DOMAIN!,           // bare host, e.g. acme.us.auth0.com — v7 throws on a scheme
  clientId: process.env.AUTH0_M2M_CLIENT_ID!,
  clientSecret: process.env.AUTH0_M2M_CLIENT_SECRET!,
});

/** Assign a role to a user (e.g. after a Stripe upgrade webhook). */
export async function grantRole(userId: string, roleId: string): Promise<void> {
  await management.users.roles.assign(userId, { roles: [roleId] });
}

/** Persist app-level state on the Auth0 user record. */
export async function setPlan(userId: string, plan: string): Promise<void> {
  await management.users.update(userId, { app_metadata: { plan } });
}

/** Look up a user by email (admin tooling). */
export async function findByEmail(email: string) {
  // v5+ returns the array directly — there is no `.data` wrapper.
  return await management.users.listUsersByEmail({ email });
}

v7 (Sep 2026) breaking changes. ManagementClient and its method surface are unchanged from v5/v6. The code above type-checks against 7.6.0. What changed:

  • AuthenticationClient and UserInfoClient are gone from the auth0 entrypoint. Token grants moved to AuthClient in @auth0/auth0-auth-js (for example, getTokenByClientCredentials(...)). auth0/legacy keeps the old clients as a temporary stopgap.
  • domain must be a bare hostname. A scheme, slash, or query string throws at construction.
  • Token failures throw ManagementError (with statusCode and a parsed body). A token request over 10 s throws 408.
  • useMTLS: true now needs an explicit fetch that carries the client certificate.

The v5 regeneration is still the big one if you're coming from v4: positional args (users.update(userId, body)), sub-clients (users.roles.assign, users.listUsersByEmail), and no { data } wrapper (use .withRawResponse() for headers). Any snippet with assignRoles(...), usersByEmail.getByEmail(...), or { id }-wrapped args is pre-v5 and won't compile.

Gotcha: The Management API is heavily rate-limited, and M2M tokens are metered by plan (1,000/month on Free and Essentials, 5,000 on Professional). Never call it on a hot request path. Call it only from webhooks, admin actions, and background jobs. Use app_metadata (server-controlled) for authorization-relevant fields and user_metadata (user-editable) for preferences.


JWT Verification for APIs

When a separate service (a mobile app, a backend microservice, a third party) calls your API with a Bearer token issued by Auth0, verify the JWT against Auth0's published JWKS. Check the signature, issuer, audience, and expiry. The house choice is jose (6.2.12). It runs on Node, Edge, and Workers runtimes, and createRemoteJWKSet caches the keys. jsonwebtoken + jwks-rsa still work, but only on Node. For Express services, use Auth0's express-oauth2-jwt-bearer (1.11.0).

npm install jose
// lib/verify-jwt.ts
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";

const issuer = `https://${process.env.AUTH0_DOMAIN}/`;
const JWKS = createRemoteJWKSet(new URL(`${issuer}.well-known/jwks.json`));

export type Auth0Claims = JWTPayload & { scope?: string; permissions?: string[] };

/** Verify signature (RS256), issuer, audience and expiry; return the claims. */
export async function verifyAccessToken(token: string): Promise<Auth0Claims> {
  const { payload } = await jwtVerify<Auth0Claims>(token, JWKS, {
    issuer,
    audience: process.env.AUTH0_AUDIENCE,
    algorithms: ["RS256"],
  });
  return payload;
}

export function hasScope(claims: Auth0Claims, needed: string): boolean {
  const scopes = claims.scope?.split(" ") ?? [];
  return scopes.includes(needed) || (claims.permissions ?? []).includes(needed);
}

Use it to guard a machine-facing route:

// app/api/v1/orders/route.ts
import { NextResponse, type NextRequest } from "next/server";
import { hasScope, verifyAccessToken } from "@/lib/verify-jwt";

export async function GET(req: NextRequest) {
  const auth = req.headers.get("authorization");
  if (!auth?.startsWith("Bearer ")) {
    return NextResponse.json({ error: "Missing bearer token" }, { status: 401 });
  }

  try {
    const claims = await verifyAccessToken(auth.slice(7));
    if (!hasScope(claims, "read:orders")) {
      return NextResponse.json({ error: "Insufficient scope" }, { status: 403 });
    }
    return NextResponse.json({ sub: claims.sub, orders: [] });
  } catch {
    return NextResponse.json({ error: "Invalid token" }, { status: 401 });
  }
}

Note: This is for separate API callers. For the browser app itself, auth0.getSession() is the path. Don't re-verify the SDK's own session cookie by hand.


Calling Your Own API From the App

When the app needs to call a downstream API with a real Auth0-issued access token, get it with auth0.getAccessToken(). The SDK handles refresh through offline_access:

// app/api/data/route.ts
import { NextResponse } from "next/server";
import { auth0 } from "@/lib/auth0";

export async function GET() {
  const { token } = await auth0.getAccessToken();

  const res = await fetch("https://data-api.example.com/records", {
    headers: { Authorization: `Bearer ${token}` },
  });

  return NextResponse.json(await res.json());
}

Auth0 for AI Agents (Token Vault, CIBA)

Auth0 for AI Agents is Auth0's identity layer for agents. It has four parts:

Capability What it does When codeAmani uses it
Token Vault Stores users' third-party OAuth refresh tokens (Google, GitHub, Slack, Salesforce, 30+ integrations, or any OAuth 2.0 provider) and hands the agent short-lived access tokens through token exchange. The agent never sees the user's credentials. An agent that reads a user's calendar or inbox, or opens PRs, on that user's behalf
Async Authorization (CIBA) Human-in-the-loop approval. The tool pauses until the user approves a push or email prompt with a binding message. High-risk tool calls: payments, trades, deletes
FGA for RAG Filters retrieved documents by the user's fine-grained permissions before they reach the model Multi-tenant RAG over private documents
Auth for MCP OAuth 2.1 / OIDC for remote MCP servers: client registration, resource-scoped tokens, and on-behalf-of token exchange Shipping a hosted MCP server that needs user auth

Pricing: on paid plans, Auth0 for AI Agents is an add-on that adds 50% to the base price (unlimited Token Vault + all forms of CIBA). The Free plan includes Token Vault (limit "2") but not CIBA. See Pricing.

Connecting an account (Next.js SDK)

Turn on enableConnectAccountEndpoint: true in Auth0Client, enable Offline Access in the connection's permissions, then send the user to the connect endpoint:

<a href="/auth/connect?connection=google-oauth2&returnTo=/dashboard">Connect Google Calendar</a>

You can do the same thing in code with auth0.connectAccount({ connection, scopes, authorizationParams, returnTo }), which returns a redirect NextResponse. For a non-agent server route, auth0.getAccessTokenForConnection({ connection: "github" }) returns { token } for a connected account.

A Token Vault tool for an agent (@auth0/ai-vercel)

npm install @auth0/ai-vercel @auth0/ai ai@6 zod   # ai-vercel 5.1.1 peers on ai ^5 || ^6 — not ai 7 yet
// lib/auth0-ai.ts
import { Auth0AI, getAccessTokenFromTokenVault } from "@auth0/ai-vercel";
import { TokenVaultError } from "@auth0/ai/interrupts";
import { tool } from "ai";
import { z } from "zod";
import { auth0 } from "@/lib/auth0";

// Defaults to AUTH0_DOMAIN / AUTH0_CLIENT_ID / AUTH0_CLIENT_SECRET.
const auth0AI = new Auth0AI();

export const withGoogleCalendar = auth0AI.withTokenVault({
  connection: "google-oauth2",
  scopes: ["openid", "https://www.googleapis.com/auth/calendar.freebusy"],
  refreshToken: async () => (await auth0.getSession())?.tokenSet.refreshToken,
});

export const checkCalendar = withGoogleCalendar(
  tool({
    description: "Check whether the user is free for one hour from the given time",
    inputSchema: z.object({ start: z.string() }),
    execute: async ({ start }) => {
      const accessToken = getAccessTokenFromTokenVault(); // short-lived Google token
      const timeMin = new Date(start);
      const res = await fetch("https://www.googleapis.com/calendar/v3/freeBusy", {
        method: "POST",
        headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
        body: JSON.stringify({
          timeMin: timeMin.toISOString(),
          timeMax: new Date(timeMin.getTime() + 3_600_000).toISOString(),
          items: [{ id: "primary" }],
        }),
      });
      if (res.status === 401) throw new TokenVaultError("Authorization required to access Google Calendar");
      const data = (await res.json()) as { calendars?: { primary?: { busy?: unknown[] } } };
      return { available: (data.calendars?.primary?.busy?.length ?? 0) === 0 };
    },
  }),
);

In the agent route, call setAIContext({ threadID }) before streamText(...) so Token Vault credentials are cached per thread (the default credentialsContext is "thread"). For chat UIs, wrap the stream in withInterruptions(...) from @auth0/ai-vercel/interrupts so a TokenVaultError becomes a "connect your account" prompt instead of a failure. CIBA works the same way: auth0AI.withAsyncAuthorization({ userID, bindingMessage, scopes, audience }) wraps a tool, and getAsyncAuthorizationCredentials() reads the approved token inside it. LangChain and LlamaIndex users get the same API from @auth0/ai-langchain and @auth0/ai-llamaindex.

AI routing still applies. Token Vault is about whose credentials a tool uses. The model choice follows house routing (Claude primary). The example routes the model through the Vercel AI Gateway by string id.


Organizations (B2B Multi-Tenancy)

For B2B clients, Organizations model each customer company as a tenant with its own members, roles, and its own enterprise connection. That way Acme logs in through their Okta SAML and Globex through their Entra ID, all in one Auth0 tenant. Enable "Organizations" on the application, then route users through an org-scoped login:

// app/teams/[orgId]/login/route.ts
import { redirect } from "next/navigation";

export async function GET(_: Request, { params }: { params: Promise<{ orgId: string }> }) {
  const { orgId } = await params; // Next.js 15+: params is a Promise
  redirect(`/auth/login?organization=${encodeURIComponent(orgId)}&returnTo=/teams/${encodeURIComponent(orgId)}`);
}

The active organization lands in the session as the org_id claim. Gate org-scoped data on it. This is the main reason a codeAmani client picks Auth0 over Clerk: per-organization SAML/OIDC enterprise connections out of the box. As of 2026 the Free plan includes 1 enterprise connection, 5 Organizations, Self-Service SSO, and inbound SCIM, so a pilot with one enterprise customer can start at $0.


Pricing (checked 2026-10-20)

Source: https://auth0.com/pricing. Paid plans are priced by MAU tier, and B2C and B2B differ. Yearly billing is 11× the monthly price.

Plan B2C from B2B from Notes
Free $0 $0 Up to 25,000 MAU, 1 custom domain, 5 Organizations, 1 enterprise connection, Self-Service SSO, SCIM, 1,000 M2M tokens, Token Vault (2)
Essentials $35/mo (500 MAU) $150/mo (500 MAU) Pro MFA, RBAC, log streaming. B2B adds unlimited Orgs + 3 enterprise SSO connections
Professional $240/mo (500 MAU) $800/mo (500 MAU) Enhanced attack protection, custom DB, Enterprise MFA, 5,000 M2M tokens
Enterprise Contact sales Contact sales 99.99% SLA, HIPAA/BAA add-on, private deployment

Add-ons: Auth0 for AI Agents adds +50% of base. Extra enterprise SSO connections are $100/mo each (max 30). Enterprise MFA on Essentials is $100/mo. M2M token packs start at $10/mo (B2B, 2,500 tokens). A client between tiers is billed at the next tier up.


Environment Variables

Secrets (store in the vault, never in the bundle):

AUTH0_CLIENT_SECRET=your-regular-web-app-client-secret
AUTH0_SECRET=output-of-openssl-rand-hex-32
AUTH0_M2M_CLIENT_SECRET=your-m2m-client-secret

Non-secret settings:

Variable Example Purpose
AUTH0_DOMAIN acme.us.auth0.com Tenant (or custom) domain. Bare host, no https:// (the v7 node SDK throws on a scheme)
AUTH0_CLIENT_ID from the dashboard The Regular Web Application's client ID
APP_BASE_URL http://localhost:3000 Your app's base URL (prod: https://app.example.com)
AUTH0_AUDIENCE https://api.example.com Optional. API identifier, so you get a JWT access token
AUTH0_M2M_CLIENT_ID from the dashboard Management API M2M application
AI_MODEL an AI Gateway model id Only for the agent example

Add these to ENV_MASTER.md and each project's .env.example. AUTH0_SECRET encrypts the session cookie. If you rotate it, every session is invalidated, so treat it like a signing key and keep it identical across instances. AUTH0_DOMAIN must be the bare host: the v3 AUTH0_ISSUER_BASE_URL (with a scheme) is gone, and AUTH0_BASE_URL was renamed to APP_BASE_URL in v4.


Automation Workflows

Claude Code slash command: scaffold Auth0 auth

.claude/commands/auth0-setup.md:

Scaffold @auth0/nextjs-auth0 v4 (≥ 4.32) authentication for this Next.js App Router project.

First confirm Auth0 is actually required (enterprise SSO/SAML, B2B orgs, an
existing tenant, or Token Vault for an agent). If not, recommend Clerk per the
house default and stop. Then:

1. Run `npm view @auth0/nextjs-auth0 version` and install that version.
2. Create `lib/auth0.ts` exporting a configured `Auth0Client`.
3. Next.js 16: create `proxy.ts` exporting `proxy(request)` → `auth0.middleware(request)`.
   Next.js 15: `middleware.ts` exporting `middleware`. Use the asset-excluding matcher.
4. Add log-in / log-out links to `app/layout.tsx` (`/auth/login`, `/auth/logout`) as plain <a>.
5. Add a protected `app/dashboard/page.tsx` using `auth0.getSession()`.
6. Document the env vars in `.env.example` (secrets as empty placeholders).
7. Report manual dashboard steps: create the app, set Allowed Callback URLs to
   `${APP_BASE_URL}/auth/callback` and Allowed Logout URLs to `${APP_BASE_URL}`.

Usage: /project:auth0-setup. The auth0:auth0-nextjs plugin skill covers the same ground interactively.

GitHub Actions: verify Auth0 config

# .github/workflows/auth0-verify.yml
name: Verify Auth0 Config
on: [pull_request]

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci
      - name: Check proxy/middleware exists
        run: test -f proxy.ts || test -f middleware.ts || (echo "Missing proxy.ts / middleware.ts!" && exit 1)
      - name: Check required env vars documented
        run: |
          for v in AUTH0_DOMAIN AUTH0_CLIENT_ID AUTH0_CLIENT_SECRET AUTH0_SECRET APP_BASE_URL; do
            grep -q "$v" .env.example || echo "Warning: $v missing from .env.example"
          done

Pin third-party Actions to a commit SHA in real projects (see the SLSA section of CLAUDE.md).


Common Use Cases

Use Case Approach
Default managed auth Clerk (house default). Use Auth0 only when a client requires it
Default in-app auth Custom Argon2 + sessions (the dashboard). Auth0 doesn't replace it
Add Auth0 to Next.js /project:auth0-setup or the auth0:auth0-nextjs skill
Read the current user auth0.getSession() in a Server Component / Route Handler
Protect a page auth0.withPageAuthRequired(fn, { returnTo }) or a getSession() guard
Social / enterprise login Configure connections in the dashboard. Universal Login picks them up
RBAC / permissions Enable RBAC on the API + a namespaced-claim post-login Action
Admin user/role management Management API via auth0 v7 ManagementClient
Client-credentials token in code AuthClient from @auth0/auth0-auth-js (not auth0 v7)
Verify a machine-issued JWT jose jwtVerify + createRemoteJWKSet
Call your own API auth0.getAccessToken() with an audience configured
Agent acts in user's Google/GitHub Token Vault: /auth/connect + @auth0/ai-vercel withTokenVault
Human approval for risky agent action CIBA: withAsyncAuthorization
B2B SSO / per-tenant SAML Auth0 Organizations + enterprise connections
MFA enforcement Dashboard → Security → Multi-factor Auth (or a post-login Action)

Troubleshooting

Issue Fix
404 on /api/auth/login v4 uses /auth/login (no /api). Update links. This is the #1 v3→v4 break
Auth routes 404 on Next.js 16 The file must be proxy.ts exporting proxy (or Edge-only middleware.ts). Check the matcher doesn't exclude /auth/*
callback URL mismatch Add ${APP_BASE_URL}/auth/callback to the app's Allowed Callback URLs
State error / forced re-login right after a deploy 4.29.0 changed the __txn_* cookie format. Logins started on the old version and finished on the new one fail once. Expected during rolling deploys
HTTP 431 (headers too large) Pile-up of __txn_* cookies. Upgrade to ≥ 4.29.0 (FIFO eviction, 3,500-byte cap)
AUTH0_DOMAIN errors / invalid issuer / ManagementClient throws at startup Use the bare host (acme.us.auth0.com). No https://
All users logged out unexpectedly AUTH0_SECRET changed (or differs across instances). It must be stable and identical everywhere
Roles missing from token Add a post-login Action that sets a namespaced custom claim. Bare roles is stripped
permissions claim empty Enable RBAC + "Add Permissions in the Access Token" on the API, and set an audience
JWSSignatureVerificationFailed / JWTClaimValidationFailed Confirm RS256, the JWKS URI https://${AUTH0_DOMAIN}/.well-known/jwks.json, and the audience/issuer (trailing slash)
AuthenticationClient is not exported (v7) Move token grants to @auth0/auth0-auth-js AuthClient, or import from auth0/legacy temporarily
Management API 429 You're calling it on a hot path. Move it to webhooks or jobs
Management API 403 insufficient_scope Grant the specific scope (e.g. update:users) to the M2M app
Token Vault: TokenVaultError / no refresh token Request offline_access, enable Offline Access on the connection, and have the user visit /auth/connect
@auth0/ai-vercel peer-dep conflict It supports ai ^5 or ^6. Pin ai@6 until a release adds ai 7

codeAmani notes

Official docs: