Auth0Client is the main entry point for implementing Auth0 authentication in Next.js applications. It provides methods for managing authentication flows, sessions, and access tokens.
Constructor
Configuration Options
All configuration options are optional and can be provided via constructor options or environment variables.Authorization Server Configuration
The Auth0 domain for the tenant (e.g.,
example.us.auth0.com).Environment Variable: AUTH0_DOMAINThe Auth0 client ID.Environment Variable:
AUTH0_CLIENT_IDThe Auth0 client secret.Environment Variable:
AUTH0_CLIENT_SECRETNote: Either clientSecret or clientAssertionSigningKey is required for client authentication.Additional parameters to send to the
/authorize endpoint.If enabled, the SDK will use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server.
Private key for use with
private_key_jwt clients. This should be a string that is the contents of a PEM file or a CryptoKey.Environment Variable: AUTH0_CLIENT_ASSERTION_SIGNING_KEYThe algorithm used to sign the client assertion JWT. Uses one of
token_endpoint_auth_signing_alg_values_supported if not specified.Environment Variable: AUTH0_CLIENT_ASSERTION_SIGNING_ALGApplication Configuration
The 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).Environment Variable: APP_BASE_URL (comma-separated for multiple origins)If not specified, the SDK will infer it from the request host at runtime.A 32-byte, hex-encoded secret used for encrypting cookies.Environment Variable:
AUTH0_SECRETRequiredThe path to redirect the user to after successfully authenticating.
Session Configuration
Configure the session timeouts and whether to use rolling sessions or not.See Session configuration for additional details.
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.The absolute duration after which the session will expire (in seconds). Default: 3 days (259200 seconds).
The duration of inactivity after which the session will expire (in seconds). Default: 1 day (86400 seconds).
Options for the session cookie.
The name of the session cookie.
The secure attribute of the session cookie. Defaults based on the protocol of the application’s base URL.Environment Variable:
AUTH0_COOKIE_SECUREThe sameSite attribute of the session cookie.Environment Variable:
AUTH0_COOKIE_SAME_SITEThe path attribute of the session cookie.Environment Variable:
AUTH0_COOKIE_PATHThe domain attribute of the session cookie.Environment Variable:
AUTH0_COOKIE_DOMAINWhen true, the cookie will not persist beyond the current session.Environment Variable:
AUTH0_COOKIE_TRANSIENTTransaction Cookie Configuration
Configure the transaction cookie used to store the state of the authentication transaction.
The prefix of the cookie used to store the transaction state.
The secure attribute of the transaction cookie. Defaults based on the protocol of the application’s base URL.
The sameSite attribute of the transaction cookie.
The path attribute of the transaction cookie.
The expiration time for transaction cookies in seconds. Default: 1 hour (3600 seconds).
Enable support for multiple concurrent authentication flows by using unique transaction cookies per flow.
Logout Configuration
Configure the logout strategy to use.
'auto': Attempts OIDC RP-Initiated Logout first, falls back to/v2/logoutif not supported'oidc': Always uses OIDC RP-Initiated Logout (requires RP-Initiated Logout to be enabled)'v2': Always uses the Auth0/v2/logoutendpoint (supports wildcards in allowed logout URLs)
Configure 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.Alternative approach: Set to false if your application cannot securely store ID tokens. When disabled, only logout_hint (session ID), client_id, and post_logout_redirect_uri are sent.Hooks
A method to manipulate the session before persisting it.See beforeSessionSaved for additional details.
A method to handle errors or manage redirects after attempting to authenticate.See onCallback for additional details.
Custom Session Store
A custom session store implementation used to persist sessions to a data store.See Database sessions for additional details.
Routes Configuration
Configure the paths for the authentication routes.See Custom routes for additional details.
Advanced Configuration
Allow 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.Note: This option can only be used when
NODE_ENV is not set to production.Integer value for the HTTP timeout in milliseconds for authentication requests.
Boolean value to opt-out of sending the library name and version to your authorization server via the
Auth0-Client header.Boolean value to enable the
/auth/access-token endpoint for use in the client app.Note: Set this to false if your client does not need to directly interact with resource servers (Token Mediating Backend). A security best practice is to disable this to avoid exposing access tokens to the client app.Number of seconds to refresh access tokens early when calling
getAccessToken. This is a server-side buffer applied to token expiration checks.If true, the profile endpoint will return a 204 No Content response when the user is not authenticated instead of returning a 401 Unauthorized response.
If true, the
/auth/connect endpoint will be mounted to enable users to connect additional accounts.DPoP Configuration
Enable DPoP (Demonstrating Proof-of-Possession) for enhanced OAuth 2.0 security.When enabled, the SDK will:
- Generate DPoP proofs for token requests and protected resource requests
- Bind access tokens cryptographically to the client’s key pair
- Prevent token theft and replay attacks
- Handle DPoP nonce errors with automatic retry logic
ES256 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.Configuration options for DPoP timing validation and retry behavior.Environment Variables:
AUTH0_DPOP_CLOCK_SKEWAUTH0_DPOP_CLOCK_TOLERANCEAUTH0_RETRY_DELAYAUTH0_RETRY_JITTER
MFA Configuration
MFA context TTL in seconds. Controls how long encrypted mfa_token remains valid.Environment Variable:
AUTH0_MFA_TOKEN_TTLDefault: 300 seconds (5 minutes, matching Auth0’s mfa_token expiration)Methods
middleware
The incoming request object.
Returns a NextResponse that handles the authentication route or passes through to the next middleware.
getSession
The request object. Required for Pages Router and middleware usage. Optional for App Router.
Returns the session data or
null if the user is not authenticated.SessionData Properties:user: User object with claims from the ID tokentokenSet: Token set containing access token, ID token, and refresh tokenaccessTokens: Array of access tokens for different audiences (MRRT)internal: Internal session metadata (sid, createdAt)
getAccessToken
Note: Server Components cannot set cookies. Calling
getAccessToken() in a Server Component will cause the access token to be refreshed, if it is expired, and the updated token set will not be persisted. It is recommended to call getAccessToken(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.The request object. Required for Pages Router and middleware usage.
The response object. Required for Pages Router and middleware usage.
Optional configuration for getting the access token.
Force a refresh of the access token.
The scope to request for the access token.
The audience to request for the access token.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).
The access token.
The time at which the access token expires (seconds since epoch).
The scope granted for the access token.
The type of the access token (e.g., “Bearer”, “DPoP”).
The audience for the access token.
AccessTokenErrorwith codeMISSING_SESSIONif the user does not have an active sessionMfaRequiredErrorif MFA is required for the token request
getAccessTokenForConnection
Options for retrieving an access token for a connection.
The connection name.
The request object (Pages Router only).
The response object (Pages Router only).
The access token for the connection.
The time at which the access token expires (seconds since epoch).
The scope granted for the access token.
AccessTokenForConnectionErrorwith codeMISSING_SESSIONif the user does not have an active session
customTokenExchange
The custom token exchange options.
The external token to exchange.
The token type of the subject token (e.g., ‘urn:acme:legacy-token’).
The audience for the requested token.
The scope to request for the token.
The access token.
The ID token (if requested).
The refresh token (if requested).
CustomTokenExchangeErrorif validation fails or the exchange request fails
updateSession
The request object (Pages Router only).
The response object (Pages Router only).
The updated session data.
Errorif the user is not authenticatedErrorif the session data is missing
startInteractiveLogin
Options for the interactive login.
Returns a NextResponse that redirects to the authorization server.
getTokenByBackchannelAuth
The backchannel authentication options.
Human-readable message to be displayed at the consumption device and authentication device.
The login hint to inform which user to use.
Set a custom expiry time for the CIBA flow in seconds. Defaults to 300 seconds (5 minutes) if not set.
The token set containing access token, ID token, and refresh token.
The ID token claims.
connectAccount
Options for connecting an account.
Returns a NextResponse that redirects to the authorization server.
ConnectAccountErrorwith codeMISSING_SESSIONif the user does not have an active session
createFetcher
- Automatic access token retrieval and injection
- DPoP (Demonstrating Proof-of-Possession) proof generation when enabled
- Token refresh and session management
- Error handling and retry logic for DPoP nonce errors
- Base URL resolution for relative requests
Request object for session context (required for Pages Router, optional for App Router).
Enable DPoP for this fetcher instance (overrides global setting).
Custom access token factory function. If not provided, uses the default from hooks.
Base URL for relative requests. Must be provided if using relative URLs.
Custom fetch implementation. Falls back to global fetch if not provided.
Returns a configured Fetcher instance.
AccessTokenErrorwith codeMISSING_SESSIONwhen no active session exists
withPageAuthRequired
withApiAuthRequired
mfa
getAuthenticators: List enrolled MFA factorschallenge: Initiate MFA challenge (OTP/OOB)verify: Complete MFA verification