Skip to main content
The 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

import { Auth0Client } from '@auth0/nextjs-auth0/server';

const auth0 = new Auth0Client(options?: Auth0ClientOptions);

Configuration Options

All configuration options are optional and can be provided via constructor options or environment variables.

Authorization Server Configuration

domain
string
The Auth0 domain for the tenant (e.g., example.us.auth0.com).Environment Variable: AUTH0_DOMAIN
clientId
string
The Auth0 client ID.Environment Variable: AUTH0_CLIENT_ID
clientSecret
string
The Auth0 client secret.Environment Variable: AUTH0_CLIENT_SECRETNote: Either clientSecret or clientAssertionSigningKey is required for client authentication.
authorizationParameters
AuthorizationParameters
Additional parameters to send to the /authorize endpoint.
pushedAuthorizationRequests
boolean
If enabled, the SDK will use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server.
clientAssertionSigningKey
string | CryptoKey
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_KEY
clientAssertionSigningAlg
string
The 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_ALG

Application Configuration

appBaseUrl
string | string[]
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.
secret
string
A 32-byte, hex-encoded secret used for encrypting cookies.Environment Variable: AUTH0_SECRETRequired
signInReturnToPath
string
default:"/"
The path to redirect the user to after successfully authenticating.

Session Configuration

session
SessionConfiguration
Configure the session timeouts and whether to use rolling sessions or not.See Session configuration for additional details.
session.rolling
boolean
default:true
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.
session.absoluteDuration
number
default:259200
The absolute duration after which the session will expire (in seconds). Default: 3 days (259200 seconds).
session.inactivityDuration
number
default:86400
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_SECURE
The sameSite attribute of the session cookie.Environment Variable: AUTH0_COOKIE_SAME_SITE
The path attribute of the session cookie.Environment Variable: AUTH0_COOKIE_PATH
The domain attribute of the session cookie.Environment Variable: AUTH0_COOKIE_DOMAIN
When true, the cookie will not persist beyond the current session.Environment Variable: AUTH0_COOKIE_TRANSIENT
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).
enableParallelTransactions
boolean
default:true
Enable support for multiple concurrent authentication flows by using unique transaction cookies per flow.

Logout Configuration

logoutStrategy
'auto' | 'oidc' | 'v2'
default:"auto"
Configure the logout strategy to use.
  • 'auto': 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)
includeIdTokenHintInOIDCLogoutUrl
boolean
default:true
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

beforeSessionSaved
BeforeSessionSavedHook
A method to manipulate the session before persisting it.See beforeSessionSaved for additional details.
onCallback
OnCallbackHook
A method to handle errors or manage redirects after attempting to authenticate.See onCallback for additional details.

Custom Session Store

sessionStore
SessionDataStore
A custom session store implementation used to persist sessions to a data store.See Database sessions for additional details.

Routes Configuration

routes
RoutesOptions
Configure the paths for the authentication routes.See Custom routes for additional details.

Advanced Configuration

allowInsecureRequests
boolean
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.
httpTimeout
number
default:5000
Integer value for the HTTP timeout in milliseconds for authentication requests.
enableTelemetry
boolean
default:true
Boolean value to opt-out of sending the library name and version to your authorization server via the Auth0-Client header.
enableAccessTokenEndpoint
boolean
default:true
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.
tokenRefreshBuffer
number
default:0
Number of seconds to refresh access tokens early when calling getAccessToken. This is a server-side buffer applied to token expiration checks.
noContentProfileResponseWhenUnauthenticated
boolean
default:false
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.
enableConnectAccountEndpoint
boolean
If true, the /auth/connect endpoint will be mounted to enable users to connect additional accounts.

DPoP Configuration

useDPoP
boolean
default:false
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
dpopKeyPair
DpopKeyPair
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.
dpopOptions
DpopOptions
Configuration options for DPoP timing validation and retry behavior.Environment Variables:
  • AUTH0_DPOP_CLOCK_SKEW
  • AUTH0_DPOP_CLOCK_TOLERANCE
  • AUTH0_RETRY_DELAY
  • AUTH0_RETRY_JITTER

MFA Configuration

mfaTokenTtl
number
default:300
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

middleware(req: Request | NextRequest): Promise<NextResponse>
Mounts the SDK routes to run as a middleware function.
req
Request | NextRequest
required
The incoming request object.
response
Promise<NextResponse>
Returns a NextResponse that handles the authentication route or passes through to the next middleware.

getSession

// App Router: Server Components, Server Actions, Route Handlers
getSession(): Promise<SessionData | null>

