From f57791098551c26869fa7708969388a67f65785d Mon Sep 17 00:00:00 2001
From: Tushar Pandey Error thrown when backchannel logout processing fails. Error thrown when backchannel logout processing fails. Error 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 This error is thrown when a Custom Token Exchange operation fails,
such as validation errors or server-side token exchange failures. Constructs a new The error code. The error message. The OAuth2 cause of the error. The 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. Constructs a new The underlying error that caused this DPoP error (optional) The specific DPoP error code indicating the type of failure Thrown when mfa.challengeWithPopup is called outside of a browser context
+(e.g., in a Server Component, Route Handler, or middleware). Thrown when request validation fails (missing/invalid params).
+ Thrown when request validation fails (missing/invalid params).
Mapped to 400 Bad Request. Error thrown when initiating an MFA challenge fails. Error thrown when initiating an MFA challenge fails. Error thrown when MFA enrollment fails. Error thrown when MFA enrollment fails. Error thrown when listing MFA authenticators fails. Error thrown when listing MFA authenticators fails. Error 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. Error class representing a connect account request error. Error class representing a connect account request error. A human-readable description of the specific error. Required. A human-readable description of the specific error. Required. The name of the invalid parameter. Optional. A JSON Pointer that points to the exact location of the error in a JSON document being validated. Optional. Specifies the source of the error (e.g., body, query, or header in an HTML message). Optional. Errors that come from Auth0 in the Errors that come from Auth0 in the 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. Thrown when the user closes the popup window before completing MFA. The SDK polls Thrown 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. Thrown when the popup does not complete authentication within the configured timeout. Default timeout is 60 seconds. Configure per-call via
+ isRolling returns true if rolling sessions are enabled. calculateMaxAge calculates the max age of the session based on createdAt and the rolling and absolute durations. epoch returns the time since unix epoch in seconds. save adds the encrypted session cookie as a isRolling returns true if rolling sessions are enabled. calculateMaxAge calculates the max age of the session based on createdAt and the rolling and absolute durations. epoch returns the time since unix epoch in seconds. save adds the encrypted session cookie as a MFA API for server-side operations. Provides access to MFA methods that require encrypted mfa_token from MfaRequiredError: 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 This method first attempts to obtain an access token with the The user will then be redirected to authorize the connection with the third-party provider. You must enable 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. Optional configuration for getting the access token. Optional configuration for getting the access token. Please 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 getAccessToken returns the access token. Control 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. getAccessToken returns the access token. This method can be used in middleware and The request object. The response object. Please 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 Retrieves an access token for a connection. Control 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. Retrieves 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 Retrieves an access token for a connection. Retrieves an access token for a connection. This method can be used in middleware and 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 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 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. 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. A descriptive error message The 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. A 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 Original Auth0 error code Original Auth0 error description MFA requirements indicating available challenge/enrollment methods Encrypted MFA token to pass to MFA API methods. Serialize error for HTTP responses.
+ Original Auth0 error code Original Auth0 error description MFA requirements indicating available challenge/enrollment methods 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. A 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 Optional 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 The access token as a string, or the full token response when 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 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. The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications. 📚 Documentation - 🚀 Getting Started - 💻 API Reference - 💬 Feedback This library requires Node.js 20 LTS and newer LTS versions. Add the following environment variables to your Add the following environment variables to your When using dynamic hosts (preview environments), ensure the resulting callback and logout URLs are registered in your Auth0 application. For preview environments ( For preview environments ( If you know the base URL at startup (for example, a stable production domain), set 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): 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
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. Create a Create a 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): You can customize the client by using the options below: You can customize the client by using the options below: 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: Quick 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: 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 DPoP Inheritance Behavior Fetchers created with 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. Configure timing validation for DPoP proofs to handle clock differences between client and server: Configure timing validation for DPoP proofs to handle clock differences between client and server: 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 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 Configure audience and scopes for the APIs: Configure audience and scopes for the APIs: Make requests through the proxy paths: Make requests through the proxy paths: The 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.: Your Next.js application may be configured to use a base path (e.g.: For example, if the
We do not recommend using the The SDK performs validation of required configuration options when initializing the The SDK performs validation of required configuration options when initializing the 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. The SDK supports authenticating users against multiple Auth0 custom domains on the same tenant. Pass a The SDK supports authenticating users against multiple Auth0 custom domains on the same tenant. Pass a For complete documentation, configuration options, and examples, see Multiple Custom Domains in EXAMPLES.md. The SDK mounts 6 routes: The SDK mounts 6 routes: 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.
Class AccessTokenError
Hierarchy (View Summary)
Index
Constructors
Class AccessTokenError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    code: string,
    message: string,
    cause?: OAuth2Error,
): AccessTokenErrorParameters
Optionalcause: OAuth2ErrorReturns AccessTokenError
Constructors
constructor
    code: string,
    message: string,
    cause?: OAuth2Error,
): AccessTokenErrorParameters
Optionalcause: OAuth2ErrorReturns AccessTokenError
Class AccessTokenForConnectionError
Class AuthorizationCodeGrantError
Hierarchy (View Summary)
Index
Constructors
Class AuthorizationCodeGrantError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    __namedParameters: { cause: OAuth2Error; message?: string },
): AuthorizationCodeGrantErrorParameters
Returns AuthorizationCodeGrantError
Constructors
constructor
    __namedParameters: { cause: OAuth2Error; message?: string },
): AuthorizationCodeGrantErrorParameters
Returns AuthorizationCodeGrantError
Class AuthorizationCodeGrantRequestError
Hierarchy (View Summary)
Index
Constructors
Class AuthorizationCodeGrantRequestError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    message?: string,
): AuthorizationCodeGrantRequestErrorParameters
Optionalmessage: stringReturns AuthorizationCodeGrantRequestError
Constructors
constructor
    message?: string,
): AuthorizationCodeGrantRequestErrorParameters
Optionalmessage: stringReturns AuthorizationCodeGrantRequestError
Class AuthorizationError
Hierarchy (View Summary)
Index
Constructors
Class AuthorizationError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    __namedParameters: { cause: OAuth2Error; message?: string },
): AuthorizationErrorParameters
Returns AuthorizationError
Constructors
constructor
    __namedParameters: { cause: OAuth2Error; message?: string },
): AuthorizationErrorParameters
Returns AuthorizationError
Class BackchannelAuthenticationError
Hierarchy (View Summary)
Index
Constructors
Class BackchannelAuthenticationError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    __namedParameters: { cause?: OAuth2Error },
): BackchannelAuthenticationErrorParameters
Returns BackchannelAuthenticationError
Constructors
constructor
    __namedParameters: { cause?: OAuth2Error },
): BackchannelAuthenticationErrorParameters
Returns BackchannelAuthenticationError
Class BackchannelAuthenticationNotSupportedError
Hierarchy (View Summary)
Index
Constructors
Class BackchannelAuthenticationNotSupportedError
Hierarchy (View Summary)
Index
Constructors
Properties
Class BackchannelLogoutError
Hierarchy (View Summary)
Index
Constructors
Class BackchannelLogoutError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns BackchannelLogoutError
Constructors
constructor
Parameters
Optionalmessage: stringReturns BackchannelLogoutError
Class ConnectAccountError
Hierarchy (View Summary)
Index
Constructors
Class ConnectAccountError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    __namedParameters: {
        cause?: MyAccountApiError;
        code: string;
        message: string;
    },
): ConnectAccountErrorParameters
Returns ConnectAccountError
Constructors
constructor
    __namedParameters: {
        cause?: MyAccountApiError;
        code: string;
        message: string;
    },
): ConnectAccountErrorParameters
Returns ConnectAccountError
Class CustomTokenExchangeError
Class CustomTokenExchangeError
SdkError class.Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    code: string,
    message: string,
    cause?: OAuth2Error,
): CustomTokenExchangeErrorCustomTokenExchangeError instance.Parameters
Optionalcause: OAuth2ErrorReturns CustomTokenExchangeError
Returns CustomTokenExchangeError
Properties
Optionalcausecode
Class DPoPError
Class DPoPError
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
DPoPError instance.Returns DPoPError
Properties
Optionalcausecode
Class DiscoveryError
Hierarchy (View Summary)
Index
Constructors
Class DiscoveryError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns DiscoveryError
Constructors
constructor
Parameters
Optionalmessage: stringReturns DiscoveryError
Class ExecutionContextError
challengeWithPopup() requires window and can only run in client components.Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns ExecutionContextError
Class InvalidConfigurationError
Hierarchy (View Summary)
Index
Constructors
Class InvalidConfigurationError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns InvalidConfigurationError
Constructors
constructor
Parameters
Optionalmessage: stringReturns InvalidConfigurationError
Class InvalidRequestError
Class InvalidRequestError
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
constructor
Parameters
Returns InvalidRequestError
Constructors
constructor
Parameters
Returns InvalidRequestError
Class InvalidStateError
Hierarchy (View Summary)
Index
Constructors
Class InvalidStateError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns InvalidStateError
Constructors
constructor
Parameters
Optionalmessage: stringReturns InvalidStateError
Class MfaChallengeError
Class MfaChallengeError
Hierarchy
Index
Constructors
Hierarchy
Index
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaChallengeErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaChallengeError
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaChallengeErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaChallengeError
Returns { error: string; error_description: string }
Class MfaEnrollmentError
Class MfaEnrollmentError
Hierarchy
Index
Constructors
Hierarchy
Index
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaEnrollmentErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaEnrollmentError
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaEnrollmentErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaEnrollmentError
Returns { error: string; error_description: string }
Class MfaGetAuthenticatorsError
Class MfaGetAuthenticatorsError
Hierarchy
Index
Constructors
Hierarchy
Index
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaGetAuthenticatorsErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaGetAuthenticatorsError
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaGetAuthenticatorsErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaGetAuthenticatorsError
Returns { error: string; error_description: string }
Class MfaNoAvailableFactorsError
Class MfaNoAvailableFactorsError
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Returns MfaNoAvailableFactorsError
Constructors
constructor
Parameters
Returns MfaNoAvailableFactorsError
Class MfaVerifyError
Class MfaVerifyError
Hierarchy
Index
Constructors
Hierarchy
Index
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaVerifyErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaVerifyError
Constructors
constructor
    error: string,
    error_description: string,
    cause?: MfaApiErrorResponse,
): MfaVerifyErrorParameters
Optionalcause: MfaApiErrorResponseReturns MfaVerifyError
Returns { error: string; error_description: string }
Class MissingStateError
Hierarchy (View Summary)
Index
Constructors
Class MissingStateError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns MissingStateError
Constructors
constructor
Parameters
Optionalmessage: stringReturns MissingStateError
Class MyAccountApiError
Hierarchy (View Summary)
Index
Constructors
Class MyAccountApiError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    __namedParameters: {
        detail: string;
        status: number;
        title: string;
        type: string;
        validationErrors?: {
            detail: string;
            field?: string;
            pointer?: string;
            source?: string;
        }[];
    },
): MyAccountApiErrorParameters
    detail: string;
    status: number;
    title: string;
    type: string;
    validationErrors?: {
        detail: string;
        field?: string;
        pointer?: string;
        source?: string;
    }[];
}Returns MyAccountApiError
Properties
code
detail
name
status
title
type
Optionalvalidation
    detail: string;
    field?: string;
    pointer?: string;
    source?: string;
}[]Type Declaration
detail: string
Constructors
constructor
    __namedParameters: {
        detail: string;
        status: number;
        title: string;
        type: string;
        validationErrors?: {
            detail: string;
            field?: string;
            pointer?: string;
            source?: string;
        }[];
    },
): MyAccountApiErrorParameters
    detail: string;
    status: number;
    title: string;
    type: string;
    validationErrors?: {
        detail: string;
        field?: string;
        pointer?: string;
        source?: string;
    }[];
}Returns MyAccountApiError
Properties
code
detail
name
status
title
type
Optionalvalidation
    detail: string;
    field?: string;
    pointer?: string;
    source?: string;
}[]Type Declaration
detail: string
Optionalfield?: stringOptionalpointer?: stringOptionalsource?: stringClass OAuth2Error
redirect_uri callback may contain reflected user input via the OpenID Connect error and error_description query parameter.
+Class OAuth2Error
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.Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Returns OAuth2Error
Constructors
constructor
Parameters
Returns OAuth2Error
Class PopupBlockedError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns PopupBlockedError
Class PopupCancelledError
popup.closed every 500ms to detect manual closure.
+This is a user-initiated cancellation, not an error condition.Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns PopupCancelledError
Class PopupInProgressError
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns PopupInProgressError
Class PopupTimeoutError
ChallengeWithPopupOptions.timeout.Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns PopupTimeoutError
Class SdkError
AbstractHierarchy (View Summary)
Index
Constructors
Class SdkError
AbstractHierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns SdkError
Constructors
constructor
Parameters
Optionalmessage: stringReturns SdkError
Class AbstractSessionStore
AbstractIndex
Constructors
Class AbstractSessionStore
AbstractIndex
Constructors
Properties
Constructors
constructor
Parameters
Returns AbstractSessionStore
Properties
cookie
Protectedrollingsecret
session
OptionalstoreAccessors
is
Returns boolean
Methods
calculate
Parameters
Returns number
Abstractdelete
    reqCookies: RequestCookies | ReadonlyRequestCookies,
    resCookies: ResponseCookies,
): Promise<void>Parameters
Returns Promise<void>
epoch
Returns number
AbstractgetParameters
Returns Promise<SessionData | null>
Abstractset
    reqCookies: RequestCookies | ReadonlyRequestCookies,
    resCookies: ResponseCookies,
    session: SessionData,
    isNew?: boolean,
): Promise<void>Set-Cookie header. If the iat property
+Constructors
constructor
Parameters
Returns AbstractSessionStore
Properties
cookie
Protectedrollingsecret
session
OptionalstoreAccessors
is
Returns boolean
Methods
calculate
Parameters
Returns number
Abstractdelete
    reqCookies: RequestCookies | ReadonlyRequestCookies,
    resCookies: ResponseCookies,
): Promise<void>Parameters
Returns Promise<void>
epoch
Returns number
AbstractgetParameters
Returns Promise<SessionData | null>
Abstractset
    reqCookies: RequestCookies | ReadonlyRequestCookies,
    resCookies: ResponseCookies,
    session: SessionData,
    isNew?: boolean,
): Promise<void>Set-Cookie header. If the iat property
is present on the session, then it will be used to compute the maxAge cookie value.Parameters
OptionalisNew: booleanReturns Promise<void>
Parameters
OptionalisNew: booleanReturns Promise<void>
Class Auth0Client
Index
Constructors
Class Auth0Client
Index
Constructors
Accessors
Methods
Constructors
constructor
Parameters
Returns Auth0Client
Constructors
constructor
Parameters
Returns Auth0Client
Accessors
mfa
Returns ServerMfaClient
Example: Handling MFA required scenario
-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'
});
}
}
Methods
connect
ConnectAccountError is thrown.create:me:connected_accounts scope
for the My Account API to create a connected account for the user.Offline Access from the Connection Permissions settings to be able to use the connection with Connected Accounts.Parameters
Returns Promise<NextResponse<unknown>>
create
    req: NextRequest | Request | PagesRouterRequest | undefined,
    options: {
        baseUrl?: string;
        fetch?: CustomFetchImpl<TOutput>;
        getAccessToken?: AccessTokenFactory;
        useDPoP?: boolean;
    },
): Promise<Fetcher<TOutput>>Parameters
Returns Promise<NextResponse<unknown>>
create
    req: NextRequest | Request | PagesRouterRequest | undefined,
    options: {
        baseUrl?: string;
        fetch?: CustomFetchImpl<TOutput>;
        getAccessToken?: AccessTokenFactory;
        useDPoP?: boolean;
    },
): Promise<Fetcher<TOutput>>
-custom
    options: CustomTokenExchangeOptions,
): Promise<CustomTokenExchangeResponse>custom
    options: CustomTokenExchangeOptions,
): Promise<CustomTokenExchangeResponse>get
    options?: GetAccessTokenOptions,
): Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>Parameters
Optionaloptions: GetAccessTokenOptionsget
    options?: GetAccessTokenOptions,
): Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>Parameters
Optionaloptions: GetAccessTokenOptionsOptionalaudience?: string | nullOptionalrefresh?: boolean | nullOptionalscope?: string | nullReturns Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>
    req: NextRequest | PagesRouterRequest,
    res: NextResponse<unknown> | PagesRouterResponse,
    options?: GetAccessTokenOptions,
): Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>OptionalmergeScopes?: booleanOptionalrefresh?: boolean | nullOptionalscope?: string | nullReturns Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>
    req: NextRequest | PagesRouterRequest,
    res: NextResponse<unknown> | PagesRouterResponse,
    options?: GetAccessTokenOptions,
): Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>getServerSideProps, API routes in the Pages Router.Parameters
Optionalaudience?: string | nullOptionalrefresh?: boolean | nullOptionalscope?: string | nullReturns Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>get
    options: AccessTokenForConnectionOptions,
): Promise<{ expiresAt: number; token: string }>OptionalmergeScopes?: booleanOptionalrefresh?: boolean | nullOptionalscope?: string | nullReturns Promise<
    {
        audience?: string;
        expiresAt: number;
        scope?: string;
        token: string;
        token_type?: string;
    },
