> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/auth0/nextjs-auth0/llms.txt
> Use this file to discover all available pages before exploring further.

# Auth0Client

> Main SDK client for server-side authentication in Next.js applications

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

```typescript theme={null}
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

<ParamField path="domain" type="string">
  The Auth0 domain for the tenant (e.g., `example.us.auth0.com`).

  **Environment Variable:** `AUTH0_DOMAIN`
</ParamField>

<ParamField path="clientId" type="string">
  The Auth0 client ID.

  **Environment Variable:** `AUTH0_CLIENT_ID`
</ParamField>

<ParamField path="clientSecret" type="string">
  The Auth0 client secret.

  **Environment Variable:** `AUTH0_CLIENT_SECRET`

  **Note:** Either `clientSecret` or `clientAssertionSigningKey` is required for client authentication.
</ParamField>

<ParamField path="authorizationParameters" type="AuthorizationParameters">
  Additional parameters to send to the `/authorize` endpoint.
</ParamField>

<ParamField path="pushedAuthorizationRequests" type="boolean">
  If enabled, the SDK will use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server.
</ParamField>

<ParamField path="clientAssertionSigningKey" type="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`
</ParamField>

<ParamField path="clientAssertionSigningAlg" type="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`
</ParamField>

#### Application Configuration

<ParamField path="appBaseUrl" type="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.
</ParamField>

<ParamField path="secret" type="string">
  A 32-byte, hex-encoded secret used for encrypting cookies.

  **Environment Variable:** `AUTH0_SECRET`

  **Required**
</ParamField>

<ParamField path="signInReturnToPath" type="string" default="/">
  The path to redirect the user to after successfully authenticating.
</ParamField>

#### Session Configuration

