
The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications.
📚 Documentation - 🚀 Getting Started - 💻 API Reference - 💬 Feedback
npm i @auth0/nextjs-auth0
This library requires Node.js 20 LTS and newer LTS versions.
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/callbackto the list of Allowed Callback URLs- Add
http://localhost:3000to the list of Allowed Logout URLsWhen using dynamic hosts (preview environments), ensure the resulting callback and logout URLs are registered in your Auth0 application.
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 setAUTH0_COOKIE_SECURE=false,session.cookie.secure=false, ortransactionCookie.secure=false, the SDK throwsInvalidConfigurationError.
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.
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.
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 asrc/directory, themiddleware.tsfile must be created inside thesrc/directory.
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 isproxy.ts. You can still continue usingmiddleware.tsfor 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.
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 |
$ claude mcp add nextjs-auth0 \
-- python -m otcore.mcp_server <graph>