Auth0 Next.js login
Auth0 Next.js login uses the @auth0/nextjs-auth0 v4 SDK. The SDK keeps the session in an encrypted cookie and answers the /auth routes from a proxy file (Next.js 16) or a middleware file (Next.js 15).
The library asks for Node.js 20 LTS or a newer LTS release. The current Auth0 quickstart also asks for npm 10 or newer, yarn 1.22 or newer, or pnpm 8 or newer. The steps below use the App Router. In the Pages Router, getSession(req) takes the request from getServerSideProps or from an API route.
Check the runtime with:
node --version
Create the application in Auth0
In the Auth0 dashboard, open Applications, then Applications, and create an application. Choose Regular Web Application. The v4 SDK reads a client secret on the server, and that application type is the one the SDK setup expects.
On the Settings tab, copy the Domain, Client ID, and Client Secret. The domain looks like your-tenant.us.auth0.com. Leave the https:// prefix off. That value is AUTH0_DOMAIN.
Still on Settings, set the URLs for local development:
Allowed Callback URLs: http://localhost:3000/auth/callback
Allowed Logout URLs: http://localhost:3000
Allowed Web Origins: http://localhost:3000
Auth0 sends the browser to the callback URL after login, and it only uses a callback that is on that list. After logout it only redirects to a URL on the logout list. The quickstart also sets Allowed Web Origins to the same origin, which is the list silent authentication checks. For a deployed site, add the live origin next to the localhost lines. The callback on that origin is https://your-domain/auth/callback.
Install the SDK
From the Next.js project:
npm install @auth0/nextjs-auth0
Put the secrets in .env.local at the project root. Next.js loads that file for the server, and a name without the NEXT_PUBLIC_ prefix is not inlined into the browser bundle. Keep the file out of git.
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
AUTH0_SECRET=
APP_BASE_URL=http://localhost:3000
AUTH0_SECRET is the key that encrypts the session cookie and the transaction cookies. Generate a 32-byte hex value:
openssl rand -hex 32
The command prints 64 hexadecimal characters. Paste that line into AUTH0_SECRET. If you change this value after people have logged in, the old cookie cannot be decrypted. The SDK then fails with JWEDecryptionFailed. Clear the site cookies and restart the dev server.
APP_BASE_URL is optional. Set it when you know the origin, such as http://localhost:3000 or a production domain. One absolute URL only. A comma-separated list is not accepted. If you omit it, the SDK takes the host from the incoming request. Preview deployments on Vercel and Netlify can use that. The host header is not a secret, so Auth0 still rejects an authorize request whose callback URL is not registered. In production, omitting APP_BASE_URL also forces secure cookies. Setting AUTH0_COOKIE_SECURE=false in that mode throws InvalidConfigurationError.
new Auth0Client() reads these variables. The constructor warns if domain, client ID, or secret is missing, and it warns if you provide neither a client secret nor a client-assertion signing key.
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client();
Save that as src/lib/auth0.ts when the project uses a src/ directory, or as lib/auth0.ts otherwise. Import this same object from pages, route handlers, and the proxy.
Proxy on Next.js 16, middleware on Next.js 15
Next.js 16 renamed middleware.ts to proxy.ts. The proxy runs on the Node.js runtime, and you cannot switch that runtime. middleware.ts still exists for the Edge runtime, and Next.js marks that file name as deprecated. On Next.js 15, keep middleware.ts and export a function named middleware.
For a Next.js 16 app with a src/ directory, src/proxy.ts looks like this. Without src/, the file sits next to app/.
import { auth0 } from "./lib/auth0";
export async function proxy(request: Request) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};
auth0.middleware(request) mounts the auth routes and runs the session logic. The matcher skips static files, the image optimizer, and the usual metadata files, then runs on every other path. That broad matcher is what rolling sessions use. A matcher that only lists /dashboard does not see the rest of the site, so those other requests do not extend the session.
On Next.js 15 the same call is export async function middleware(request: NextRequest), in middleware.ts, with the same config object. The import of auth0 is the same.
Calling the middleware does not protect pages. Any route outside /auth is public until a page or the proxy checks getSession().
The /auth routes
v4 does not use a route file. v3 mounted login with handleAuth() in app/api/auth/[auth0]/route.ts, and the URLs started with /api/auth. v4 mounts the routes from the proxy, and the /api prefix is gone.
These are the routes the proxy mounts for a normal login:
/auth/login
/auth/logout
/auth/callback
/auth/profile
/auth/access-token
/auth/backchannel-logout
/auth/login starts the authorize redirect. /auth/callback is where Auth0 returns the browser, and that exact URL has to be in Allowed Callback URLs. /auth/logout ends the session. /auth/profile returns the user attributes, and in v4 it responds with 401 when nobody is logged in. /auth/access-token returns an access token and refreshes it when a refresh token is in the session. You can turn that route off with enableAccessTokenEndpoint: false on Auth0Client when the browser should not be able to read a token.
A link to login is a plain anchor:
export function LoginButton() {
return <a href="/auth/login">Log in</a>;
}
The browser requests /auth/login. The proxy starts the Auth0 transaction and redirects the person to Auth0. After Auth0 accepts the password, it redirects to /auth/callback. The SDK stores the session cookie and then redirects to /, which is the default signInReturnToPath.
returnTo changes that last hop. /auth/login?returnTo=/dashboard lands on /dashboard after a successful login. On logout, /auth/logout?returnTo=https://example.com only works when that URL is in Allowed Logout URLs. The default logout strategy is "auto", which uses OpenID Connect RP-Initiated Logout when the tenant has it, and otherwise calls Auth0’s /v2/logout.
Next.js prefetches a <Link> in production. The default prefetch is "auto". The SDK sees that request and returns 204 without writing a transaction cookie. <Link prefetch={true}> is a full prefetch. It does not send a header the SDK recognizes, so the SDK treats it as a real visit to /auth/login and can start a login. A plain <a> tag does not prefetch.
Authorization parameters on the login URL are forwarded to Auth0. /auth/login?audience=https://api.example.com asks for an access token for that API. /auth/login?connection=google-oauth2 sends connection, which is how Auth0 selects a connection you have enabled. returnTo is not one of those parameters. The SDK uses it locally after the callback. The same authorization values can live on the client:
export const auth0 = new Auth0Client({
authorizationParameters: {
audience: "https://api.example.com",
scope: "openid profile email",
},
});
v3 read an audience from AUTH0_AUDIENCE. v4 does not. The audience has to be in authorizationParameters or on the login URL.
If /auth/login is a 404, the proxy file is missing, it is in the wrong folder, or the dev server was not restarted after the file was added. The import path has to point at the file that exports auth0.
Protect a page
getSession() returns the session, or null when there is no session. In a Server Component you call it with no arguments.
import { redirect } from "next/navigation";
import { auth0 } from "@/lib/auth0";
export default async function DashboardPage() {
const session = await auth0.getSession();
if (!session) {
redirect("/auth/login?returnTo=/dashboard");
}
return <h1>Welcome, {session.user.name}</h1>;
}
redirect runs before the page renders. The login route sends the person to Auth0, and returnTo brings them back to /dashboard. session.user.name is one of the claims the SDK keeps by default.
A route handler does the same check and returns 401 when the cookie is missing:
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 });
}
const { token, expiresAt } = await auth0.getAccessToken();
const orders = await fetch("https://api.example.com/orders", {
headers: { Authorization: `Bearer ${token}` },
});
return NextResponse.json({
sub: session.user.sub,
expiresAt,
orders: await orders.json(),
});
}
getAccessToken() returns an object. token is the access token string. expiresAt is a Unix timestamp in seconds. The fetch above sends token to your API in the Authorization header. The JSON response to the browser is the API body, the user id, and the expiry. It does not repeat the token.
If the access token is expired and the session holds a refresh token, the SDK asks Auth0 for a new one. In a Route Handler the SDK can write the updated token set through cookies(). In a Server Component that write fails, the SDK logs a warning in development, and the new token set is not stored. The caller still receives the refreshed token for this render. Call getAccessToken(request, authRes) from the proxy, where authRes is the response from auth0.middleware(request), when a later Server Component needs the refreshed token to still be in the cookie.
tokenRefreshBuffer is a number of seconds. The default is 0, so the SDK waits until the access token is expired. Set tokenRefreshBuffer: 60 and getAccessToken() refreshes a token that expires within the next minute, when a refresh token is available.
If the SDK cannot produce a token, getAccessToken() throws AccessTokenError. One case is an upstream session limit. When a connection puts session_expiry on the ID token and that time has passed, getSession() returns null and getAccessToken() throws AccessTokenError with code session_expired.
Inside the proxy, pass the request into getSession. A call with no arguments can miss a session update made earlier in the same request. Return the response from auth0.middleware when you let the request continue, so its Set-Cookie headers stay on the response.
import { NextResponse, type NextRequest } from "next/server";
import { auth0 } from "./lib/auth0";
export async function proxy(request: NextRequest) {
const authRes = await auth0.middleware(request);
if (request.nextUrl.pathname.startsWith("/auth")) {
return authRes;
}
if (request.nextUrl.pathname === "/") {
return authRes;
}
const session = await auth0.getSession(request);
if (!session) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
return authRes;
}
This leaves / and every /auth path public. Any other matched path redirects to login when getSession(request) is null. On Next.js 15, the function name is middleware and the file is middleware.ts. The body is the same.
The Auth0 docs also ask you to keep a check next to the data you are protecting. The proxy redirect above is an early redirect. The page and the route handler still call getSession() themselves.
Read the user in a client component
useUser() reads the user in a client component. It is a SWR hook. It revalidates when the component mounts, when the tab is focused, and when the network reconnects. It does not poll on a timer. isLoading is true while that first read is in flight. user is empty when nobody is logged in.
"use client";
import { useUser } from "@auth0/nextjs-auth0/client";
export function Profile() {
const { user, error, isLoading } = useUser();
if (isLoading) {
return <p>Loading</p>;
}
if (error) {
return <p>{error.message}</p>;
}
if (!user) {
return <a href="/auth/login">Log in</a>;
}
return (
<p>
{user.name} ({user.email})
</p>
);
}
Auth0Provider is optional. Wrap the tree when you already loaded the session on the server and you want useUser() to start from that user:
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 lang="en">
<body>
<Auth0Provider user={session?.user}>{children}</Auth0Provider>
</body>
</html>
);
}
v3 required UserProvider around the app. v4 renamed it to Auth0Provider and only needs it for that initial user.
What the session cookie holds
The default session is a stateless encrypted cookie named __session. There is no server-side session row unless you pass a custom sessionStore. httpOnly is always true, and the SDK does not let you turn it off. SameSite defaults to Lax. Secure defaults to false, then becomes true when APP_BASE_URL is https, or when you omit APP_BASE_URL in production.
Rolling sessions are on by default. Each matched request extends the session by inactivityDuration, until absoluteDuration. The defaults are one day of inactivity and three days absolute, both counted in seconds. You can set them on the client:
export const auth0 = new Auth0Client({
session: {
rolling: true,
absoluteDuration: 60 * 60 * 24 * 3,
inactivityDuration: 60 * 60 * 24,
},
});
v4 stores a short list of ID token claims on session.user:
sub
name
nickname
given_name
family_name
picture
email
email_verified
org_id
Anything else on the ID token is dropped when the cookie is saved, which is how v4 avoids the oversized cookies v3 built. beforeSessionSaved runs just before that save. The session.user it receives still has every ID token claim. The object you return is what gets stored.
import {
Auth0Client,
filterDefaultIdTokenClaims,
} from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client({
async beforeSessionSaved(session) {
return {
...session,
user: {
...filterDefaultIdTokenClaims(session.user),
"https://my-app.example.com/roles":
session.user["https://my-app.example.com/roles"],
},
};
},
});
filterDefaultIdTokenClaims keeps the default list. The extra line copies one custom claim into the cookie. Returning session unchanged keeps every claim, and the cookie grows with them.
onCallback runs when Auth0 redirects back to /auth/callback, including when that exchange fails. It must return a NextResponse. On success, session is the session about to be saved and context.returnTo is the path to open. On failure, error is set and session is null.
import { NextResponse } from "next/server";
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client({
async onCallback(error, context, session) {
const appBaseUrl = context.appBaseUrl ?? process.env.APP_BASE_URL;
if (error) {
return NextResponse.redirect(
new URL(`/error?error=${error.message}`, appBaseUrl)
);
}
return NextResponse.redirect(
new URL(context.returnTo || "/", appBaseUrl)
);
},
});
The redirect you return is the response the browser follows. If this hook is set, it replaces the SDK’s default redirect.
Roles
Roles are created in the Auth0 dashboard and assigned to users. They do not appear on session.user until an Action copies them onto the ID token and beforeSessionSaved keeps that claim.
For an API, open Applications, then APIs, then the API. Enable RBAC. Enable Add Permissions in the Access Token if the access token should carry a permissions claim. With RBAC on, the access token’s scope is the overlap of what the app requested and what that user was granted. The permissions claim is the full set assigned to the user, and it is only added when that second toggle is on.
A Login / Post Login Action can copy roles onto the tokens. Auth0 ignores a custom claim named roles. The name has to be a namespace you control. An auth0.com, webtask.io, or webtask.run host is rejected, and the login still succeeds without the claim.
exports.onExecutePostLogin = async (event, api) => {
const namespace = "https://my-app.example.com";
if (event.authorization) {
api.idToken.setCustomClaim(
`${namespace}/roles`,
event.authorization.roles
);
api.accessToken.setCustomClaim(
`${namespace}/roles`,
event.authorization.roles
);
}
};
After the claim is on the ID token, the beforeSessionSaved hook above copies https://my-app.example.com/roles into the cookie. A Server Component can then read session.user["https://my-app.example.com/roles"]. The access token’s copy is for the API, not for the session cookie.
DPoP
DPoP (Demonstrating Proof-of-Possession) binds an access token to an ES256 key pair. The SDK can attach a proof when it asks Auth0 for a token and when it calls an API. A resource server that requires DPoP rejects the token if the caller cannot prove it holds the private key. useDPoP defaults to false.
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client({
useDPoP: true,
});
With useDPoP: true, the SDK loads PEM keys from AUTH0_DPOP_PUBLIC_KEY and AUTH0_DPOP_PRIVATE_KEY. generateDpopKeyPair() from @auth0/nextjs-auth0/server creates a pair you can export into those variables. If the flag is true and either key is missing, the SDK logs a warning and sends a normal bearer token instead.
A fetcher picks up the client setting. In a route handler:
const fetcher = await auth0.createFetcher(undefined, {
baseUrl: "https://api.example.com",
});
const response = await fetcher.fetchWithAuth("/orders");
fetchWithAuth("/orders") calls https://api.example.com/orders with the access token. When DPoP is on, the fetcher adds a proof for that request. dpopOptions.clockTolerance is how many seconds of clock drift the SDK allows. The default is 30. dpopOptions.clockSkew shifts the time the SDK treats as now. Both can also be set with AUTH0_DPOP_CLOCK_TOLERANCE and AUTH0_DPOP_CLOCK_SKEW.
Other sign-in methods
The same proxy mounts these routes. They finish the login only when the tenant has that connection or feature turned on.
MFA uses /auth/mfa/authenticators, /auth/mfa/associate, /auth/mfa/challenge, and /auth/mfa/verify. Passwordless email, SMS, and magic-link connections use /auth/passwordless/start and /auth/passwordless/verify. A magic link comes back through /auth/callback. Passkeys use /auth/passkey/register, /auth/passkey/challenge, and /auth/passkey/get-token. The client helper passkey is exported from @auth0/nextjs-auth0/client.
Social connections are the connection query parameter on /auth/login, after the connection exists in the dashboard.
Deploy
Set AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, AUTH0_SECRET, and APP_BASE_URL in the host’s environment. APP_BASE_URL for a known production domain is that origin, with no path on the end. If the app is served from a base path, set NEXT_PUBLIC_BASE_PATH as well. A base path of /dashboard mounts login at /dashboard/auth/login. The SDK does not want that path repeated inside APP_BASE_URL.
For a Vercel or Netlify preview, you can leave APP_BASE_URL unset and register each preview callback in Auth0. The v4 migration guide’s example for a wildcard callback is https://*.vercel.app/auth/callback. Auth0 rejects the login when the inferred host is not on the list.
The Node process on the host has to be Node.js 20 LTS or a newer LTS release, the same requirement as local development. AUTH0_CLIENT_SECRET and AUTH0_SECRET stay in the server environment. A NEXT_PUBLIC_ name would ship the value to the browser.
Moving from v3
v3 used AUTH0_ISSUER_BASE_URL with a scheme, and AUTH0_BASE_URL for the app. v4 uses AUTH0_DOMAIN with no scheme, and APP_BASE_URL. Delete the app/api/auth/[auth0]/route.ts handler. Point every /api/auth/login and /api/auth/logout link at /auth/login and /auth/logout, and add the new callback to Allowed Callback URLs.
The v3 session cookie was named appSession. v4 reads that cookie when __session is missing, writes a v4 session on the next login, and deletes the old cookie. Logout clears both.
There is no @auth0/nextjs-auth0/edge entry point in v4. touchSession is gone. Rolling sessions are the middleware’s job.
When login fails
JWEDecryptionFailed means the cookie was encrypted with a different AUTH0_SECRET, or the secret is not 32 bytes. Generate a new value with openssl rand -hex 32, put all 64 hex characters in .env.local, delete the cookies for that host, and restart the server.
A 404 on /auth/login means the proxy or middleware file is not where Next.js looks. With a src/ directory the file is src/proxy.ts on Next.js 16 and src/middleware.ts on Next.js 15. Restart the dev server after adding it.
A missing custom claim on session.user is the default filter. The claim has to be on the ID token under a namespace you control, and beforeSessionSaved has to copy it into the object it returns.
A call to getAccessToken() inside a Server Component can refresh a token and then lose it, because that render cannot set a cookie. Move the refresh to the proxy or to a route handler if the new token has to be saved.