diff --git a/.version b/.version
index 5a74a2876..b4abc5014 100644
--- a/.version
+++ b/.version
@@ -1 +1 @@
-v4.18.0
+v4.19.0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9dcd00dc2..5292dca5e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Change Log
+## [v4.19.0](https://github.com/auth0/nextjs-auth0/tree/v4.19.0) (2026-04-22)
+[Full Changelog](https://github.com/auth0/nextjs-auth0/compare/v4.18.0...v4.19.0)
+
+**Added**
+- feat: add mfa.stepUpWithPopup() for reactive MFA step-up via Universal Login [\#2524](https://github.com/auth0/nextjs-auth0/pull/2524) ([tusharpandey13](https://github.com/tusharpandey13))
+
+**Fixed**
+- fix: MFA http contract parity fixes [\#2555](https://github.com/auth0/nextjs-auth0/pull/2555) ([tusharpandey13](https://github.com/tusharpandey13))
+- fix: skip MCD session backfill in static mode [\#2618](https://github.com/auth0/nextjs-auth0/pull/2618) ([tusharpandey13](https://github.com/tusharpandey13))
+
## [v4.18.0](https://github.com/auth0/nextjs-auth0/tree/v4.18.0) (2026-04-17)
[Full Changelog](https://github.com/auth0/nextjs-auth0/compare/v4.17.1...v4.18.0)
diff --git a/docs/assets/hierarchy.js b/docs/assets/hierarchy.js
index 8329097cd..8946d20f1 100644
--- a/docs/assets/hierarchy.js
+++ b/docs/assets/hierarchy.js
@@ -1 +1 @@
-window.hierarchyData = "eJyll0tP4zAURv+L1xdI7CZ2uuM5QhoeoiNmgViY1KUWqd2xHTQM4r+PQgtym1S5gUVVqfXnc+wk9zqvxFkbPBnf8ZwBpTkwkdwDcWpWqTJoazwZvxJK8+bLyIUiYzJR3mtrjq2Z6cfayWYYAfKkzZSMaZYDqV1FxkSboNxMlsofhJel8vtdwf15WFQESFlJ78mYBD/da2ba+0w3f851NXXKkPEdZeL+DQhlom00Cdapq+VKe4BQnEP4vAFhIonwt8rp2cvFTK7nOJJeofhdwaEbwgQFJjJgorh/N6NdZr91mF+F5ZDN2ZHFblC2U8M+fF3jM4vVKHZp3KjSPiv3cmyng+6ZvklwYjljkdjFTN6oP7V2anrqnHWfIikVHyLv8yl/4JV7Vm5/O7ITu/qhQWZbyF/2SZnTv8uB2FYMg+Yd6HPzLCs9GB3H+tGcxoXixC6kNjfK26purhaW3ZlDwFnWgt828nI4fCuHgI/iGnXufa3ccHhnDgPvqM+rhVxov5ChnGMNdocRGnl8z0+mT71Q1Qzw+x9DexAblThnDPKs+XDgVABnGfBRAnwkgOcCOM+BixS4yIEXKfAiB5FkINIERFqAoCMQVIBgOYiRAJEnIDgDITIoUgpFkUCaJMn9+8Li/b06rMOcYtcWjUbsII9b/4n2q4KHZW0GEDiRxpVCe6/N4yTIoLDEVgYDjde4ri+DoK0MAlqkbejG0WggvJ3FSMQrb+4L6/S/QfR2qB8rkmwXtumkP5w0oeluyocvaXROgtBKk16t7/mgReJjy5Esn8q5NEZVP+2jrdEO3UEEno668c2ilAm6fF/VpQ2Term0LiDOD22lnskwmgKj+W01rA7beJbKUnm/Oithb5mtCAK50WWj/Jl1x9aY1SvcF/jtPEImj5+e49oHu1ifFZttfUQX011RhAKP2/3Jtb1G96mPsQjIxqvNxcthWdrahMOlRreo7Uw/tEjj17r1tVnPgt7XdgoBLpLNo/ulPXyWupIPlTqTZbDOo5e9M9yv0Zx72u1yYI/oSPWR397+A0YH0wk="
\ No newline at end of file
+window.hierarchyData = "eJyll01P4zAQhv9LzoZtPprE3KDACmmBiiL2sOJgUre1mtpZ20GwiP++47Ygt0mVCRwcR41fP+84zoz7FmilrAlO/uRxQqJkSJIoeySB5rOSF1YoCc/eAnjgOslWPDgJJtwYeDJScibmtWZuWECCpZDT4CQapiSodQnjhLRcz1jBzQ/7WnFz3CY8XthVCeqiZAZYgTXTIzfT0afaPVyIcqq5BJ/RMHt8JwF0TUcTqzS/rTa2exjydQg/gIdV8vAPXIvZ6/WMbec4Y4aj+G3CvguSRJQkcQQtfVw7o23Ofgu7uLVVn8U5oEUuUBwdtKGevm7jU4u1kR6ycccL9cz160hNe+2ZrklwxrJB4hmD2e7431poPr3QWulPI2GUfxhZzwcuDNdAPN6XHMRufnDIaA95r5ZcXrxUPbENGQadt6Cv5DMrRW+0L0Ogqf89nKsVE/KOG1XW7m1h2a26bng+SBvwB2ee9Yfv6RDwMPTgV8bUXPeHt+owcNrMz5tAroVZMVsssA4OixE2Yn/PT6bLTih3A6AybId2IHYyMXzTBD4yaDmBbUfg7RN4CdDgPoaWZCQfRtCgT6FPoc9gTA5j6ADaEBoldJARChoah4QmCaGQjWgek3CQhnDJ3CVP4ULdHYW7cBC6y7oAAMkL+fa0tosIG7U3GrG2iV8Dz4XZpEIsa1eAwA39igL7wAg5n1hmOZbY0GCgfozbzNML2tAgoGnUhO4cmnrCm1qMCT9yty+UFv960ZsiBDZLD2Fdjf2pmbSu7nFjv2SjdRKErTzstPU9P1gjdOAZOWPFslgwKXn5S81VjfbQLsTgh+14FxSXVhTrqG6UndRVpbRFnCyaljomw9ikGJvftoa0Awnd3z0FHCbN5hSF3TJ7EgRyp/56+kulIR3IzZ+7L/CbeoSZ2P96RrWxarU9RbplnaOT6SEpwkLiHwTOx2qMrlMfYxGQoZ+8rl9h2VQt7Wkl0CVqX4OA5rG/uJt3s50Fva5NVTfYHUd2T/U36vSZiZI9lfySFfCn2qDjPijG+MjCZr3sWSRaVBhy7r/wsarq6qxUxRKf9RoaDJWG+9QRkwUvy57cXRWK3Ij3Xqx4j8LT0CCocLrdp17JsVZzDUmpF3hPhmL7EV+88KLelG34M/+CjrpV10V/f/8PDT2nww=="
\ No newline at end of file
diff --git a/docs/assets/icons.js b/docs/assets/icons.js
index 3ae8f55e5..58882d76d 100644
--- a/docs/assets/icons.js
+++ b/docs/assets/icons.js
@@ -3,7 +3,7 @@
function addIcons() {
if (document.readyState === "loading") return document.addEventListener("DOMContentLoaded", addIcons);
const svg = document.body.appendChild(document.createElementNS("http://www.w3.org/2000/svg", "svg"));
- svg.innerHTML = `
Optionalcause: OAuth2ErrorOptionalcause: OAuth2ErrorOptionalmessage: stringOptionalmessage: stringError thrown when backchannel logout processing fails.
-Error thrown when backchannel logout processing fails.
+Optionalmessage: stringOptionalmessage: stringError class representing a connect account error.
-Error class representing a connect account error.
+Error class representing a Custom Token Exchange error. +
Error class representing a Custom Token Exchange error.
Extends the SdkError class.
This error is thrown when a Custom Token Exchange operation fails, such as validation errors or server-side token exchange failures.
Constructs a new CustomTokenExchangeError instance.
The error code.
The error message.
Optionalcause: OAuth2ErrorThe OAuth2 cause of the error.
-OptionalcauseThe underlying OAuth2 error that caused this error (if applicable).
+The error code associated with the custom token exchange error.
+Represents an error that occurred during DPoP (Demonstrating Proof-of-Possession) operations.
+Represents an error that occurred during DPoP (Demonstrating Proof-of-Possession) operations.
DPoP is an OAuth 2.0 extension that provides application-level proof-of-possession security by binding access tokens to cryptographic key pairs. This error is thrown when DPoP-related operations fail, such as key pair operations, proof generation, or configuration issues.
@@ -16,7 +16,7 @@Constructs a new DPoPError instance.
OptionalcauseThe underlying error that caused this DPoP error (optional)
+The specific DPoP error code indicating the type of failure
+Optionalmessage: stringOptionalmessage: stringThrown when mfa.challengeWithPopup is called outside of a browser context +(e.g., in a Server Component, Route Handler, or middleware).
+challengeWithPopup() requires window and can only run in client components.
Optionalmessage: stringOptionalmessage: stringOptionalmessage: stringThrown when request validation fails (missing/invalid params). +
Thrown when request validation fails (missing/invalid params). Mapped to 400 Bad Request.
-Optionalmessage: stringOptionalmessage: stringError thrown when initiating an MFA challenge fails.
+Error thrown when initiating an MFA challenge fails.
Optionalcause: MfaApiErrorResponseOptionalcause: MfaApiErrorResponseError thrown when MFA enrollment fails.
+Error thrown when MFA enrollment fails.
Optionalcause: MfaApiErrorResponseOptionalcause: MfaApiErrorResponseError thrown when listing MFA authenticators fails.
+Error thrown when listing MFA authenticators fails.
Optionalcause: MfaApiErrorResponseOptionalcause: MfaApiErrorResponseError thrown when no MFA factors are available for challenge. +
Error thrown when no MFA factors are available for challenge. SDK-generated error (no Auth0 API equivalent).
-Error thrown when MFA verification fails.
+Error thrown when MFA verification fails.
Optionalcause: MfaApiErrorResponseOptionalcause: MfaApiErrorResponseOptionalmessage: stringOptionalmessage: stringError class representing a connect account request error.
-Error class representing a connect account request error.
+OptionalvalidationA human-readable description of the specific error. Required.
+OptionalvalidationA human-readable description of the specific error. Required.
Optionalfield?: stringThe name of the invalid parameter. Optional.
Optionalpointer?: stringA JSON Pointer that points to the exact location of the error in a JSON document being validated. Optional.
Optionalsource?: stringSpecifies the source of the error (e.g., body, query, or header in an HTML message). Optional.
-Errors that come from Auth0 in the redirect_uri callback may contain reflected user input via the OpenID Connect error and error_description query parameter.
+
Errors that come from Auth0 in the redirect_uri callback may contain reflected user input via the OpenID Connect error and error_description query parameter.
You should not render the error message, or error and error_description properties without properly escaping them first.
Thrown when the browser blocks the popup window opened by mfa.challengeWithPopup.
+Most browsers block popups unless they are triggered by a direct user action +(e.g., a click handler). Prompt the user to allow popups for your site.
+Optionalmessage: stringThrown when the user closes the popup window before completing MFA.
+The SDK polls popup.closed every 500ms to detect manual closure.
+This is a user-initiated cancellation, not an error condition.
Optionalmessage: stringThrown when mfa.challengeWithPopup is called while another popup is already active.
+Only one popup flow is allowed at a time, regardless of audience. Wait for the +current popup to complete or be cancelled before starting another.
+Optionalmessage: stringThrown when the popup does not complete authentication within the configured timeout.
+Default timeout is 60 seconds. Configure per-call via
+ChallengeWithPopupOptions.timeout.
Optionalmessage: stringAbstractAbstractOptionalmessage: stringOptionalmessage: stringAbstractAbstractProtectedrollingOptionalstoreisRolling returns true if rolling sessions are enabled.
-calculateMaxAge calculates the max age of the session based on createdAt and the rolling and absolute durations.
-Abstractdeleteepoch returns the time since unix epoch in seconds.
-AbstractgetAbstractsetsave adds the encrypted session cookie as a Set-Cookie header. If the iat property
+
ProtectedrollingOptionalstoreisRolling returns true if rolling sessions are enabled.
+calculateMaxAge calculates the max age of the session based on createdAt and the rolling and absolute durations.
+Abstractdeleteepoch returns the time since unix epoch in seconds.
+AbstractgetAbstractsetsave adds the encrypted session cookie as a Set-Cookie header. If the iat property
is present on the session, then it will be used to compute the maxAge cookie value.
OptionalisNew: booleanOptionalisNew: booleanMFA API for server-side operations.
Provides access to MFA methods that require encrypted mfa_token from MfaRequiredError:
try {
const { token } = await auth0.getAccessToken({ audience: 'https://api.example.com' });
} catch (error) {
if (error instanceof MfaRequiredError) {
// Get available authenticators
const authenticators = await auth0.mfa.getAuthenticators({
mfaToken: error.mfa_token
});
// Initiate challenge
const challenge = await auth0.mfa.challenge({
mfaToken: error.mfa_token,
challengeType: 'otp',
authenticatorId: authenticators[0].id
});
// Verify code
const tokens = await auth0.mfa.verify({
mfaToken: error.mfa_token,
otp: '123456'
});
}
}
-Initiates the Connect Account flow to connect a third-party account to the user's profile.
If the user does not have an active session, a ConnectAccountError is thrown.
This method first attempts to obtain an access token with the create:me:connected_accounts scope
for the My Account API to create a connected account for the user.
The user will then be redirected to authorize the connection with the third-party provider.
You must enable Offline Access from the Connection Permissions settings to be able to use the connection with Connected Accounts.
Creates a configured Fetcher instance for making authenticated API requests.
+Creates a configured Fetcher instance for making authenticated API requests.
This method creates a specialized HTTP client that handles:
Exchanges an external token for Auth0 tokens using Custom Token Exchange (RFC 8693).
+Exchanges an external token for Auth0 tokens using Custom Token Exchange (RFC 8693).
This is a server-only method that does NOT modify the session. The returned tokens can be used independently or stored by the developer.
Note: CTE tokens are not cached. The caller is responsible for token storage if needed.
@@ -67,11 +67,15 @@Optionaloptions: GetAccessTokenOptionsOptional configuration for getting the access token.
+Optionaloptions: GetAccessTokenOptionsOptional configuration for getting the access token.
Optionalaudience?: string | nullPlease note: If you are passing audience, ensure that the used audiences and scopes are part of the Application's Refresh Token Policies in Auth0 when configuring Multi-Resource Refresh Tokens (MRRT). Auth0 Documentation on Multi-resource Refresh Tokens
-Optionalrefresh?: boolean | nullOptionalscope?: string | nullgetAccessToken returns the access token.
+OptionalmergeScopes?: booleanControl scope merging behavior. +When true (default): merge global scopes for default audience. +When false: use ONLY requested scope (no global merge). +Used by challengeWithPopup() to prevent global scope pollution.
+Optionalrefresh?: boolean | nullOptionalscope?: string | nullgetAccessToken returns the access token.
This method can be used in middleware and getServerSideProps, API routes in the Pages Router.
The request object.
The response object.
@@ -79,23 +83,27 @@Optionalaudience?: string | nullPlease note: If you are passing audience, ensure that the used audiences and scopes are part of the Application's Refresh Token Policies in Auth0 when configuring Multi-Resource Refresh Tokens (MRRT). Auth0 Documentation on Multi-resource Refresh Tokens
-Optionalrefresh?: boolean | nullOptionalscope?: string | nullRetrieves an access token for a connection.
+OptionalmergeScopes?: booleanControl scope merging behavior. +When true (default): merge global scopes for default audience. +When false: use ONLY requested scope (no global merge). +Used by challengeWithPopup() to prevent global scope pollution.
+Optionalrefresh?: boolean | nullOptionalscope?: string | nullRetrieves an access token for a connection.
This method can be used in Server Components, Server Actions, and Route Handlers in the App Router.
NOTE: Server Components cannot set cookies. Calling getAccessTokenForConnection() in a Server Component will cause the access token to be refreshed, if it is expired, and the updated token set will not to be persisted.
It is recommended to call getAccessTokenForConnection(req, res) in the middleware if you need to retrieve the access token in a Server Component to ensure the updated token set is persisted.
Retrieves an access token for a connection.
+Retrieves an access token for a connection.
This method can be used in middleware and getServerSideProps, API routes in the Pages Router.
getSession returns the session data for the current request.
+getSession returns the session data for the current request.
This method can be used in Server Components, Server Actions, and Route Handlers in the App Router.
-getSession returns the session data for the current request.
+getSession returns the session data for the current request.
This method can be used in middleware and getServerSideProps, API routes in the Pages Router.
Authenticates using Client-Initiated Backchannel Authentication and returns the token set and optionally the ID token claims and authorization details.
+Authenticates using Client-Initiated Backchannel Authentication and returns the token set and optionally the ID token claims and authorization details.
This method will initialize the backchannel authentication process with Auth0, and poll the token endpoint until the authentication is complete.
Using Client-Initiated Backchannel Authentication requires the feature to be enabled in the Auth0 dashboard.
middleware mounts the SDK routes to run as a middleware function.
-updateSession updates the session of the currently authenticated user. If the user does not have a session, an error is thrown.
+middleware mounts the SDK routes to run as a middleware function.
+updateSession updates the session of the currently authenticated user. If the user does not have a session, an error is thrown.
This method can be used in middleware and getServerSideProps, API routes, and middleware in the Pages Router.
updateSession updates the session of the currently authenticated user. If the user does not have a session, an error is thrown.
+updateSession updates the session of the currently authenticated user. If the user does not have a session, an error is thrown.
This method can be used in Server Actions and Route Handlers in the App Router.
-Optionalopts: WithPageAuthRequiredAppRouterOptions<P>Optionalopts: WithPageAuthRequiredAppRouterOptions<P>Error thrown when domain resolution fails during MCD initialization or request handling.
+Error thrown when domain resolution fails during MCD initialization or request handling.
This error is public and may be caught by application code.
-Creates a new DomainResolutionError instance.
Optionalmessage: stringA descriptive error message
Optionalcause: ErrorThe underlying error that caused the resolution failure (optional)
-Error thrown when a domain hostname fails validation.
+Error thrown when a domain hostname fails validation.
This includes rejection of IP addresses, localhost, .local domains, paths, and ports. This error is public and may be caught by application code.
-Creates a new DomainValidationError instance.
Optionalmessage: stringA descriptive error message
-Error thrown when the issuer URL is invalid or cannot be resolved.
+Error thrown when the issuer URL is invalid or cannot be resolved.
This error is public and may be caught by application code.
-Creates a new IssuerValidationError instance.
The expected issuer URL
The actual issuer URL from the token
-Thrown when getAccessToken requires MFA step-up authentication.
+Thrown when getAccessToken requires MFA step-up authentication.
This error is thrown during token refresh when Auth0 returns mfa_required.
The mfa_token property contains an encrypted token that can be used
with Auth0's MFA API to complete the authentication challenge.
Optional ReadonlycauseReadonlycodeReadonlyerrorOriginal Auth0 error code
-Readonlyerror_Original Auth0 error description
-Optional Readonlymfa_MFA requirements indicating available challenge/enrollment methods
-Readonlymfa_Encrypted MFA token to pass to MFA API methods.
-Serialize error for HTTP responses. +
Optional ReadonlycauseReadonlycodeReadonlyerrorOriginal Auth0 error code
+Readonlyerror_Original Auth0 error description
+Optional Readonlymfa_MFA requirements indicating available challenge/enrollment methods
+Readonlymfa_Encrypted MFA token to pass to MFA API methods.
+Serialize error for HTTP responses. Called automatically by Response.json() and JSON.stringify(). Ensures both SDK and HTTP API consumers get identical shape.
-Thrown when MFA API methods are called but no context exists in session +
Thrown when MFA API methods are called but no context exists in session for the provided encrypted mfa_token.
This typically occurs when:
Thrown when the encrypted mfa_token is invalid.
+Thrown when the encrypted mfa_token is invalid.
This occurs when:
Error thrown when a session's domain does not match the current request domain.
+Error thrown when a session's domain does not match the current request domain.
This indicates a potential security issue where a user is attempting to use a session created for a different domain.
-Creates a new SessionDomainMismatchError instance.
Optionalmessage: stringA descriptive error message
-TransactionStore is responsible for storing the state required to successfully complete +
TransactionStore is responsible for storing the state required to successfully complete an authentication transaction. The store relies on encrypted, stateless cookies to store the transaction state.
-Deletes all transaction cookies based on the configured prefix.
-Returns the configured prefix for transaction cookies.
-Saves the transaction state to an encrypted cookie.
+Deletes all transaction cookies based on the configured prefix.
+Returns the configured prefix for transaction cookies.
+Saves the transaction state to an encrypted cookie.
The response cookies object to set the transaction cookie on
The transaction state to save
OptionalreqCookies: RequestCookiesOptional request cookies to check for existing transactions. @@ -17,4 +17,4 @@ will check for existing transaction cookies. When omitted, the existence check is skipped for performance optimization.
Enum representing error codes related to access tokens for connections.
-Enum representing error codes related to access tokens for connections.
+Failed to exchange the refresh token.
-The refresh token is missing.
-The session is missing.
-The refresh token is missing.
+The session is missing.
+Enum representing error codes related to the connect account flow.
-Enum representing error codes related to the connect account flow.
+Failed to complete the connect account flow.
-Failed to initiate the connect account flow.
-The session is missing.
-Failed to initiate the connect account flow.
+The session is missing.
+Error codes for Custom Token Exchange errors.
-Error codes for Custom Token Exchange errors.
+The token exchange request failed.
-The subject_token_type is not a valid URI, wrong length, or uses a reserved namespace.
-The actor_token was provided without actor_token_type.
-The subject_token is missing or empty.
-The subject_token_type is not a valid URI, wrong length, or uses a reserved namespace.
+The actor_token was provided without actor_token_type.
+The subject_token is missing or empty.
+Error codes for DPoP-related errors.
+Error codes for DPoP-related errors.
These error codes categorize different types of failures that can occur during DPoP (Demonstrating Proof-of-Possession) operations.
-DPoP configuration is invalid or incomplete. This occurs when the provided DPoP configuration contains invalid values or missing required components.
-Failed to calculate dpop_jkt (JWK thumbprint) parameter. +
Failed to calculate dpop_jkt (JWK thumbprint) parameter. This occurs when the SDK cannot generate the required thumbprint from the provided public key for the authorization request.
-Failed to export DPoP public key to JWK format. +
Failed to export DPoP public key to JWK format. This occurs when the SDK cannot convert the CryptoKey to the JSON Web Key format required for DPoP proofs.
-Connect Account flow.
+Indicates that the token is an OAuth 2.0 access token issued by the given authorization server.
Indicates that the token is an OAuth 2.0 refresh token issued by the given authorization server.
+Indicates that the token is an OAuth 2.0 refresh token issued by the given authorization server.
Fetches an access token for the currently logged-in user.
+Fetches an access token for the currently logged-in user.
Options for fetching the access token, including optional audience and scope.
-The access token as a string, or the full token response when includeFullResponse is true.
The access token as a string, or the full token response when includeFullResponse is true.
Fetches an access token for the currently logged-in user.
+Fetches an access token for the currently logged-in user.
Optionaloptions: AccessTokenOptions & { includeFullResponse?: false }Options for fetching the access token, including optional audience and scope.
The access token as a string, or the full token response when includeFullResponse is true.
Filters the claims to only include those that are considered default.
+Filters the claims to only include those that are considered default.
The claims to filter.
The filtered claims containing only default ID token claims.
-Generates a new ES256 key pair for DPoP (Demonstrating Proof-of-Possession) operations.
+Generates a new ES256 key pair for DPoP (Demonstrating Proof-of-Possession) operations.
This function creates a cryptographically secure ES256 key pair suitable for DPoP proof generation. The generated keys use the P-256 elliptic curve with SHA-256 hashing, which is the required algorithm for DPoP as specified in RFC 9449.
@@ -7,4 +7,4 @@

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
+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:
+2. Add the environment variables
Add the following environment variables to your .env.local file:
AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=
@@ -42,8 +38,7 @@ 2. Add the envi
When 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.
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):
@@ -57,8 +52,7 @@
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.
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.
+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();
@@ -66,19 +60,16 @@ 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.
+
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:
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).*)"
]
};
If you're using a src/ directory, the middleware.ts file must be created inside the src/ directory.
Next.js 16 introduces a new convention called proxy.ts, replacing middleware.ts. +
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):
@@ -101,8 +92,7 @@
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:
+You can customize the client by using the options below:
| cspNonce | +string |
+CSP nonce for inline scripts in popup callback HTML responses. When provided, <script> tags in the MFA popup callback include a nonce="..." attribute for strict Content Security Policy compliance. Only required when using mfa.challengeWithPopup() with a CSP that blocks inline scripts. |
+
| discoveryCache | DiscoveryCacheOptions |
Configure the OIDC discovery metadata cache for Multiple Custom Domains. Controls TTL and maximum cached issuers. |
While the authentication routes are handled automatically by the middleware, you can still customize the authentication flow through two main approaches:
+While the authentication routes are handled automatically by the middleware, you can still customize the authentication flow through two main approaches:
onCallback hook to add custom logic after authentication completesQuick Start: For detailed examples and step-by-step migration patterns from v3, see Customizing Auth Handlers.
-You can specify the following environment variables to configure the session cookie:
+You can specify the following environment variables to configure the session cookie:
AUTH0_COOKIE_DOMAIN=
AUTH0_COOKIE_PATH=
AUTH0_COOKIE_TRANSIENT=
@@ -273,10 +266,8 @@ Session Cookie Con
AUTH0_DPOP_CLOCK_TOLERANCE=
-The Auth0 Next.js SDK supports DPoP (Demonstrating Proof-of-Possession) for enhanced OAuth 2.0 security. DPoP binds access tokens to cryptographic key pairs, preventing token theft and replay attacks.
-Option 1: Environment Variables
+The Auth0 Next.js SDK supports DPoP (Demonstrating Proof-of-Possession) for enhanced OAuth 2.0 security. DPoP binds access tokens to cryptographic key pairs, preventing token theft and replay attacks.
+Option 1: Environment Variables
# Enable DPoP and provide ES256 key pair
AUTH0_DPOP_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
@@ -293,16 +284,14 @@ Quick Startimport { Auth0Client } from "@auth0/nextjs-auth0/server";
import { generateKeyPair } from "oauth4webapi";
const dpopKeyPair = await generateKeyPair("ES256");
export const auth0 = new Auth0Client({
useDPoP: true,
dpopKeyPair,
dpopOptions: {
clockTolerance: 30, // Allow 30s clock difference
retry: {
delay: 100, // 100ms retry delay
jitter: true // Add randomness
}
}
});
-// Create a fetcher - DPoP inherited from global configuration
const fetcher = await auth0.createFetcher(req, {
baseUrl: "https://api.example.com"
// useDPoP is inherited from Auth0Client config
});
// Make authenticated requests with automatic DPoP proof generation
const response = await fetcher.fetchWithAuth("/protected-resource", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data: "example" })
});
+Making DPoP-Protected Requests
// Create a fetcher - DPoP inherited from global configuration
const fetcher = await auth0.createFetcher(req, {
baseUrl: "https://api.example.com"
// useDPoP is inherited from Auth0Client config
});
// Make authenticated requests with automatic DPoP proof generation
const response = await fetcher.fetchWithAuth("/protected-resource", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data: "example" })
});
DPoP Inheritance Behavior
Fetchers created with createFetcher automatically inherit the global DPoP configuration from your Auth0Client instance.
This inheritance pattern follows the same behavior as auth0-spa-js, providing consistent developer experience across Auth0 SDKs.
For complete DPoP documentation, examples, and best practices, see DPoP Examples.
-Advanced: Clock Validation Configuration
-Configure timing validation for DPoP proofs to handle clock differences between client and server:
+Advanced: Clock Validation Configuration
Configure timing validation for DPoP proofs to handle clock differences between client and server:
export const auth0 = new Auth0Client({
useDPoP: true,
dpopKeyPair: await generateKeyPair("ES256"),
dpopOptions: {
clockSkew: 120, // Adjust for local clock being 2 minutes behind
clockTolerance: 45 // Allow 45 seconds tolerance for validation
}
});
@@ -312,36 +301,30 @@ Advance
Respective counterparts are also available in the client configuration. See Cookie Configuration for more details.
-The SDK provides built-in proxy support for Auth0's My Account and My Organization Management APIs, enabling secure browser-initiated requests while maintaining server-side DPoP authentication and token management.
-The proxy handler automatically intercepts requests to /me/* and /my-org/* paths in your Next.js application and forwards them to the respective Auth0 APIs with proper authentication headers. This implements a Backend-for-Frontend (BFF) pattern where:
The SDK provides built-in proxy support for Auth0's My Account and My Organization Management APIs, enabling secure browser-initiated requests while maintaining server-side DPoP authentication and token management.
+The proxy handler automatically intercepts requests to /me/* and /my-org/* paths in your Next.js application and forwards them to the respective Auth0 APIs with proper authentication headers. This implements a Backend-for-Frontend (BFF) pattern where:
Configure audience and scopes for the APIs:
+Configure audience and scopes for the APIs:
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client({
useDPoP: true,
authorizationParameters: {
audience: "urn:your-api-identifier",
scope: {
[`https://${process.env.AUTH0_DOMAIN}/me/`]: "profile:read profile:write",
[`https://${process.env.AUTH0_DOMAIN}/my-org/`]: "org:read org:write"
}
}
});
-Make requests through the proxy paths:
+Make requests through the proxy paths:
// My Account API
const response = await fetch("/me/v1/profile", {
headers: { "scope": "profile:read" }
});
// My Organization API
const response = await fetch("/my-org/organizations", {
headers: { "scope": "org:read" }
});
The scope header specifies the required scope. The SDK retrieves an access token with the appropriate audience and scope, then forwards the request with authentication headers.
For complete documentation, examples, and integration patterns with UI Components, see Proxy Handler for My Account and My Organization APIs.
-Your Next.js application may be configured to use a base path (e.g.: /dashboard) — this is usually done by setting the basePath option in the next.config.js file. To configure the SDK to use the base path, you will also need to set the NEXT_PUBLIC_BASE_PATH environment variable which will be used when mounting the authentication routes.
Your Next.js application may be configured to use a base path (e.g.: /dashboard) — this is usually done by setting the basePath option in the next.config.js file. To configure the SDK to use the base path, you will also need to set the NEXT_PUBLIC_BASE_PATH environment variable which will be used when mounting the authentication routes.
For example, if the NEXT_PUBLIC_BASE_PATH environment variable is set to /dashboard, the SDK will mount the authentication routes on /dashboard/auth/login, /dashboard/auth/callback, /dashboard/auth/profile, etc.
We do not recommend using the NEXT_PUBLIC_BASE_PATH environment variable in conjunction with a APP_BASE_URL that contains a path component. If your application is configured to use a base path, you should set the APP_BASE_URL to the root URL of your application (e.g.: https://example.com) and use the NEXT_PUBLIC_BASE_PATH environment variable to specify the base path (e.g.: /dashboard).
The SDK performs validation of required configuration options when initializing the Auth0Client. The following options are mandatory and must be provided either through constructor options or environment variables:
The SDK performs validation of required configuration options when initializing the Auth0Client. The following options are mandatory and must be provided either through constructor options or environment variables:
domain (or AUTH0_DOMAIN environment variable)clientId (or AUTH0_CLIENT_ID environment variable)If any of these required options are missing, the SDK will issue a warning with a detailed message explaining which options are missing and how to provide them.
appBaseUrl is optional; if omitted, the SDK will infer it from the request host at runtime.
The SDK supports authenticating users against multiple Auth0 custom domains on the same tenant. Pass a DomainResolver function as the domain option to enable per-request domain resolution:
The SDK supports authenticating users against multiple Auth0 custom domains on the same tenant. Pass a DomainResolver function as the domain option to enable per-request domain resolution:
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client({
domain: ({ headers }) => {
const host = headers.get("host") ?? "";
if (host.startsWith("brand1.")) return "auth.brand1.com";
return "auth.default.com";
}
});
For complete documentation, configuration options, and examples, see Multiple Custom Domains in EXAMPLES.md.
-The SDK mounts 6 routes:
+The SDK mounts 6 routes:
/auth/login: the login route that the user will be redirected to to initiate an authentication transaction/auth/logout: the logout route that must be added to your Auth0 application's Allowed Logout URLs
The /auth/access-token route is enabled by default, but is only necessary when the access token is needed on the client-side. If this isn't something you need, you can disable this endpoint by setting enableAccessTokenEndpoint to false.
We appreciate feedback and contribution to this repo! Before you get started, please read the following:
+We appreciate feedback and contribution to this repo! Before you get started, please read the following:
To provide feedback or report a bug, please raise an issue on our issue tracker.
-Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
-+
To provide feedback or report a bug, please raise an issue on our issue tracker.
+Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
+
What is Auth0?
This project is licensed under the MIT license. See the LICENSE file for more info.
-
Options for ClientMfaClient.challengeWithPopup | mfa.challengeWithPopup().
+Controls the popup MFA step-up flow: which API audience to target, +scopes to request, and popup window behavior.
+Optionalacr_ACR values for step-up (optional, default: MFA policy URI)
+Target API audience (required)
+OptionalpopupPopup window height (optional, default: 600)
+OptionalpopupPopup window width (optional, default: 400)
+OptionalpromptOIDC prompt parameter (optional, default: not sent).
When omitted, Auth0 will use the existing session and skip straight to
+the MFA challenge if the user is already authenticated. Set to "login"
+to force full re-authentication (username + password + MFA).
OptionalreturnReturn URL after authentication (optional, default: '/')
+OptionalscopeSpace-separated scopes (optional — inherits global config when omitted)
+OptionaltimeoutTimeout in milliseconds (optional, default: 60000)
+Options to customize the withPageAuthRequired higher order component.
-Options to customize the withPageAuthRequired higher order component.
+OptionalonwithPageAuthRequired(Profile, {
onError: error => <div>Error: {error.message}</div>
});
Render a fallback in case of error fetching the user from the profile API route.
-OptionalonwithPageAuthRequired(Profile, {
onRedirecting: () => <div>Redirecting...</div>
});
+OptionalonwithPageAuthRequired(Profile, {
onRedirecting: () => <div>Redirecting...</div>
});
Render a message to show that the user is being redirected.
-OptionalreturnwithPageAuthRequired(Profile, {
returnTo: '/profile'
});
+OptionalreturnwithPageAuthRequired(Profile, {
returnTo: '/profile'
});
Add a path to return the user to after login.
-Interface for Auth0 MFA API error responses. +
Interface for Auth0 MFA API error responses. All MFA errors from Auth0 follow this shape (snake_case).
-MFA requirements from an mfa_required error response. +
MFA requirements from an mfa_required error response. Indicates which MFA methods are available for the user. Matches Auth0 API response shape and auth0-spa-js type.
-OptionalenrollRequired enrollment types (user needs to enroll new authenticator)
+Options for retrieving a connection access token.
-Options for retrieving a connection access token.
+The connection name for while you want to retrieve the access token.
-Optionallogin_An optional login hint to pass to the authorization server.
-Optionalsubject_The type of token that is being exchanged.
+Optionallogin_An optional login hint to pass to the authorization server.
+Optionalsubject_The type of token that is being exchanged.
Uses the SUBJECT_TOKEN_TYPES enum with the following allowed values:
SUBJECT_TYPE_REFRESH_TOKEN: "urn:ietf:params:oauth:token-type:refresh_token"SUBJECT_TYPE_ACCESS_TOKEN: "urn:ietf:params:oauth:token-type:access_token"Defaults to SUBJECT_TYPE_REFRESH_TOKEN.
OptionalallowAllow insecure requests to be made to the authorization server. This can be useful when testing
with a mock OIDC provider that does not support TLS, locally.
This option can only be used when NODE_ENV is not set to production.
OptionalappThe URL of your application (e.g.: http://localhost:3000).
OptionalappThe URL of your application (e.g.: http://localhost:3000).
Can be a single URL string, or an array of allowed base URLs. When an array is provided, the SDK validates the incoming request origin against the list and uses the matching entry (allow-list mode). This is useful for multi-domain or preview @@ -40,27 +41,34 @@
If it's not specified, it will be loaded from the APP_BASE_URL environment variable.
Multiple origins can be provided as a comma-separated string (e.g. https://app.example.com,https://myapp.vercel.app).
If neither is provided, the SDK will infer it from the request host at runtime.
OptionalauthorizationAdditional parameters to send to the /authorize endpoint.
OptionalbeforeA method to manipulate the session before persisting it.
+OptionalauthorizationAdditional parameters to send to the /authorize endpoint.
OptionalbeforeA method to manipulate the session before persisting it.
See beforeSessionSaved for additional details
-OptionalclientThe algorithm used to sign the client assertion JWT. +
OptionalclientThe algorithm used to sign the client assertion JWT.
Uses one of token_endpoint_auth_signing_alg_values_supported if not specified.
If the Authorization Server discovery document does not list token_endpoint_auth_signing_alg_values_supported
this property will be required.
OptionalclientPrivate key for use with private_key_jwt clients.
+
OptionalclientPrivate key for use with private_key_jwt clients.
This should be a string that is the contents of a PEM file or a CryptoKey.
OptionalclientThe Auth0 client ID.
+OptionalclientThe Auth0 client ID.
If it's not specified, it will be loaded from the AUTH0_CLIENT_ID environment variable.
OptionalclientThe Auth0 client secret.
+OptionalclientThe Auth0 client secret.
If it's not specified, it will be loaded from the AUTH0_CLIENT_SECRET environment variable.
OptionaldiscoveryConfiguration for the OIDC discovery metadata cache. +
OptionalcspContent Security Policy nonce for inline scripts in popup flows.
+Required when your application uses CSP and the popup-based step-up
+authentication flow (challengeMode: 'popup'). The nonce is
+injected into the inline <script> tag of the postMessage HTML response.
OptionaldiscoveryConfiguration for the OIDC discovery metadata cache. Controls TTL and maximum cached issuers for MCD resolver mode. Also applies in static mode (single cached entry).
OptionaldomainThe Auth0 domain for the tenant.
+OptionaldomainThe Auth0 domain for the tenant.
string: Static domain (e.g., "example.us.auth0.com"). Existing behavior preserved.DomainResolver: Async function resolving domain per-request from headers.
@@ -71,7 +79,7 @@
OptionaldpopES256 key pair for DPoP proof generation.
+OptionaldpopES256 key pair for DPoP proof generation.
If not provided when useDPoP is true, the SDK will attempt to load keys from
environment variables AUTH0_DPOP_PUBLIC_KEY and AUTH0_DPOP_PRIVATE_KEY.
Keys must be in PEM format and use the P-256 elliptic curve.
OptionaldpopConfiguration options for DPoP timing validation and retry behavior.
+OptionaldpopConfiguration options for DPoP timing validation and retry behavior.
These options control how the SDK validates DPoP proof timing and handles nonce errors. Proper configuration is important for both security and reliability.
const auth0 = new Auth0Client({
useDPoP: true,
dpopOptions: {
clockTolerance: 60, // Allow 60 seconds clock difference
clockSkew: 0, // No clock adjustment needed
retry: {
delay: 200, // 200ms delay before retry
jitter: true // Add randomness to prevent thundering herd
}
}
});
@@ -95,17 +103,17 @@
OptionalenableBoolean value to enable the /auth/access-token endpoint for use in the client app.
OptionalenableBoolean value to enable the /auth/access-token endpoint for use in the client app.
Defaults to true.
NOTE: Set this to false if your client does not need to directly interact with resource servers (Token Mediating Backend). This will be false for most apps.
A security best practice is to disable this to avoid exposing access tokens to the client app.
-OptionalenableIf true, the /auth/connect endpoint will be mounted to enable users to connect additional accounts.
OptionalenableOptionalenableBoolean value to opt-out of sending the library name and version to your authorization server +
OptionalenableIf true, the /auth/connect endpoint will be mounted to enable users to connect additional accounts.
OptionalenableOptionalenableBoolean value to opt-out of sending the library name and version to your authorization server
via the Auth0-Client header. Defaults to true.
OptionalhttpInteger value for the HTTP timeout in milliseconds for authentication requests. +
OptionalhttpInteger value for the HTTP timeout in milliseconds for authentication requests.
Defaults to 5000 ms.
OptionalincludeConfigure whether to include id_token_hint in OIDC logout URLs.
+OptionalincludeConfigure whether to include id_token_hint in OIDC logout URLs.
Recommended (default): Set to true to include id_token_hint parameter.
Auth0 recommends using id_token_hint for secure logout as per the
OIDC specification.
OptionallogoutConfigure the logout strategy to use.
+OptionallogoutConfigure the logout strategy to use.
'auto' (default): Attempts OIDC RP-Initiated Logout first, falls back to /v2/logout if not supported'oidc': Always uses OIDC RP-Initiated Logout (requires RP-Initiated Logout to be enabled)'v2': Always uses the Auth0 /v2/logout endpoint (supports wildcards in allowed logout URLs)OptionalmfaMFA context TTL in seconds. Controls how long encrypted mfa_token remains valid. +
OptionalmfaMFA context TTL in seconds. Controls how long encrypted mfa_token remains valid. Default: 300 (5 minutes, matching Auth0's mfa_token expiration)
Can also be set via AUTH0_MFA_TOKEN_TTL environment variable.
-OptionalnoIf true, the profile endpoint will return a 204 No Content response when the user is not authenticated instead of returning a 401 Unauthorized response.
Defaults to false.
OptionalonA method to handle errors or manage redirects after attempting to authenticate.
+OptionalonA method to handle errors or manage redirects after attempting to authenticate.
See onCallback for additional details
-OptionalpushedIf enabled, the SDK will use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server.
-OptionalroutesConfigure the paths for the authentication routes.
+OptionalpushedIf enabled, the SDK will use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server.
+OptionalroutesConfigure the paths for the authentication routes.
See Custom routes for additional details.
-OptionalsecretA 32-byte, hex-encoded secret used for encrypting cookies.
+OptionalsecretA 32-byte, hex-encoded secret used for encrypting cookies.
If it's not specified, it will be loaded from the AUTH0_SECRET environment variable.
OptionalsessionConfigure the session timeouts and whether to use rolling sessions or not.
+OptionalsessionConfigure the session timeouts and whether to use rolling sessions or not.
See Session configuration for additional details.
-OptionalsessionA custom session store implementation used to persist sessions to a data store.
+OptionalsessionA custom session store implementation used to persist sessions to a data store.
See Database sessions for additional details.
-OptionalsignThe path to redirect the user to after successfully authenticating. Defaults to /.
OptionaltokenNumber of seconds to refresh access tokens early when calling getAccessToken.
+
OptionalsignThe path to redirect the user to after successfully authenticating. Defaults to /.
OptionaltokenNumber of seconds to refresh access tokens early when calling getAccessToken.
This is a server-side buffer applied to token expiration checks. For example,
with a buffer of 60 seconds, tokens expiring within the next minute will be
refreshed proactively when a refresh token is available.
Defaults to 0 (no early refresh).
OptionaltransactionConfigure the transaction cookie used to store the state of the authentication transaction.
-OptionaluseEnable DPoP (Demonstrating Proof-of-Possession) for enhanced OAuth 2.0 security.
+OptionaltransactionConfigure the transaction cookie used to store the state of the authentication transaction.
+OptionaluseEnable DPoP (Demonstrating Proof-of-Possession) for enhanced OAuth 2.0 security.
When enabled, the SDK will:
MFA authenticator (enrolled factor). +
MFA authenticator (enrolled factor). Uses camelCase for SDK-facing interface.
Whether authenticator is active
-Authenticator type (primary field mapped from authenticator_type)
-OptionalcreatedISO 8601 timestamp of creation
-Authenticator ID
-OptionallastISO 8601 timestamp of last authentication
-OptionalnameAuthenticator name (user-defined or default)
-OptionaloobOOB channel (sms, voice)
-OptionalphonePhone number for OOB (masked)
-OptionaltypeDirect type value (optional, feature-flagged field from Auth0 API)
-Authenticator type (primary field mapped from authenticator_type)
+OptionalcreatedISO 8601 timestamp of creation
+Authenticator ID
+OptionallastISO 8601 timestamp of last authentication
+OptionalnameAuthenticator name (user-defined or default)
+OptionaloobOOB channel (sms, voice)
+OptionalphonePhone number for OOB (masked)
+OptionaltypeDirect type value (optional, feature-flagged field from Auth0 API)
+Authenticator response from Auth0 API (snake_case). +Maps to Authenticator in SDK-facing interface.
+Whether authenticator is active
+Authenticator type (primary field)
+Optionalcreated_ISO 8601 timestamp of creation
+Authenticator ID
+Optionallast_ISO 8601 timestamp of last authentication
+OptionalnameAuthenticator name (user-defined or default)
+Optionaloob_OOB channel (sms, voice)
+Optionalphone_Phone number for OOB (masked)
+OptionaltypeDirect type value (optional, feature-flagged field)
+Additional authorization parameters.
-Additional authorization parameters.
+OptionalaudienceThe unique identifier of the target API you want to access.
-Optionalmax_The maximum amount of time, in seconds, after which a user must reauthenticate.
-OptionalorganizationThe unique identifier of the organization that the user should be logged into. +
Optionalmax_The maximum amount of time, in seconds, after which a user must reauthenticate.
+OptionalorganizationThe unique identifier of the organization that the user should be logged into. When specified, the user will be prompted to log in to this specific organization. The organization ID will be included in the user's session after successful authentication.
-Optionalredirect_The URL to which the authorization server will redirect the user after granting authorization.
-OptionalscopeThe scope of the access request, expressed as a list of space-delimited, case-sensitive strings. +
Optionalredirect_The URL to which the authorization server will redirect the user after granting authorization.
+OptionalscopeThe scope of the access request, expressed as a list of space-delimited, case-sensitive strings.
Defaults to "openid profile email offline_access".
OptionalauthorizationOptional authorization details to use Rich Authorization Requests (RAR).
OptionalauthorizationAuthorization Parameters to be sent with the authorization request.
-Human-readable message to be displayed at the consumption device and authentication device. +
OptionalauthorizationAuthorization Parameters to be sent with the authorization request.
+Human-readable message to be displayed at the consumption device and authentication device. This allows the user to ensure the transaction initiated by the consumption device is the same that triggers the action on the authentication device.
-The login hint to inform which user to use.
+The login hint to inform which user to use.
The sub claim of the user that is trying to login using Client-Initiated Backchannel Authentication, and to which a push notification to authorize the login will be sent.
OptionalrequestedSet a custom expiry time for the CIBA flow in seconds. Defaults to 300 seconds (5 minutes) if not set.
-OptionalrequestedSet a custom expiry time for the CIBA flow in seconds. Defaults to 300 seconds (5 minutes) if not set.
+Challenge response from Auth0 API (snake_case). +Maps to ChallengeResponse in SDK-facing interface.
+MFA challenge response. +
MFA challenge response. Uses camelCase for SDK-facing interface.
Challenge type (otp, oob)
+OptionaloobOOB code (for oob challenges)
+Options to initiate a connect account flow using the My Account API.
+Options to initiate a connect account flow using the My Account API.
OptionalauthorizationAuthorization parameters to be passed to the authorization server.
-The name of the connection to link the account with (e.g., 'google-oauth2', 'facebook').
-OptionalreturnThe URL to redirect to after successfully connecting the account.
-OptionalscopesArray of scopes to request from the Identity Provider during the connect account flow.
-The name of the connection to link the account with (e.g., 'google-oauth2', 'facebook').
+OptionalreturnThe URL to redirect to after successfully connecting the account.
+OptionalscopesArray of scopes to request from the Identity Provider during the connect account flow.
+Options for Custom Token Exchange.
+Options for Custom Token Exchange.
Custom Token Exchange allows exchanging external tokens for Auth0 tokens without a browser redirect. The external token is validated by an Auth0 Action with the Custom Token Exchange trigger.
OptionalactorActor token for delegation/impersonation scenarios (RFC 8693). Represents the identity of the acting party.
If provided, actorTokenType is required.
OptionalactorActor token type URI (required if actorToken is provided).
-OptionaladditionalAdditional custom parameters passed to the token endpoint. +
OptionalactorActor token type URI (required if actorToken is provided).
+OptionaladditionalAdditional custom parameters passed to the token endpoint.
Accessible in Auth0 Action via event.request.body.
Use this for custom parameters instead of index signature to avoid TypeScript issues.
-OptionalaudienceThe unique identifier of the target API.
-OptionalorganizationOrganization ID or name for multi-tenant scenarios. +
OptionalaudienceThe unique identifier of the target API.
+OptionalorganizationOrganization ID or name for multi-tenant scenarios. The organization ID will be present in the resulting access token claims.
-OptionalscopeSpace-delimited OAuth 2.0 scopes.
+OptionalscopeSpace-delimited OAuth 2.0 scopes.
Note: These scopes are merged with SDK default scopes (openid profile email offline_access). Duplicates are removed.
-The external token being exchanged. +
The external token being exchanged. This will be validated by your Auth0 Action with the Custom Token Exchange trigger.
Validation: Must be a non-empty string.
-Custom URI identifying the token type.
+Custom URI identifying the token type.
Validation Rules:
Response from Custom Token Exchange.
-Response from Custom Token Exchange.
+The access token issued by Auth0
-Token lifetime in seconds
-OptionalidThe ID token, if openid scope was requested
-OptionalrefreshThe refresh token, if offline_access scope was requested
-OptionalscopeGranted scopes
-Token type, typically "Bearer" or "DPoP"
-Token lifetime in seconds
+OptionalidThe ID token, if openid scope was requested
+OptionalrefreshThe refresh token, if offline_access scope was requested
+OptionalscopeGranted scopes
+Token type, typically "Bearer" or "DPoP"
+Configuration for the OIDC discovery metadata cache. +
Configuration for the OIDC discovery metadata cache. Applies in both static and resolver modes.
OptionalttlTime-to-live for cached discovery metadata in seconds. Default: 600 (10 minutes).
+Enroll OOB authenticator using factorType.
+OptionalemailEmail address (optional for email channel - uses user's email if not provided)
+Factor type discriminator
+Encrypted MFA token
+OptionalphonePhone number in E.164 format (required for sms/voice)
+Enroll OTP authenticator using factorType.
+Enroll OOB authenticator (SMS/Voice/Push/Email).
-Enroll OOB authenticator (SMS/Voice/Push/Email).
+Authenticator types to enroll
-OptionalemailEmail address (optional for email channel - uses user's email if not provided)
-Encrypted MFA token
-OOB channels (sms, voice, auth0, email)
-OptionalphonePhone number in E.164 format (required for sms/voice)
-OptionalemailEmail address (optional for email channel - uses user's email if not provided)
+Encrypted MFA token
+OOB channels (sms, voice, auth0, email)
+OptionalphonePhone number in E.164 format (required for sms/voice)
+Enroll OTP authenticator (TOTP app like Authy/Google Authenticator).
-Enroll OTP authenticator (TOTP app like Authy/Google Authenticator).
+Encrypted MFA token
+Enrollment response from Auth0 API (snake_case). +Maps to EnrollmentResponse in SDK-facing interface.
+Authenticator type discriminator
+Optionalbarcode_Barcode URI (otp: otpauth:// format, oob: Guardian/Push QR code)
+Optionalbinding_Binding method (oob only - prompt, none)
+Authenticator ID
+OptionalnameAuthenticator name (oob/email only)
+Optionaloob_OOB channel (oob only - required for oob)
+Optionaloob_OOB code (oob only - for enrollment verification)
+Optionalrecovery_Recovery codes (first enrollment only)
+OptionalsecretTOTP secret (otp only - required for otp)
+InternalMetadata for a specific domain and its associated issuer. +
InternalMetadata for a specific domain and its associated issuer. Stored in session internal state to track which domain authenticated the user.
-The OIDC issuer URL for the domain
+MFA client interface available in both server and client contexts.
-MFA client interface available in both server and client contexts.
+Initiate an MFA challenge.
Challenge options
Challenge response (oobCode, bindingMethod)
-Enroll a new MFA authenticator during initial MFA setup.
+Enroll a new MFA authenticator during initial MFA setup.
Enrollment options (otp | oob | email)
Enrollment response with authenticator details and optional recovery codes
-List enrolled authenticators for the user. +
List enrolled authenticators for the user. Filters by allowed challenge types from mfa_requirements.
Options containing encrypted mfaToken
Array of authenticators
-Verify MFA code and complete authentication. +
Verify MFA code and complete authentication. Caches resulting access token in session.
Verification options (otp | oobCode+bindingCode | recoveryCode)
Token response with access token, refresh token, etc.
-MFA context embedded in encrypted token. +
MFA context embedded in encrypted token. Self-contained with all information needed for challenge completion.
-Timestamp for TTL validation (milliseconds since epoch)
+MFA requirements from Auth0
+Raw mfa_token from Auth0
+Scopes requested
+MFA verify response from Auth0. +
MFA verify response from Auth0. Uses snake_case to match Auth0 API and SPA SDK conventions.
Access token
-OptionalaudienceAPI audience
-Expires in seconds
-Optionalid_ID token (if present)
-Optionalrecovery_Recovery code (if regenerated by tenant config)
-Optionalrefresh_Refresh token (if present)
-OptionalscopeToken scope
-Token type (usually "Bearer")
-OptionalaudienceAPI audience
+Expires in seconds
+Optionalid_ID token (if present)
+Optionalrecovery_Recovery code (if regenerated by tenant config)
+Optionalrefresh_Refresh token (if present)
+OptionalscopeToken scope
+Token type (usually "Bearer")
+OptionalabsoluteThe absolute duration after which the session will expire. The value must be specified in seconds.
Once the absolute duration has been reached, the session will no longer be extended.
Default: 3 days.
-OptionalcookieThe options for the session cookie.
-OptionalinactivityThe duration of inactivity after which the session will expire. The value must be specified in seconds.
+OptionalcookieThe options for the session cookie.
+OptionalinactivityThe duration of inactivity after which the session will expire. The value must be specified in seconds.
The session will be extended as long as it was active before the inactivity duration has been reached.
Default: 1 day.
-OptionalrollingA boolean indicating whether rolling sessions should be used or not.
+OptionalrollingA boolean indicating whether rolling sessions should be used or not.
When enabled, the session will continue to be extended as long as it is used within the inactivity duration.
Once the upper bound, set via the absoluteDuration, has been reached, the session will no longer be extended.
Default: true.
OptionaldomainSpecifies the value for the Set-Cookie attribute. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
-OptionalnameThe name of the session cookie.
+OptionalnameThe name of the session cookie.
Default: __session.
OptionalpathThe path attribute of the session cookie. Will be set to '/' by default.
-OptionalsameThe sameSite attribute of the session cookie.
+OptionalpathThe path attribute of the session cookie. Will be set to '/' by default.
+OptionalsameThe sameSite attribute of the session cookie.
Default: lax.
OptionalsecureThe secure attribute of the session cookie.
+OptionalsecureThe secure attribute of the session cookie.
Default: depends on the protocol of the application's base URL. If the protocol is https, then true, otherwise false.
OptionaltransientThe transient attribute of the session cookie. When true, the cookie will not persist beyond the current session.
-OptionaltransientThe transient attribute of the session cookie. When true, the cookie will not persist beyond the current session.
+Interface for a custom session data store.
+Interface for a custom session data store.
TTL contract: every successful write method (set, update) must reset the session
TTL/expiry so that active sessions are not silently expired between requests.
Destroys the session with the given session ID.
-OptionaldeleteDeletes the session with the given logout token which may contain a session ID or a user ID, or both.
+OptionaldeleteDeletes the session with the given logout token which may contain a session ID or a user ID, or both.
MCD resolver mode: When using multiple custom domains with a domain resolver,
implementations MUST filter on the iss field in addition to sub/sid to
ensure sessions are only deleted for the matching issuer. Custom domains on the
same tenant share signing keys, so failing to filter on iss allows a logout
token from one domain to delete sessions created by a different domain.
Gets the session from the store given a session ID.
-Upsert a session in the store given a session ID and SessionData.
OptionalupdateOptional: update the session by its ID only if it already exists. +
Gets the session from the store given a session ID.
+Upsert a session in the store given a session ID and SessionData.
OptionalupdateOptional: update the session by its ID only if it already exists.
Return true if updated, false if not found.
OptionalabsoluteThe absolute duration after which the session will expire. The value must be specified in seconds.
Once the absolute duration has been reached, the session will no longer be extended.
Default: 3 days.
-OptionalcookieThe options for the session cookie.
-OptionalcookieOptionalinactivityThe duration of inactivity after which the session will expire. The value must be specified in seconds.
+OptionalcookieThe options for the session cookie.
+OptionalcookieOptionalinactivityThe duration of inactivity after which the session will expire. The value must be specified in seconds.
The session will be extended as long as it was active before the inactivity duration has been reached.
Default: 1 day.
-OptionalrollingA boolean indicating whether rolling sessions should be used or not.
+OptionalrollingA boolean indicating whether rolling sessions should be used or not.
When enabled, the session will continue to be extended as long as it is used within the inactivity duration.
Once the upper bound, set via the absoluteDuration, has been reached, the session will no longer be extended.
Default: true.
OptionalstoreOptionalstoreOptionalchallengeControl callback return behavior.
+OptionalreturnThe URL to redirect to after a successful login.
+OptionaldomainSpecifies the value for the Set-Cookie attribute. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
-OptionalmaxThe expiration time for transaction cookies in seconds. +
OptionalmaxThe expiration time for transaction cookies in seconds. If not provided, defaults to 1 hour (3600 seconds).
OptionalpathThe path attribute of the transaction cookie. Will be set to '/' by default.
-OptionalprefixThe prefix of the cookie used to store the transaction state.
+OptionalpathThe path attribute of the transaction cookie. Will be set to '/' by default.
+OptionalprefixThe prefix of the cookie used to store the transaction state.
Default: __txn_{state}.
OptionalsameThe sameSite attribute of the transaction cookie.
+OptionalsameThe sameSite attribute of the transaction cookie.
Default: lax.
OptionalsecureThe secure attribute of the transaction cookie.
+OptionalsecureThe secure attribute of the transaction cookie.
Default: depends on the protocol of the application's base URL. If the protocol is https, then true, otherwise false.
Any other JWT Claim Set member.
-Any other JWT Claim Set member.
+OptionalaudienceThe audience used for this transaction.
-OptionalauthOptionalmaxOptionalnonceOptional InternaloriginThe Auth0 domain used for this transaction (MCD mode). +
OptionalauthOptionalchallengeThe challenge mode for this transaction.
+OptionalmaxOptionalnonceOptional InternaloriginThe Auth0 domain used for this transaction (MCD mode). Stored to validate that the session is for the same domain.
-Optional InternaloriginThe OIDC issuer URL for this transaction (MCD mode). +
Optional InternaloriginThe OIDC issuer URL for this transaction (MCD mode). Stored alongside originDomain for validation.
-OptionalscopeThe scope requested for this transaction.
-OptionalscopeThe scope requested for this transaction.
+OptionalcookieOptionalenableControls whether multiple parallel login transactions are allowed. When false, only one transaction cookie is maintained at a time. When true (default), multiple transaction cookies can coexist for multi-tab support.
OptionalemailOptionalemail_Optionalfamily_Optionalgiven_OptionalnameOptionalnicknameOptionalorg_The organization ID that the user belongs to. This field is populated when the user logs in through an organization.
-OptionalpictureOptionalpictureBase options for MFA verify.
-Base options for MFA verify.
+Verification with OOB code sent via SMS/Email/Push.
+Verification with OOB code sent via SMS/Email/Push.
Verification with OTP code from authenticator app.
+Verification with OTP code from authenticator app.
Verification with recovery code (backup).
+Verification with recovery code (backup).
Full response from the /auth/access-token endpoint.
Returned by getAccessToken({ includeFullResponse: true }) and by
+mfa.challengeWithPopup(). Contains the access token along with scope
+and expiration metadata.
Optionalexpires_Absolute expiration time in seconds since Unix epoch.
+Optionalexpires_Time-to-live in seconds from the time of issuance.
+OptionalscopeSpace-separated scopes granted by Auth0.
+The access token string (JWT or opaque).
+Optionaltoken_Token type, typically "Bearer".
const MyProtectedPage = withPageAuthRequired(MyPage);
+WithPageAuthRequired | @auth0/nextjs-auth0 - v4.19.0 Type Alias WithPageAuthRequired
WithPageAuthRequired: <P extends object>(
    Component: ComponentType<P & UserProps>,
    options?: WithPageAuthRequiredOptions,
) => React.FC<P>const MyProtectedPage = withPageAuthRequired(MyPage);
When you wrap your pages in this higher order component and an anonymous user visits your page,
they will be redirected to the login page and then returned to the page they were redirected from (after login).
-Type Declaration
- <P extends object>(
    Component: ComponentType<P & UserProps>,
    options?: WithPageAuthRequiredOptions,
): React.FC<P> Type Parameters
- P extends object
Parameters
- Component: ComponentType<P & UserProps>
Optionaloptions: WithPageAuthRequiredOptions
Returns React.FC<P>
+Optionaloptions: WithPageAuthRequiredOptionsAn app route that has been augmented with WithPageAuthRequired. +
An app route that has been augmented with WithPageAuthRequired. Returns any to be compatible with React's return types while avoiding React dependency.
The generic parameter P allows passing Next.js PageProps or LayoutProps
types for strongly-typed route parameters:
export default auth0.withPageAuthRequired(
async function Page(props: PageProps<"/customers/[id]/details">) {
const { id } = await props.params;
return <div>{id}</div>;
}
);
-Objects containing the route parameters and search parameters of the page.
-Objects containing the route parameters and search parameters of the page.
+If you wrap your getServerSideProps with WithPageAuthRequired your props object will be augmented with
+
If you wrap your getServerSideProps with WithPageAuthRequired your props object will be augmented with
the user property, which will be the User object.
// pages/profile.js
import { auth0 } from "@/lib/auth0";
export default function Profile({ user }) {
return <div>Hello {user.name}</div>;
}
export const getServerSideProps = auth0.withPageAuthRequired();
-A page route that has been augmented with WithPageAuthRequired.
-A page route that has been augmented with WithPageAuthRequired.
+Protects Page router pages WithPageAuthRequiredPageRouter or +
Protects Page router pages WithPageAuthRequiredPageRouter or App router pages WithPageAuthRequiredAppRouter
-Wrap your Server Component with this method to make sure the user is authenticated before +
Wrap your Server Component with this method to make sure the user is authenticated before visiting the page.
// app/protected-page/page.js
import { auth0 } from "@/lib/auth0";
const ProtectedPage = auth0.withPageAuthRequired(async function ProtectedPage() {
return <div>Protected content</div>;
}, { returnTo: '/protected-page' });
export default ProtectedPage;
@@ -14,4 +14,4 @@
// app/protected-page/[slug]/page.js
import { AppRouterPageRouteOpts } from '@auth0/nextjs-auth0/server';
import { auth0 } from "@/lib/auth0";
const ProtectedPage = auth0.withPageAuthRequired(async function ProtectedPage({
params, searchParams
}: AppRouterPageRouteOpts) {
const slug = (await params)?.slug as string;
return <div>Protected content for {slug}</div>;
}, {
returnTo({ params }) {
return `/protected-page/${(await params)?.slug}`;
}
});
export default ProtectedPage;
-Optionalopts: WithPageAuthRequiredAppRouterOptions<P>Optionalopts: WithPageAuthRequiredAppRouterOptions<P>Specify the URL to returnTo - this is important in app router pages because the server component
+
Specify the URL to returnTo - this is important in app router pages because the server component
won't know the URL of the page.
*
The type of the page or layout props, extending AppRouterPageRouteOpts.
This allows the returnTo callback to access strongly-typed route parameters.
Wrap your getServerSideProps with this method to make sure the user is authenticated before
+
Wrap your getServerSideProps with this method to make sure the user is authenticated before
visiting the page.
// pages/protected-page.js
import { auth0 } from "@/lib/auth0";
export default function ProtectedPage() {
return <div>Protected content</div>;
}
export const getServerSideProps = auth0.withPageAuthRequired();
If the user visits /protected-page without a valid session, it will redirect the user to the
login page. Then they will be returned to /protected-page after login.
Optionalopts: WithPageAuthRequiredPageRouterOptions<P, Q>Optionalopts: WithPageAuthRequiredPageRouterOptions<P, Q>If you have a custom returnTo url you should specify it in returnTo.
If you have a custom returnTo url you should specify it in returnTo.
You can pass in your own getServerSideProps method, the props returned from this will be
merged with the user props. You can also access the user session data by calling getSession
inside of this method. For example:
// pages/protected-page.js
import { auth0 } from "@/lib/auth0";
export default function ProtectedPage({ user, customProp }) {
return <div>Protected content</div>;
}
export const getServerSideProps = auth0.withPageAuthRequired({
// returnTo: '/unauthorized',
async getServerSideProps(ctx) {
// access the user session if needed
// const session = await auth0.getSession(ctx.req);
return {
props: {
// customProp: 'bar',
}
};
}
});
-postMessage payload sent from the popup callback page to the parent window.
+Uses a discriminated union on success for type-safe handling:
success: true — MFA completed, optional user metadata attachedsuccess: false — error occurred, error code and message attachedSecurity: Never contains raw access tokens. Only user metadata (sub, email)
+is sent via postMessage. Tokens remain server-side in the encrypted session.
Optionaluser?: { email: string; sub: string }User metadata from the authenticated session (sub and email only).
+Error details from the callback (OAuth error code + description).
+Resolves the Auth0 domain from request context. +
Resolves the Auth0 domain from request context. Called once per SDK operation in resolver mode.
Supports both synchronous and asynchronous resolution patterns.
Request headers from the current context. @@ -22,4 +22,4 @@
MFA enrollment options (discriminated union).
-MFA enrollment options (discriminated union).
+MFA enrollment response (discriminated union).
-MFA enrollment response (discriminated union).
+Factor types for MFA enrollment.
+OptionalaudiencePlease note: If you are passing audience, ensure that the used audiences and scopes are part of the Application's Refresh Token Policies in Auth0 when configuring Multi-Resource Refresh Tokens (MRRT). Auth0 Documentation on Multi-resource Refresh Tokens
-OptionalrefreshOptionalscopeOptionalmergeControl scope merging behavior. +When true (default): merge global scopes for default audience. +When false: use ONLY requested scope (no global merge). +Used by challengeWithPopup() to prevent global scope pollution.
+OptionalrefreshOptionalscopeLogout strategy options for controlling logout endpoint selection.
-Logout strategy options for controlling logout endpoint selection.
+OptionalappThe resolved base URL for the current request, used to build safe redirects.
-OptionalconnectedThe connected account information when the responseType is RESPONSE_TYPES.CONNECT_CODE
-OptionalresponseThe type of response expected from the authorization server. +
OptionalchallengeThe return strategy for this callback flow.
+OptionalconnectedThe connected account information when the responseType is RESPONSE_TYPES.CONNECT_CODE
+OptionalresponseThe type of response expected from the authorization server. One of RESPONSE_TYPES
-OptionalreturnThe URL or path the user should be redirected to after completing the transaction.
-OptionalreturnThe URL or path the user should be redirected to after completing the transaction.
+MFA verification options (union type).
-MFA verification options (union type).
+ConstClient-side MFA API singleton.
-import { mfa } from '@auth0/nextjs-auth0/client';
// List authenticators
const authenticators = await mfa.getAuthenticators({ mfaToken });
// Initiate challenge
const challenge = await mfa.challenge({ mfaToken, challengeType: 'oob' });
// Verify and complete
const tokens = await mfa.verify({ mfaToken, otp: '123456' });
+mfa | @auth0/nextjs-auth0 - v4.19.0 Variable mfaConst
mfa: ClientMfaClient = ...Client-side MFA API singleton.
+Provides methods for MFA authenticator management, challenge/verify flows,
+and popup-based step-up authentication via Universal Login.
+Example
import { mfa } from '@auth0/nextjs-auth0/client';
// List authenticators
const authenticators = await mfa.getAuthenticators({ mfaToken });
// Initiate challenge
const challenge = await mfa.challenge({ mfaToken, challengeType: 'oob' });
// Verify and complete
const tokens = await mfa.verify({ mfaToken, otp: '123456' });
// Step-up via popup (no redirect)
const { token } = await mfa.challengeWithPopup({
audience: 'https://api.example.com'
});
-
+ConstConstConstDefault claims for the ID token.
-ConstDefault claims for the ID token.
+ConstGrant type for Custom Token Exchange as per RFC 8693.
+ConstGrant type for MFA OOB (SMS/Email/Push) verification.
+ConstGrant type for MFA OOB (SMS/Email/Push) verification.
ConstGrant type for MFA token exchange. +
ConstGrant type for MFA token exchange. Used in token endpoint requests to exchange an mfa_token for access/refresh tokens.
ConstGrant type for MFA recovery code verification.
+ConstGrant type for MFA recovery code verification.
Error class representing an access token for connection error. +
Class AccessTokenForConnectionError
Error class representing an access token for connection error. Extends the
-SdkErrorclass.Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    code: string,
    message: string,
    cause?: OAuth2Error,
): AccessTokenForConnectionError
Constructs a new
AccessTokenForConnectionErrorinstance.Parameters
The error code.
The error message.
Optionalcause: OAuth2ErrorThe OAuth2 cause of the error.
-Returns AccessTokenForConnectionError
Properties
Optionalcausecode
The error code associated with the access token error.
-Settings
On This Page
Constructors
Properties
Returns AccessTokenForConnectionError