// Pages Router: middleware, getServerSideProps, API routes
getSession(req: PagesRouterRequest | NextRequest): Promise<SessionData | null>
Returns the session data for the current request.
req
PagesRouterRequest | NextRequest
The request object. Required for Pages Router and middleware usage. Optional for App Router.
session
Promise<SessionData | null>
Returns the session data or null if the user is not authenticated.SessionData Properties:
  • user: User object with claims from the ID token
  • tokenSet: Token set containing access token, ID token, and refresh token
  • accessTokens: Array of access tokens for different audiences (MRRT)
  • internal: Internal session metadata (sid, createdAt)

getAccessToken

// App Router: Server Components, Server Actions, Route Handlers
getAccessToken(options?: GetAccessTokenOptions): Promise<{
  token: string;
  expiresAt: number;
  scope?: string;
  token_type?: string;
  audience?: string;
}>

// Pages Router: middleware, getServerSideProps, API routes
getAccessToken(
  req: PagesRouterRequest | NextRequest,
  res: PagesRouterResponse | NextResponse,
  options?: GetAccessTokenOptions
): Promise<{
  token: string;
  expiresAt: number;
  scope?: string;
  token_type?: string;
  audience?: string;
}>
Returns the access token. Automatically refreshes the token if it is expired and a refresh token is available.
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.
req
PagesRouterRequest | NextRequest
The request object. Required for Pages Router and middleware usage.
res
PagesRouterResponse | NextResponse
The response object. Required for Pages Router and middleware usage.
options
GetAccessTokenOptions
Optional configuration for getting the access token.
options.refresh
boolean
Force a refresh of the access token.
options.scope
string
The scope to request for the access token.
options.audience
string
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).
token
string
The access token.
expiresAt
number
The time at which the access token expires (seconds since epoch).
scope
string
The scope granted for the access token.
token_type
string
The type of the access token (e.g., “Bearer”, “DPoP”).
audience
string
The audience for the access token.
Throws:
  • AccessTokenError with code MISSING_SESSION if the user does not have an active session
  • MfaRequiredError if MFA is required for the token request

getAccessTokenForConnection

// App Router
getAccessTokenForConnection(
  options: AccessTokenForConnectionOptions
): Promise<{ token: string; expiresAt: number }>

// Pages Router
getAccessTokenForConnection(
  options: AccessTokenForConnectionOptions,
  req: PagesRouterRequest | NextRequest | Request | undefined,
  res: PagesRouterResponse | NextResponse | undefined
): Promise<{ token: string; expiresAt: number }>
Retrieves an access token for a connection.
options
AccessTokenForConnectionOptions
required
Options for retrieving an access token for a connection.
options.connection
string
required
The connection name.
req
PagesRouterRequest | NextRequest | Request
The request object (Pages Router only).
res
PagesRouterResponse | NextResponse
The response object (Pages Router only).
token
string
The access token for the connection.
expiresAt
number
The time at which the access token expires (seconds since epoch).
scope
string
The scope granted for the access token.
Throws:
  • AccessTokenForConnectionError with code MISSING_SESSION if the user does not have an active session

customTokenExchange

customTokenExchange(
  options: CustomTokenExchangeOptions
): Promise<CustomTokenExchangeResponse>
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.
options
CustomTokenExchangeOptions
required
The custom token exchange options.
options.subjectToken
string
required
The external token to exchange.
options.subjectTokenType
string
required
The token type of the subject token (e.g., ‘urn:acme:legacy-token’).
options.audience
string
The audience for the requested token.
options.scope
string
The scope to request for the token.
accessToken
string
The access token.
idToken
string
The ID token (if requested).
refreshToken
string
The refresh token (if requested).
Throws:
  • CustomTokenExchangeError if validation fails or the exchange request fails

updateSession

// App Router: Server Actions, Route Handlers
updateSession(session: SessionData): Promise<void>

// Pages Router: middleware, getServerSideProps, API routes
updateSession(
  req: PagesRouterRequest | NextRequest | Request,
  res: PagesRouterResponse | NextResponse | Response,
  session: SessionData
): Promise<void>
Updates the session of the currently authenticated user. If the user does not have a session, an error is thrown.
req
PagesRouterRequest | NextRequest | Request
The request object (Pages Router only).
res
PagesRouterResponse | NextResponse | Response
The response object (Pages Router only).
session
SessionData
required
The updated session data.
Throws:
  • Error if the user is not authenticated
  • Error if the session data is missing

startInteractiveLogin

startInteractiveLogin(
  options?: StartInteractiveLoginOptions
): Promise<NextResponse>
Starts an interactive login flow.
options
StartInteractiveLoginOptions
Options for the interactive login.
response
Promise<NextResponse>
Returns a NextResponse that redirects to the authorization server.

getTokenByBackchannelAuth

getTokenByBackchannelAuth(
  options: BackchannelAuthenticationOptions
): Promise<BackchannelAuthenticationResponse>
Authenticates using Client-Initiated Backchannel Authentication and returns the token set. This method will initialize the backchannel authentication process with Auth0, and poll the token endpoint until the authentication is complete.
options
BackchannelAuthenticationOptions
required
The backchannel authentication options.
options.bindingMessage
string
required
Human-readable message to be displayed at the consumption device and authentication device.
options.loginHint
{ sub: string }
required
The login hint to inform which user to use.
options.requestedExpiry
number
Set a custom expiry time for the CIBA flow in seconds. Defaults to 300 seconds (5 minutes) if not set.
tokenSet
TokenSet
The token set containing access token, ID token, and refresh token.
idTokenClaims
object
The ID token claims.

connectAccount

connectAccount(
  options: ConnectAccountOptions
): Promise<NextResponse>
Initiates the Connect Account flow to connect a third-party account to the user’s profile.
options
ConnectAccountOptions
required
Options for connecting an account.
response
Promise<NextResponse>
Returns a NextResponse that redirects to the authorization server.
Throws:
  • ConnectAccountError with code MISSING_SESSION if the user does not have an active session

createFetcher

createFetcher<TOutput extends Response = Response>(
  req: PagesRouterRequest | NextRequest | Request | undefined,
  options: {
    useDPoP?: boolean;
    getAccessToken?: AccessTokenFactory;
    baseUrl?: string;
    fetch?: CustomFetchImpl<TOutput>;
  }
): Promise<Fetcher<TOutput>>
Creates a configured Fetcher instance for making authenticated API requests. This method creates a specialized HTTP client that handles:
  • 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
req
PagesRouterRequest | NextRequest | Request
Request object for session context (required for Pages Router, optional for App Router).
options.useDPoP
boolean
Enable DPoP for this fetcher instance (overrides global setting).
options.getAccessToken
AccessTokenFactory
Custom access token factory function. If not provided, uses the default from hooks.
options.baseUrl
string
Base URL for relative requests. Must be provided if using relative URLs.
options.fetch
CustomFetchImpl<TOutput>
Custom fetch implementation. Falls back to global fetch if not provided.
fetcher
Promise<Fetcher<TOutput>>
Returns a configured Fetcher instance.
Throws:
  • AccessTokenError with code MISSING_SESSION when no active session exists

withPageAuthRequired

// App Router
withPageAuthRequired(
  Component: AppRouterPageRoute,
  opts?: WithPageAuthRequiredAppRouterOptions
): AppRouterPageRoute

// Pages Router
withPageAuthRequired(
  opts?: WithPageAuthRequiredPageRouterOptions
): PageRoute
Protects a page route by requiring authentication.

withApiAuthRequired

withApiAuthRequired(
  apiRoute: AppRouteHandlerFn | NextApiHandler
): (req, res) => Promise<Response>
Protects an API route by requiring authentication.

mfa

get mfa(): ServerMfaClient
MFA API for server-side operations. Provides access to MFA methods that require encrypted mfa_token from MfaRequiredError:
  • getAuthenticators: List enrolled MFA factors
  • challenge: Initiate MFA challenge (OTP/OOB)
  • verify: Complete MFA verification

Example Usage

import { Auth0Client } from '@auth0/nextjs-auth0/server';

// Create an instance
export const auth0 = new Auth0Client({
  domain: process.env.AUTH0_DOMAIN,
  clientId: process.env.AUTH0_CLIENT_ID,
  clientSecret: process.env.AUTH0_CLIENT_SECRET,
  secret: process.env.AUTH0_SECRET,
  appBaseUrl: process.env.APP_BASE_URL,
  session: {
    rolling: true,
    absoluteDuration: 60 * 60 * 24 * 7, // 7 days
    inactivityDuration: 60 * 60 * 24 // 1 day
  }
});

// Use in middleware
export async function middleware(request: NextRequest) {
  return await auth0.middleware(request);
}

// Get session in App Router
export default async function Page() {
  const session = await auth0.getSession();
  
  if (!session) {
    return <div>Not authenticated</div>;
  }
  
  return <div>Welcome, {session.user.name}!</div>;
}

// Get access token in API route
export async function GET(request: NextRequest) {
  try {
    const { token } = await auth0.getAccessToken();
    
    // Use the token to call an API
    const response = await fetch('https://api.example.com/data', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    
    return Response.json(await response.json());
  } catch (error) {
    if (error instanceof MfaRequiredError) {
      // Handle MFA required scenario
      return Response.json({ error: 'MFA required' }, { status: 401 });
    }
    throw error;
  }
}

Build docs developers (and LLMs) love