<ParamField path="session" type="SessionConfiguration">
  Configure the session timeouts and whether to use rolling sessions or not.

  See [Session configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#session-configuration) for additional details.
</ParamField>

<ParamField path="session.rolling" type="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.
</ParamField>

<ParamField path="session.absoluteDuration" type="number" default={259200}>
  The absolute duration after which the session will expire (in seconds). Default: 3 days (259200 seconds).
</ParamField>

<ParamField path="session.inactivityDuration" type="number" default={86400}>
  The duration of inactivity after which the session will expire (in seconds). Default: 1 day (86400 seconds).
</ParamField>

<ParamField path="session.cookie" type="SessionCookieOptions">
  Options for the session cookie.
</ParamField>

<ParamField path="session.cookie.name" type="string" default="__session">
  The name of the session cookie.
</ParamField>

<ParamField path="session.cookie.secure" type="boolean">
  The secure attribute of the session cookie. Defaults based on the protocol of the application's base URL.

  **Environment Variable:** `AUTH0_COOKIE_SECURE`
</ParamField>

<ParamField path="session.cookie.sameSite" type="'strict' | 'lax' | 'none'" default="lax">
  The sameSite attribute of the session cookie.

  **Environment Variable:** `AUTH0_COOKIE_SAME_SITE`
</ParamField>

<ParamField path="session.cookie.path" type="string" default="/">
  The path attribute of the session cookie.

  **Environment Variable:** `AUTH0_COOKIE_PATH`
</ParamField>

<ParamField path="session.cookie.domain" type="string">
  The domain attribute of the session cookie.

  **Environment Variable:** `AUTH0_COOKIE_DOMAIN`
</ParamField>

<ParamField path="session.cookie.transient" type="boolean">
  When true, the cookie will not persist beyond the current session.

  **Environment Variable:** `AUTH0_COOKIE_TRANSIENT`
</ParamField>

#### Transaction Cookie Configuration

<ParamField path="transactionCookie" type="TransactionCookieOptions">
  Configure the transaction cookie used to store the state of the authentication transaction.
</ParamField>

<ParamField path="transactionCookie.prefix" type="string" default="__txn_">
  The prefix of the cookie used to store the transaction state.
</ParamField>

<ParamField path="transactionCookie.secure" type="boolean">
  The secure attribute of the transaction cookie. Defaults based on the protocol of the application's base URL.
</ParamField>

<ParamField path="transactionCookie.sameSite" type="'strict' | 'lax' | 'none'" default="lax">
  The sameSite attribute of the transaction cookie.
</ParamField>

<ParamField path="transactionCookie.path" type="string" default="/">
  The path attribute of the transaction cookie.
</ParamField>

<ParamField path="transactionCookie.maxAge" type="number" default={3600}>
  The expiration time for transaction cookies in seconds. Default: 1 hour (3600 seconds).
</ParamField>

<ParamField path="enableParallelTransactions" type="boolean" default={true}>
  Enable support for multiple concurrent authentication flows by using unique transaction cookies per flow.
</ParamField>

#### Logout Configuration

<ParamField path="logoutStrategy" type="'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)
</ParamField>

<ParamField path="includeIdTokenHintInOIDCLogoutUrl" type="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.
</ParamField>

#### Hooks

<ParamField path="beforeSessionSaved" type="BeforeSessionSavedHook">
  A method to manipulate the session before persisting it.

  See [beforeSessionSaved](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#beforesessionsaved) for additional details.
</ParamField>

<ParamField path="onCallback" type="OnCallbackHook">
  A method to handle errors or manage redirects after attempting to authenticate.

  See [onCallback](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#oncallback) for additional details.
</ParamField>

#### Custom Session Store

<ParamField path="sessionStore" type="SessionDataStore">
  A custom session store implementation used to persist sessions to a data store.

  See [Database sessions](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#database-sessions) for additional details.
</ParamField>

#### Routes Configuration

<ParamField path="routes" type="RoutesOptions">
  Configure the paths for the authentication routes.

  See [Custom routes](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#custom-routes) for additional details.
</ParamField>

#### Advanced Configuration

<ParamField path="allowInsecureRequests" type="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`.
</ParamField>

<ParamField path="httpTimeout" type="number" default={5000}>
  Integer value for the HTTP timeout in milliseconds for authentication requests.
</ParamField>

<ParamField path="enableTelemetry" type="boolean" default={true}>
  Boolean value to opt-out of sending the library name and version to your authorization server via the `Auth0-Client` header.
</ParamField>

<ParamField path="enableAccessTokenEndpoint" type="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.
</ParamField>

<ParamField path="tokenRefreshBuffer" type="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.
</ParamField>

<ParamField path="noContentProfileResponseWhenUnauthenticated" type="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.
</ParamField>

<ParamField path="enableConnectAccountEndpoint" type="boolean">
  If true, the `/auth/connect` endpoint will be mounted to enable users to connect additional accounts.
</ParamField>

#### DPoP Configuration

<ParamField path="useDPoP" type="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
</ParamField>

<ParamField path="dpopKeyPair" type="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`.
</ParamField>

<ParamField path="dpopOptions" type="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`
</ParamField>

#### MFA Configuration

<ParamField path="mfaTokenTtl" type="number" default={300}>
  MFA context TTL in seconds. Controls how long encrypted mfa\_token remains valid.

  **Environment Variable:** `AUTH0_MFA_TOKEN_TTL`

  Default: 300 seconds (5 minutes, matching Auth0's mfa\_token expiration)
</ParamField>

## Methods

### middleware

```typescript theme={null}
middleware(req: Request | NextRequest): Promise<NextResponse>
```

Mounts the SDK routes to run as a middleware function.

<ParamField path="req" type="Request | NextRequest" required>
  The incoming request object.
</ParamField>

<ResponseField name="response" type="Promise<NextResponse>">
  Returns a NextResponse that handles the authentication route or passes through to the next middleware.
</ResponseField>

### getSession

```typescript theme={null}
// 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.

<ParamField path="req" type="PagesRouterRequest | NextRequest">
  The request object. Required for Pages Router and middleware usage. Optional for App Router.
</ParamField>

<ResponseField name="session" type="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)
</ResponseField>

### getAccessToken

```typescript theme={null}
// 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.

<Info>
  **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.
</Info>

<ParamField path="req" type="PagesRouterRequest | NextRequest">
  The request object. Required for Pages Router and middleware usage.
</ParamField>

<ParamField path="res" type="PagesRouterResponse | NextResponse">
  The response object. Required for Pages Router and middleware usage.
</ParamField>

<ParamField path="options" type="GetAccessTokenOptions">
  Optional configuration for getting the access token.
</ParamField>

<ParamField path="options.refresh" type="boolean">
  Force a refresh of the access token.
</ParamField>

<ParamField path="options.scope" type="string">
  The scope to request for the access token.
</ParamField>

<ParamField path="options.audience" type="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).
</ParamField>

<ResponseField name="token" type="string">
  The access token.
</ResponseField>

<ResponseField name="expiresAt" type="number">
  The time at which the access token expires (seconds since epoch).
</ResponseField>

<ResponseField name="scope" type="string">
  The scope granted for the access token.
</ResponseField>

<ResponseField name="token_type" type="string">
  The type of the access token (e.g., "Bearer", "DPoP").
</ResponseField>

<ResponseField name="audience" type="string">
  The audience for the access token.
</ResponseField>

**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

```typescript theme={null}
// 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.

<ParamField path="options" type="AccessTokenForConnectionOptions" required>
  Options for retrieving an access token for a connection.
</ParamField>

<ParamField path="options.connection" type="string" required>
  The connection name.
</ParamField>

<ParamField path="req" type="PagesRouterRequest | NextRequest | Request">
  The request object (Pages Router only).
</ParamField>

<ParamField path="res" type="PagesRouterResponse | NextResponse">
  The response object (Pages Router only).
</ParamField>

<ResponseField name="token" type="string">
  The access token for the connection.
</ResponseField>

<ResponseField name="expiresAt" type="number">
  The time at which the access token expires (seconds since epoch).
</ResponseField>

<ResponseField name="scope" type="string">
  The scope granted for the access token.
</ResponseField>

**Throws:**

* `AccessTokenForConnectionError` with code `MISSING_SESSION` if the user does not have an active session

### customTokenExchange

```typescript theme={null}
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.

<ParamField path="options" type="CustomTokenExchangeOptions" required>
  The custom token exchange options.
</ParamField>

<ParamField path="options.subjectToken" type="string" required>
  The external token to exchange.
</ParamField>

<ParamField path="options.subjectTokenType" type="string" required>
  The token type of the subject token (e.g., 'urn:acme:legacy-token').
</ParamField>

<ParamField path="options.audience" type="string">
  The audience for the requested token.
</ParamField>

<ParamField path="options.scope" type="string">
  The scope to request for the token.
</ParamField>

<ResponseField name="accessToken" type="string">
  The access token.
</ResponseField>

<ResponseField name="idToken" type="string">
  The ID token (if requested).
</ResponseField>

<ResponseField name="refreshToken" type="string">
  The refresh token (if requested).
</ResponseField>

**Throws:**

* `CustomTokenExchangeError` if validation fails or the exchange request fails

### updateSession

```typescript theme={null}
// 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.

<ParamField path="req" type="PagesRouterRequest | NextRequest | Request">
  The request object (Pages Router only).
</ParamField>

<ParamField path="res" type="PagesRouterResponse | NextResponse | Response">
  The response object (Pages Router only).
</ParamField>

<ParamField path="session" type="SessionData" required>
  The updated session data.
</ParamField>

**Throws:**

* `Error` if the user is not authenticated
* `Error` if the session data is missing

### startInteractiveLogin

```typescript theme={null}
startInteractiveLogin(
  options?: StartInteractiveLoginOptions
): Promise<NextResponse>
```

Starts an interactive login flow.

<ParamField path="options" type="StartInteractiveLoginOptions">
  Options for the interactive login.
</ParamField>

<ResponseField name="response" type="Promise<NextResponse>">
  Returns a NextResponse that redirects to the authorization server.
</ResponseField>

### getTokenByBackchannelAuth

```typescript theme={null}
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.

<ParamField path="options" type="BackchannelAuthenticationOptions" required>
  The backchannel authentication options.
</ParamField>

<ParamField path="options.bindingMessage" type="string" required>
  Human-readable message to be displayed at the consumption device and authentication device.
</ParamField>

<ParamField path="options.loginHint" type="{ sub: string }" required>
  The login hint to inform which user to use.
</ParamField>

<ParamField path="options.requestedExpiry" type="number">
  Set a custom expiry time for the CIBA flow in seconds. Defaults to 300 seconds (5 minutes) if not set.
</ParamField>

<ResponseField name="tokenSet" type="TokenSet">
  The token set containing access token, ID token, and refresh token.
</ResponseField>

<ResponseField name="idTokenClaims" type="object">
  The ID token claims.
</ResponseField>

### connectAccount

```typescript theme={null}
connectAccount(
  options: ConnectAccountOptions
): Promise<NextResponse>
```

Initiates the Connect Account flow to connect a third-party account to the user's profile.

<ParamField path="options" type="ConnectAccountOptions" required>
  Options for connecting an account.
</ParamField>

<ResponseField name="response" type="Promise<NextResponse>">
  Returns a NextResponse that redirects to the authorization server.
</ResponseField>

**Throws:**

* `ConnectAccountError` with code `MISSING_SESSION` if the user does not have an active session

### createFetcher

```typescript theme={null}
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

<ParamField path="req" type="PagesRouterRequest | NextRequest | Request">
  Request object for session context (required for Pages Router, optional for App Router).
</ParamField>

<ParamField path="options.useDPoP" type="boolean">
  Enable DPoP for this fetcher instance (overrides global setting).
</ParamField>

<ParamField path="options.getAccessToken" type="AccessTokenFactory">
  Custom access token factory function. If not provided, uses the default from hooks.
</ParamField>

<ParamField path="options.baseUrl" type="string">
  Base URL for relative requests. Must be provided if using relative URLs.
</ParamField>

<ParamField path="options.fetch" type="CustomFetchImpl<TOutput>">
  Custom fetch implementation. Falls back to global fetch if not provided.
</ParamField>

<ResponseField name="fetcher" type="Promise<Fetcher<TOutput>>">
  Returns a configured Fetcher instance.
</ResponseField>

**Throws:**

* `AccessTokenError` with code `MISSING_SESSION` when no active session exists

### withPageAuthRequired

```typescript theme={null}
// App Router
withPageAuthRequired(
  Component: AppRouterPageRoute,
  opts?: WithPageAuthRequiredAppRouterOptions
): AppRouterPageRoute

// Pages Router
withPageAuthRequired(
  opts?: WithPageAuthRequiredPageRouterOptions
): PageRoute
```

Protects a page route by requiring authentication.

### withApiAuthRequired

```typescript theme={null}
withApiAuthRequired(
  apiRoute: AppRouteHandlerFn | NextApiHandler
): (req, res) => Promise<Response>
```

Protects an API route by requiring authentication.

### mfa

```typescript theme={null}
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

```typescript theme={null}
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;
  }
}
```
