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();
}
}
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()
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.
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.
The target app's login URL. Must be a trusted, app-controlled value.
The SessionTransferTokenResult from requestSessionTransferToken
Optionalopts: { organization?: string }
Optional: organization to append (same value passed to requestSessionTransferToken)
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.
Creates a configured Fetcher instance for making authenticated API requests.
This method creates a specialized HTTP client that handles:
The fetcher provides a high-level interface for making requests to protected resources without manually handling authentication details.
Response type that extends the standard Response interface
Request object for session context (required for Pages Router, optional for App Router)
Configuration options for the fetcher
OptionalbaseUrl?: stringBase 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?: AccessTokenFactoryCustom access token factory function. If not provided, uses the default from hooks
OptionaluseDPoP?: booleanEnable DPoP for this fetcher instance (overrides global setting)
Promise that resolves to a configured Fetcher instance
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.
The custom token exchange options
The token exchange response containing access token and optionally id/refresh tokens
Optionaloptions: GetAccessTokenOptions
Optional configuration for getting the access token.
Optionalaudience?: string | nullPlease 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?: booleanControl 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 | nullOptionalscope?: string | nullgetAccessToken returns the access token.
This method can be used in middleware and getServerSideProps, API routes in the Pages Router.
The request object.
The response object.
Optionaloptions: GetAccessTokenOptions
Optional configuration for getting the access token.
Optionalaudience?: string | nullPlease 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?: booleanControl 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 | nullOptionalscope?: string | nullRetrieves 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.
Retrieves an access token for a connection.
This method can be used in middleware and getServerSideProps, API routes in the Pages Router.
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.
This method can be used in middleware and getServerSideProps, API routes in the Pages Router.
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.
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.
// 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.
The request object.
The response object.
STT exchange options.
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.
Optionaloptions: { req?: NextRequest | PagesRouterRequest }
For the Pages Router, pass the request object so the session can be read.
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.
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.
Optionalopts: WithPageAuthRequiredAppRouterOptions<P>
MFA API for server-side operations.
Provides access to MFA methods that require encrypted mfa_token from MfaRequiredError: