MCPcopy Index your code
hub / github.com/auth0/nextjs-auth0

github.com/auth0/nextjs-auth0 @v4.24.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v4.24.0 ↗ · + Follow
981 symbols 2,982 edges 324 files 168 documented · 17% 3 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Auth0 Next.js SDK Banner

The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications.

Auth0 Next.js SDK Release Ask DeepWiki Auth0 Next.js SDK Downloads Auth0 Next.js SDK License

📚 Documentation - 🚀 Getting Started - 💻 API Reference - 💬 Feedback

Documentation

  • QuickStart - our guide for adding Auth0 to your Next.js app.
  • Examples - lots of examples for your different use cases.
  • Security - Some important security notices that you should check.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

1. Install the SDK

npm i @auth0/nextjs-auth0

This library requires Node.js 20 LTS and newer LTS versions.

2. Add the environment variables

Add the following environment variables to your .env.local file:

AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=
AUTH0_SECRET=
APP_BASE_URL= # optional for dynamic preview environments

The AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET can be obtained from the Auth0 Dashboard once you've created an application. This application must be a Regular Web Application.

The AUTH0_SECRET is the key used to encrypt the session and transaction cookies. You can generate a secret using openssl:

openssl rand -hex 32

The APP_BASE_URL is the URL that your application is running on. When developing locally, this is most commonly http://localhost:3000. If you omit it, the SDK will infer the base URL from the incoming request host at runtime.

[!IMPORTANT]
You will need to register the following URLs in your Auth0 Application via the Auth0 Dashboard:

  • Add http://localhost:3000/auth/callback to the list of Allowed Callback URLs
  • Add http://localhost:3000 to the list of Allowed Logout URLs

When using dynamic hosts (preview environments), ensure the resulting callback and logout URLs are registered in your Auth0 application.

Dynamic base URLs (Preview deployments)

For preview environments (Vercel, Netlify), you can omit APP_BASE_URL and let the SDK infer the base URL from the incoming request host at runtime. This keeps dynamic preview URLs working without extra configuration.

If you know the base URL at startup (for example, a stable production domain), set appBaseUrl or APP_BASE_URL to a single absolute URL. Comma-separated values are not supported.

Because the Host header is untrusted input, Auth0's Allowed Callback URLs are the safety net in this mode: if the inferred host is not registered, Auth0 rejects the authorize request.

Example (dynamic):

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

export const auth0 = new Auth0Client();

Example (static):

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

export const auth0 = new Auth0Client({
  appBaseUrl: "https://app.example.com"
});

[!NOTE]
When relying on dynamic base URLs in production, the SDK enforces secure cookies. If you explicitly set AUTH0_COOKIE_SECURE=false, session.cookie.secure=false, or transactionCookie.secure=false, the SDK throws InvalidConfigurationError.

3. Create the Auth0 SDK client

Create an instance of the Auth0 client. This instance will be imported and used in anywhere you need access to the authentication methods on the server.

Add the following contents to a file named lib/auth0.ts:

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

export const auth0 = new Auth0Client();

[!NOTE] The Auth0Client automatically uses safe defaults to manage authentication cookies. For advanced use cases, you can customize transaction cookie behavior by providing your own configuration. See Transaction Cookie Configuration for details.

4. Add the authentication middleware

Authentication requests in Next.js are intercepted at the network boundary using a middleware or proxy file.
Follow the setup below depending on your Next.js version.

🟦 On Next.js 15

Create a middleware.ts file in the root of your project:

import type { NextRequest } from "next/server";

import { auth0 } from "./lib/auth0"; // Adjust path if your auth0 client is elsewhere

export async function middleware(request: NextRequest) {
  return await auth0.middleware(request);
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"
  ]
};

[!NOTE]
If you're using a src/ directory, the middleware.ts file must be created inside the src/ directory.

🟨 On Next.js 16

Next.js 16 introduces a new convention called proxy.ts, replacing middleware.ts. This change better represents the network interception boundary and unifies request handling for both the Edge and Node runtimes.

Create a proxy.ts file in the root of your project (Or rename your existing middleware.ts to proxy.ts):

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

export async function proxy(request: Request) { // Note that proxy uses the standard Request type
  return await auth0.middleware(request);
}

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

[!IMPORTANT]
Starting with Next.js 16, the recommended file for handling authentication boundaries is proxy.ts. You can still continue using middleware.ts for backward compatibility, it will work under the Edge runtime in Next.js 16. However, it is deprecated for the Node runtime and will be removed in a future release.

The new proxy layer also executes slightly earlier in the routing pipeline, so make sure your matcher patterns do not conflict with other proxy or middleware routes.

Additionally, the Edge runtime now applies stricter header and cookie validation,
so avoid setting non-string cookie values or invalid header formats.

[!IMPORTANT] This broad middleware matcher is essential for rolling sessions and security features. For scenarios when rolling sessions are disabled, see Session Configuration for alternative approaches.

You can now begin to authenticate your users by redirecting them to your application's /auth/login route:

import { auth0 } from "./lib/auth0"; // Adjust path if your auth0 client is elsewhere

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

  if (!session) {
    return (
      <main>
        <a href="https://github.com/auth0/nextjs-auth0/raw/v4.24.0/auth/login?screen_hint=signup">Sign up</a>
        <a href="https://github.com/auth0/nextjs-auth0/raw/v4.24.0/auth/login">Log in</a>
      </main>
    );
  }

  return (
    <main>
      <h1>Welcome, {session.user.name}!</h1>
    </main>
  );
}

[!IMPORTANT]
You must use <a> tags instead of the <Link> component to ensure that the routing is not done client-side as that may result in some unexpected behavior.

Customizing the client

You can customize the client by using the options below:

Option Type Description
domain string \| DomainResolver The Auth0 domain for the tenant (e.g.: example.us.auth0.com). Accepts a static string or a DomainResolver function for Multiple Custom Domains. Falls back to AUTH0_DOMAIN environment variable.
clientId string The Auth0 client ID. If it's not specified, it will be loaded from the AUTH0_CLIENT_ID environment variable.
clientSecret string The Auth0 client secret. If it's not specified, it will be loaded from the AUTH0_CLIENT_SECRET environment variable.
authorizationParameters AuthorizationParameters The authorization parameters to pass to the /authorize endpoint. See Passing authorization parameters for more details.
clientAssertionSigningKey string or CryptoKey Private key for use with private_key_jwt clients. This can also be specified via the AUTH0_CLIENT_ASSERTION_SIGNING_KEY environment variable.
clientAssertionSigningAlg string The algorithm used to sign the client assertion JWT. This can also be provided via the AUTH0_CLIENT_ASSERTION_SIGNING_ALG environment variable.
appBaseUrl string The URL of your application (e.g.: http://localhost:3000). If it's not specified, it will be loaded from the APP_BASE_URL environment variable or inferred from the request host at runtime.
logoutStrategy "auto" \| "oidc" \| "v2" Strategy for logout endpoint selection. "auto" (default) uses OIDC logout when available, falls back to /v2/logout. "oidc" always uses OIDC logout. "v2" always uses /v2/logout endpoint which supports wildcard URLs. See Configuring logout strategy for details.
includeIdTokenHintInOIDCLogoutUrl boolean Configure whether to include id_token_hint in OIDC logout URLs for privacy. Defaults to true (recommended). When false, excludes PII from logout URLs but reduces DoS protection. Se

Extension points exported contracts — how you extend this code

PasswordlessClient (Interface)
(no doc) [4 implementers]
src/types/passwordless.ts
ValidateDomainHostnameOptions (Interface)
* Options for domain validation.
src/utils/normalize.ts
DiscoveryCacheEntry (Interface)
* Entry in the discovery cache for OIDC metadata. * * @internal
src/server/discovery-cache.ts
ChallengeWithPopupOptions (Interface)
(no doc)
src/client/mfa/index.ts
MfaTestScenario (Interface)
(no doc)
src/test/mfa-scenarios-shared.ts
PasswordlessApiErrorResponse (Interface)
(no doc)
src/errors/passwordless-errors.ts
SheetContentProps (Interface)
(no doc)
examples/with-shadcn/components/ui/sheet.tsx
SheetContentProps (Interface)
(no doc)
examples/with-mrrt/components/ui/sheet.tsx

Core symbols most depended-on inside this repo

get
called by 1024
src/types/index.ts
set
called by 418
src/types/index.ts
generateSecret
called by 333
src/test/utils.ts
getDefaultRoutes
called by 304
src/test/defaults.ts
handler
called by 158
src/server/auth-client.ts
has
called by 122
src/utils/lru-map.ts
encrypt
called by 114
src/server/cookies.ts
normalizeDomain
called by 86
src/utils/normalize.ts

Shape

Function 468
Method 272
Class 129
Interface 104
Enum 8

Languages

TypeScript100%

Modules by API surface

src/server/auth-client.ts85 symbols
docs/assets/main.js68 symbols
src/errors/oauth-errors.ts45 symbols
src/errors/mfa-errors.ts34 symbols
src/server/client.ts26 symbols
src/types/passkey.ts24 symbols
src/types/mfa.ts24 symbols
src/errors/passkey-errors.ts23 symbols
src/errors/popup-errors.ts15 symbols
src/client/passkey/index.ts14 symbols
src/types/index.ts13 symbols
src/server/cookies.ts13 symbols

Used by 3 indexed graphs manifest dependencies, hub-wide

For agents

$ claude mcp add nextjs-auth0 \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact