@auth0/nextjs-auth0 - v4.26.0
    Preparing search index...

    Class Auth0Client

    Index
    • 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

      Returns ServerMfaClient

      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 — tokens stored in session cookie, not in response body
      await auth0.mfa.verify({
      mfaToken: error.mfa_token,
      otp: '123456'
      });
      // Retrieve the access token from the session after verify
      const token = await auth0.getAccessToken();
      }
      }
    • get passkey(): ServerPasskeyClient

      Access server-side passkey (WebAuthn) authentication and enrollment operations.

      Authentication: auth0.passkey.register(), auth0.passkey.challenge(), auth0.passkey.getToken() Enrollment: auth0.passkey.enrollmentChallenge(), auth0.passkey.enrollmentVerify()

      Returns ServerPasskeyClient

    • get passwordless(): ServerPasswordlessClient

      Access server-side passwordless authentication operations. Use auth0.passwordless.start() to send an OTP, and auth0.passwordless.verify() to verify the code and log the user in.

      Returns ServerPasswordlessClient

    • Builds a NextResponse redirect that carries the STT to the target app's login route.

      Returns a redirect to targetLoginUrl?session_transfer_token=<encoded>(&organization=…). Pure URL builder — no network call, nothing written to session.

      Parameters

      • targetLoginUrl: string

        The target app's login URL. Must be a trusted, app-controlled value.

      • result: SessionTransferTokenResult

        The SessionTransferTokenResult from requestSessionTransferToken

      • Optionalopts: { organization?: string }

        Optional: organization to append (same value passed to requestSessionTransferToken)

      Returns NextResponse

      const result = await auth0.requestSessionTransferToken({ subjectToken, subjectTokenType });
      return auth0.buildSessionTransferRedirect("https://app.example.com/auth/login", result);
    • Initiates the Connect Account flow to connect a third-party account to the user's profile. If the user does not have an active session, a ConnectAccountError is thrown.

      This method first attempts to obtain an access token with the create:me:connected_accounts scope for the My Account API to create a connected account for the user.

      The user will then be redirected to authorize the connection with the third-party provider.

      You must enable Offline Access from the Connection Permissions settings to be able to use the connection with Connected Accounts.

      Parameters

      Returns Promise<NextResponse<unknown>>

    • 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

      The fetcher provides a high-level interface for making requests to protected resources without manually handling authentication details.

      Type Parameters

      • TOutput extends Response = Response

        Response type that extends the standard Response interface

      Parameters

      • req: NextRequest | Request | PagesRouterRequest | undefined

        Request object for session context (required for Pages Router, optional for App Router)

      • options: {
            baseUrl?: string;
            fetch?: CustomFetchImpl<TOutput>;
            getAccessToken?: AccessTokenFactory;
            useDPoP?: boolean;
        }

        Configuration options for the fetcher

        • OptionalbaseUrl?: string

          Base URL for relative requests. Must be provided if using relative URLs

        • Optionalfetch?: CustomFetchImpl<TOutput>

          Custom fetch implementation. Falls back to global fetch if not provided

        • OptionalgetAccessToken?: AccessTokenFactory

          Custom access token factory function. If not provided, uses the default from hooks

        • OptionaluseDPoP?: boolean

          Enable DPoP for this fetcher instance (overrides global setting)

      Returns Promise<Fetcher<TOutput>>

      Promise that resolves to a configured Fetcher instance

      AccessTokenError when no active session exists

      import { auth0 } from "@/lib/auth0";

      const fetcher = await auth0.createFetcher(undefined, {
      baseUrl: "https://api.example.com",
      useDPoP: true
      });

      const response = await fetcher.fetchWithAuth("/users");
      const users = await response.json();
      • Fetcher for details on using the returned fetcher instance
      • FetcherMinimalConfig for available configuration options
    • 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.

      This method can be used in Server Actions, Route Handlers, and API routes.

      Parameters

      Returns Promise<CustomTokenExchangeResponse>

      The token exchange response containing access token and optionally id/refresh tokens

      If validation fails or the exchange request fails

      const result = await auth0.customTokenExchange({
      subjectToken: legacyIdToken,
      subjectTokenType: 'urn:acme:legacy-token',
      audience: 'https://api.example.com',
      scope: 'read:data'
      });

      console.log(result.accessToken);
    • Parameters

      • Optionaloptions: GetAccessTokenOptions

        Optional configuration for getting the access token.

        • Optionalaudience?: string | null

          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

        • OptionalmergeScopes?: boolean

          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.

        • Optionalrefresh?: boolean | null
        • Optionalscope?: string | null

      Returns Promise<
          {
              audience?: string;
              expiresAt: number;
              scope?: string;
              token: string;
              token_type?: string;
          },
      >

    • getAccessToken returns the access token.

      This method can be used in middleware and getServerSideProps, API routes in the Pages Router.

      Parameters

      • req: NextRequest | PagesRouterRequest

        The request object.

      • res: NextResponse<unknown> | PagesRouterResponse

        The response object.

      • Optionaloptions: GetAccessTokenOptions

        Optional configuration for getting the access token.

        • Optionalaudience?: string | null

          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

        • OptionalmergeScopes?: boolean

          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.

        • Optionalrefresh?: boolean | null
        • Optionalscope?: string | null

      Returns Promise<
          {
              audience?: string;
              expiresAt: number;
              scope?: string;
              token: string;
              token_type?: string;
          },
      >

    • 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 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 }>

    • Retrieves an access token for a connection.

      This method can be used in middleware and getServerSideProps, API routes in the Pages Router.

      Parameters

      Returns Promise<{ expiresAt: number; token: string }>

    • middleware mounts the SDK routes to run as a middleware function.

      Parameters

      • req: NextRequest | Request

      Returns Promise<NextResponse<unknown>>

    • Requests a Session Transfer Token (STT) that lets an authenticated agent establish a web session as a customer in a target app — without the customer's password.

      This method can be used in Server Components, Server Actions, and Route Handlers in the App Router.

      NOTE: Server Components cannot set cookies. If the actor's ID token needs a silent refresh (see below), calling this from a Server Component will refresh the token but the updated token set will not be persisted. Prefer calling this from a Route Handler or Server Action.

      The SDK fills in audience, grant_type, actor_token, and actor_token_type automatically. The actor defaults to the agent session's ID token. If the ID token is expired and a refresh token is available the SDK silently refreshes the session first — the refreshed token set is persisted back to the session cookie (through the beforeSessionSaved hook, if configured), since refresh token rotation invalidates the old refresh token still held in the session. If no refresh token is available this throws ACTOR_UNAVAILABLE. If the refresh itself requires MFA step-up, this throws MfaRequiredError.

      Use the result with buildSessionTransferRedirect to redirect the agent's browser to the target app's login URL.

      The returned STT is one-shot (~60s) and must never be cached.

      Parameters

      Returns Promise<SessionTransferTokenResult>

      // app/api/stt/route.ts — App Router Route Handler
      const result = await auth0.requestSessionTransferToken({
      subjectToken: mySubjectToken,
      subjectTokenType: "urn:acme:subject",
      reason: "Investigating ticket #1234"
      });
      return auth0.buildSessionTransferRedirect("https://app.example.com/auth/login", result);
    • Requests a Session Transfer Token (STT) that lets an authenticated agent establish a web session as a customer in a target app — without the customer's password.

      This method can be used in middleware and getServerSideProps, API routes in the Pages Router.

      Parameters

      Returns Promise<SessionTransferTokenResult>

      // pages/api/stt.ts — Pages Router API route
      const result = await auth0.requestSessionTransferToken(req, res, {
      subjectToken: mySubjectToken,
      subjectTokenType: "urn:acme:subject"
      });
    • Revokes the refresh token stored in the current session at the Auth0 /oauth/revoke endpoint (RFC 7009).

      Auth0 will also invalidate all access tokens issued under the same authorization grant — any subsequent API calls using those tokens will fail. The local session cookie is not cleared — use handleLogout (which already revokes on logout) for a full logout.

      Parameters

      • Optionaloptions: { req?: NextRequest | PagesRouterRequest }

        For the Pages Router, pass the request object so the session can be read.

      Returns Promise<void>

      If no session or refresh token exists, or the revocation request fails.

    • updateSession updates the session of the currently authenticated user. If the user does not have a session, an error is thrown.

      This method can be used in middleware and getServerSideProps, API routes, and middleware in the Pages Router.

      Parameters

      Returns Promise<void>

    • 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.

      Parameters

      Returns Promise<void>

    • Parameters

      • apiRoute: AppRouteHandlerFn | NextApiHandler

      Returns (
          req: NextApiRequest | NextRequest,
          resOrParams: AppRouteHandlerFnContext | NextApiResponse,
      ) => unknown