>get
    options: AccessTokenForConnectionOptions,
): Promise<{ expiresAt: number; token: string }>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.Parameters
Returns Promise<{ expiresAt: number; token: string }>
    options: AccessTokenForConnectionOptions,
    req: NextRequest | Request | PagesRouterRequest | undefined,
    res: NextResponse<unknown> | PagesRouterResponse | undefined,
): Promise<{ expiresAt: number; token: string }>Parameters
Returns Promise<{ expiresAt: number; token: string }>
    options: AccessTokenForConnectionOptions,
    req: NextRequest | Request | PagesRouterRequest | undefined,
    res: NextResponse<unknown> | PagesRouterResponse | undefined,
): Promise<{ expiresAt: number; token: string }>getServerSideProps, API routes in the Pages Router.Parameters
Returns Promise<{ expiresAt: number; token: string }>
get
Parameters
Returns Promise<{ expiresAt: number; token: string }>
get
Returns Promise<SessionData | null>
Returns Promise<SessionData | null>
getServerSideProps, API routes in the Pages Router.Parameters
Returns Promise<SessionData | null>
get
    options: BackchannelAuthenticationOptions,
): Promise<BackchannelAuthenticationResponse>Parameters
Returns Promise<SessionData | null>
get
    options: BackchannelAuthenticationOptions,
): Promise<BackchannelAuthenticationResponse>Parameters
Returns Promise<BackchannelAuthenticationResponse>
middleware
Parameters
Returns Promise<NextResponse<unknown>>
start
    options?: StartInteractiveLoginOptions,
): Promise<NextResponse<unknown>>Parameters
Returns Promise<NextResponse<unknown>>
update
    req: NextRequest | Request | PagesRouterRequest,
    res: Response | NextResponse<unknown> | PagesRouterResponse,
    session: SessionData,
): Promise<void>middleware
Parameters
Returns Promise<NextResponse<unknown>>
start
    options?: StartInteractiveLoginOptions,
): Promise<NextResponse<unknown>>Parameters
Returns Promise<NextResponse<unknown>>
update
    req: NextRequest | Request | PagesRouterRequest,
    res: Response | NextResponse<unknown> | PagesRouterResponse,
    session: SessionData,
): Promise<void>getServerSideProps, API routes, and middleware in the Pages Router.Parameters
Returns Promise<void>
Parameters
Returns Promise<void>
Parameters
Returns Promise<void>
with
    apiRoute: AppRouteHandlerFn | NextApiHandler,
): (
    req: NextApiRequest | NextRequest,
    resOrParams: AppRouteHandlerFnContext | NextApiResponse,
) => unknownParameters
Returns (
    req: NextApiRequest | NextRequest,
    resOrParams: AppRouteHandlerFnContext | NextApiResponse,
) => unknownwith
Returns PageRoute<{ [key: string]: any }, ParsedUrlQuery>
    fn: AppRouterPageRoute<P>,
    opts?: WithPageAuthRequiredAppRouterOptions<P>,
): AppRouterPageRoute<P>Type Parameters
Parameters
Optionalopts: WithPageAuthRequiredAppRouterOptions<P>Returns AppRouterPageRoute<P>
Parameters
Returns Promise<void>
with
    apiRoute: AppRouteHandlerFn | NextApiHandler,
): (
    req: NextApiRequest | NextRequest,
    resOrParams: AppRouteHandlerFnContext | NextApiResponse,
) => unknownParameters
Returns (
    req: NextApiRequest | NextRequest,
    resOrParams: AppRouteHandlerFnContext | NextApiResponse,
) => unknownwith
Returns PageRoute<{ [key: string]: any }, ParsedUrlQuery>
    fn: AppRouterPageRoute<P>,
    opts?: WithPageAuthRequiredAppRouterOptions<P>,
): AppRouterPageRoute<P>Type Parameters
Parameters
Optionalopts: WithPageAuthRequiredAppRouterOptions<P>Returns AppRouterPageRoute<P>
Class DomainResolutionError
Class DomainResolutionError
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringOptionalcause: ErrorReturns DomainResolutionError
Returns DomainResolutionError
Class DomainValidationError
Class DomainValidationError
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns DomainValidationError
Returns DomainValidationError
Class IssuerValidationError
Class IssuerValidationError
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
    expectedIssuer: string,
    actualIssuer: string,
): IssuerValidationErrorParameters
Returns IssuerValidationError
Returns IssuerValidationError
Class MfaRequiredError
Class MfaRequiredError
mfa_required.
The mfa_token property contains an encrypted token that can be used
with Auth0's MFA API to complete the authentication challenge.Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Properties
Optional ReadonlycauseReadonlycodeReadonlyerrorReadonlyerror_Optional Readonlymfa_Readonlymfa_Methods
to
    error: string;
    error_description: string;
    mfa_requirements?: MfaRequirements;
    mfa_token: string;
}Properties
Optional ReadonlycauseReadonlycodeReadonlyerrorReadonlyerror_Optional Readonlymfa_Readonlymfa_Methods
to
    error: string;
    error_description: string;
    mfa_requirements?: MfaRequirements;
    mfa_token: string;
}Returns {
    error: string;
    error_description: string;
    mfa_requirements?: MfaRequirements;
    mfa_token: string;
}Returns {
diff --git a/docs/classes/server.MfaTokenExpiredError.html b/docs/classes/server.MfaTokenExpiredError.html
index afdcbd511..f6ed3a014 100644
--- a/docs/classes/server.MfaTokenExpiredError.html
+++ b/docs/classes/server.MfaTokenExpiredError.html
@@ -1,4 +1,4 @@
-
    error: string;
    error_description: string;
    mfa_requirements?: MfaRequirements;
    mfa_token: string;
}Class MfaTokenExpiredError
Class MfaTokenExpiredError
@@ -9,6 +9,6 @@
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Returns MfaTokenExpiredError
Constructors
constructor
Returns MfaTokenExpiredError
Class MfaTokenInvalidError
Class MfaTokenInvalidError
-Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Returns MfaTokenInvalidError
Constructors
constructor
Returns MfaTokenInvalidError
Class SessionDomainMismatchError
Class SessionDomainMismatchError
Hierarchy (View Summary)
Index
Constructors
Hierarchy (View Summary)
Index
Constructors
Properties
Constructors
constructor
Parameters
Optionalmessage: stringReturns SessionDomainMismatchError
Returns SessionDomainMismatchError
Class TransactionStore
Class TransactionStore
Index
Constructors
Index
Constructors
Methods
Constructors
constructor
Parameters
Returns TransactionStore
Methods
delete
Parameters
Returns Promise<void>
delete
Parameters
Returns Promise<void>
get
    reqCookies: RequestCookies,
    state: string,
): Promise<JWTDecryptResult<TransactionState> | null>Parameters
Returns Promise<JWTDecryptResult<TransactionState> | null>
get
Returns string
save
    resCookies: ResponseCookies,
    transactionState: TransactionState,
    reqCookies?: RequestCookies,
): Promise<void>Constructors
constructor
Parameters
Returns TransactionStore
Methods
delete
Parameters
Returns Promise<void>
delete
Parameters
Returns Promise<void>
get
    reqCookies: RequestCookies,
    state: string,
): Promise<JWTDecryptResult<TransactionState> | null>Parameters
Returns Promise<JWTDecryptResult<TransactionState> | null>
get
Returns string
save
    resCookies: ResponseCookies,
    transactionState: TransactionState,
    reqCookies?: RequestCookies,
): Promise<void>Parameters
OptionalreqCookies: RequestCookiesReturns Promise<void>
Enumeration AccessTokenErrorCode
Index
Enumeration Members
Enumeration AccessTokenErrorCode
Index
Enumeration Members
Enumeration AccessTokenForConnectionErrorCode
Index
Enumeration Members
Enumeration AccessTokenForConnectionErrorCode
Index
Enumeration Members
Enumeration Members
FAILED_
MISSING_
MISSING_
MISSING_
MISSING_
Enumeration ConnectAccountErrorCodes
Index
Enumeration Members
Enumeration ConnectAccountErrorCodes
Index
Enumeration Members
Enumeration Members
FAILED_
FAILED_
MISSING_
FAILED_
MISSING_
Enumeration CustomTokenExchangeErrorCode
Index
Enumeration Members
Enumeration CustomTokenExchangeErrorCode
Index
Enumeration Members
Enumeration Members
EXCHANGE_
INVALID_
MISSING_
MISSING_
INVALID_
MISSING_
MISSING_
Enumeration DPoPErrorCode
Enumeration DPoPErrorCode
Index
Enumeration Members
Index
Enumeration Members
Enumeration Members
DPOP_
DPOP_
DPOP_
DPOP_
DPOP_
Enumeration RESPONSE_TYPES
Index
Enumeration Members
Enumeration RESPONSE_TYPES
Index
Enumeration Members
CONNECT_
Enumeration SUBJECT_TOKEN_TYPES
Index
Enumeration Members
Enumeration SUBJECT_TOKEN_TYPES
Index
Enumeration Members
Enumeration Members
SUBJECT_
SUBJECT_
SUBJECT_
Function getAccessToken
    options: AccessTokenOptions & { includeFullResponse: true },
): Promise<AccessTokenResponse>Function getAccessToken
    options: AccessTokenOptions & { includeFullResponse: true },
): Promise<AccessTokenResponse>Parameters
Returns Promise<AccessTokenResponse>
includeFullResponse is true.Returns Promise<AccessTokenResponse>
includeFullResponse is true.
    options?: AccessTokenOptions & { includeFullResponse?: false },
): Promise<string>
    options?: AccessTokenOptions & { includeFullResponse?: false },
): Promise<string>Parameters
Optionaloptions: AccessTokenOptions & { includeFullResponse?: false }Returns Promise<string>
includeFullResponse is true.Function useUser
    error: Error;
    invalidate: () => Promise<User | undefined>;
    isLoading: boolean;
    user: null;
}
| {
    error: null;
    invalidate: () => Promise<User | undefined>;
    isLoading: boolean;
    user: User;
}
| {
    error: undefined;
    invalidate: () => Promise<User | undefined>;
    isLoading: boolean;
    user: undefined;
}Returns
    | {
        error: Error;
        invalidate: () => Promise<User | undefined>;
        isLoading: boolean;
        user: null;
    }
    | {
        error: null;
        invalidate: () => Promise<User | undefined>;
        isLoading: boolean;
        user: User;
    }
    | {
        error: undefined;
        invalidate: () => Promise<User | undefined>;
        isLoading: boolean;
        user: undefined;
    }Function useUser
    error: Error;
    invalidate: () => Promise<User | undefined>;
    isLoading: boolean;
    user: null;
}
| {
    error: null;
    invalidate: () => Promise<User | undefined>;
    isLoading: boolean;
    user: User;
}
| {
    error: undefined;
    invalidate: () => Promise<User | undefined>;
    isLoading: boolean;
    user: undefined;
}Returns
    | {
        error: Error;
        invalidate: () => Promise<User | undefined>;
        isLoading: boolean;
        user: null;
    }
    | {
        error: null;
        invalidate: () => Promise<User | undefined>;
        isLoading: boolean;
        user: User;
    }
    | {
        error: undefined;
        invalidate: () => Promise<User | undefined>;
        isLoading: boolean;
        user: undefined;
    }Function filterDefaultIdTokenClaims
Function filterDefaultIdTokenClaims
Parameters
Returns User
Function generateDpopKeyPair
Function generateDpopKeyPair
Function generateSessionCookie
    session: Partial<SessionData>,
    config: GenerateSessionCookieConfig,
): Promise<string>Parameters
Returns Promise<string>
Function generateSessionCookie
    session: Partial<SessionData>,
    config: GenerateSessionCookieConfig,
): Promise<string>Parameters
Returns Promise<string>
@auth0/nextjs-auth0 - v4.18.0
Hierarchy Summary
@auth0/nextjs-auth0 - v4.19.0
Hierarchy Summary
@auth0/nextjs-auth0 - v4.18.0

@auth0/nextjs-auth0 - v4.19.0

Documentation
-
+
Documentation
-Getting Started
-1. Install the SDK
-npm i @auth0/nextjs-auth0
+Getting Started
1. Install the SDK
npm i @auth0/nextjs-auth0
2. Add the environment variables
-.env.local file:2. Add the environment variables
.env.local file:AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=
@@ -42,8 +38,7 @@ 2. Add the envi
Dynamic base URLs (Preview deployments)
-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.Dynamic base URLs (Preview deployments)
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.appBaseUrl or APP_BASE_URL to a single absolute URL. Comma-separated values are not supported.Dynamic b
When relying on dynamic base URLs in production, the SDK enforces secure cookies. If you explicitly set AUTH0_COOKIE_SECURE=false, session.cookie.secure=false, or transactionCookie.secure=false, the SDK throws InvalidConfigurationError.3. Create the Auth0 SDK client
-3. Create the Auth0 SDK client
lib/auth0.ts:
@@ -66,19 +60,16 @@ import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client();
3. Create the Aut
4. Add the authentication middleware
-
+4. Add the authentication middleware
Follow the setup below depending on your Next.js version.🟦 On Next.js 15
-middleware.ts file in the root of your project:🟦 On Next.js 15
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.🟨 On Next.js 16
-🟨 On Next.js 16
🟨 On Next.js 16
You must use <a> tags instead of the <Link> component to ensure that the routing is not done client-side as that may result in some unexpected behavior.Customizing the client
-Customizing the client
-
@@ -238,14 +228,18 @@
Customizing the clientConfigure DPoP timing validation. Supports
clockSkew (adjust assumed current time) and clockTolerance (validation tolerance). Can also be configured via AUTH0_DPOP_CLOCK_SKEW and AUTH0_DPOP_CLOCK_TOLERANCE environment variables. See DPoP Clock Validation for details.
+
+cspNonce
+
+stringCSP 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
DiscoveryCacheOptionsConfigure the OIDC discovery metadata cache for Multiple Custom Domains. Controls TTL and maximum cached issuers.
Customizing Auth Handlers
-Customizing Auth Handlers
onCallback hook to add custom logic after authentication completesCustomizing Auth Hand
When customizing auth handlers, always validate user inputs (especially redirect URLs) to prevent security vulnerabilities like open redirects. Use relative URLs when possible and implement proper input sanitization.
Session Cookie Configuration
-Session Cookie Configuration
-AUTH0_COOKIE_DOMAIN=
AUTH0_COOKIE_PATH=
AUTH0_COOKIE_TRANSIENT=
@@ -273,10 +266,8 @@ Session Cookie Con
AUTH0_DPOP_CLOCK_TOLERANCE=
DPoP Configuration
-Quick Start
-DPoP Configuration
Quick Start
-# Enable DPoP and provide ES256 key pair
AUTH0_DPOP_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
@@ -293,16 +284,14 @@ Quick Start
import { 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
}
}
});
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" })
});
+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" })
});
createFetcher automatically inherit the global DPoP configuration from your Auth0Client instance.Advanced: Clock Validation Configuration
-Advanced: Clock Validation Configuration
@@ -312,36 +301,30 @@ 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
}
});
Advance
Proxy Handler for My Account and My Organization APIs
-How It Works
-/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:Proxy Handler for My Account and My Organization APIs
How It Works
/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:
-Configuration
-Configuration
-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"
}
}
});
Client-Side Usage
-Client-Side Usage
// 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" }
});
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.Base Path
-/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.Base Path
/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.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.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).Configuration Validation
-Auth0Client. The following options are mandatory and must be provided either through constructor options or environment variables:Configuration Validation
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)Configuration Validati
appBaseUrl is optional; if omitted, the SDK will infer it from the request host at runtime.Multiple Custom Domains (MCD)
-DomainResolver function as the domain option to enable per-request domain resolution:Multiple Custom Domains (MCD)
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";
}
});
Routes
-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 URLsRoutes
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.Feedback
-Contributing
-Feedback
Contributing
-Raise an issue
-Vulnerability Reporting
-What is Auth0?
-Raise an issue
Vulnerability Reporting
What is Auth0?
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