@auth0/auth0-spa-js
- Version 2.13.1
- Published
- 3.46 MB
- 4 dependencies
- MIT license
Install
npm i @auth0/auth0-spa-jsyarn add @auth0/auth0-spa-jspnpm add @auth0/auth0-spa-jsOverview
Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE
Index
Functions
Classes
Interfaces
Enums
Type Aliases
- AuthenticatorType
- Cacheable
- CacheEntry
- CacheKeyData
- CacheLocation
- ConnectAccountRedirectResult
- CustomFetchMinimalOutput
- CustomTokenExchangeOptions
- EnrollmentResponse
- EnrollParams
- FetcherConfig
- FetchOptions
- FetchResponse
- GetTokenSilentlyVerboseResponse
- KeyManifestEntry
- MaybePromise
- MfaFactorType
- MfaGrantType
- OobChannel
- TokenEndpointResponse
- WrappedCacheEntry
Functions
function createAuth0Client
createAuth0Client: (options: Auth0ClientOptions) => Promise<Auth0Client>;Asynchronously creates the Auth0Client instance and calls
checkSession.**Note:** There are caveats to using this in a private browser tab, which may not silently authenticae a user on page refresh. Please see [the checkSession docs](https://auth0.github.io/auth0-spa-js/classes/Auth0Client.html#checksession) for more info.
Parameter options
The client options
Returns
An instance of Auth0Client
Classes
class Auth0Client
class Auth0Client {}Auth0 SDK for Single Page Applications using [Authorization Code Grant Flow with PKCE](https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce).
constructor
constructor(options: Auth0ClientOptions);property mfa
readonly mfa: MfaApiClient;MFA API client for multi-factor authentication operations.
Provides methods for: - Listing enrolled authenticators - Enrolling new authenticators (OTP, SMS, Voice, Push, Email) - Initiating MFA challenges - Verifying MFA challenges
method checkSession
checkSession: (options?: GetTokenSilentlyOptions) => Promise<void>;- await auth0.checkSession();
Check if the user is logged in using
getTokenSilently. The difference withgetTokenSilentlyis that this doesn't return a token, but it will pre-fill the token cache.This method also heeds the
auth0.{clientId}.is.authenticatedcookie, as an optimization to prevent calling Auth0 unnecessarily. If the cookie is not present because there was no previous login (or it has expired) then tokens will not be refreshed.It should be used for silently logging in the user when you instantiate the
Auth0Clientconstructor. You should not need this if you are using thecreateAuth0Clientfactory.**Note:** the cookie **may not** be present if running an app using a private tab, as some browsers clear JS cookie data and local storage when the tab or page is closed, or on page reload. This effectively means that
checkSessioncould silently return without authenticating the user on page refresh when using a private tab, despite having previously logged in. As a workaround, usegetTokenSilentlyinstead and handle the possiblelogin_requirederror [as shown in the readme](https://github.com/auth0/auth0-spa-js#creating-the-client).Parameter options
method connectAccountWithRedirect
connectAccountWithRedirect: <TAppState = any>( options: RedirectConnectAccountOptions<TAppState>) => Promise<void>;Initiates a redirect to connect the user's account with a specified connection. This method generates PKCE parameters, creates a transaction, and redirects to the /connect endpoint.
You must enable
Offline Accessfrom the Connection Permissions settings to be able to use the connection with Connected Accounts.TAppState - The application state to persist through the transaction.
Parameter options
Options for the connect account redirect flow.
Parameter
{string} options.connection - The name of the connection to link (e.g. 'google-oauth2').
Parameter
{string[]} [options.scopes] - Array of scopes to request from the Identity Provider during the connect account flow.
Parameter
{AuthorizationParams} [options.authorization_params] - Additional authorization parameters for the request to the upstream IdP.
Parameter
{string} [options.redirectUri] - The URI to redirect back to after connecting the account.
Parameter
{TAppState} [options.appState] - Application state to persist through the transaction.
Parameter
{(url: string) => Promise} [options.openUrl] - Custom function to open the URL.
Returns
{Promise} Resolves when the redirect is initiated.
Throws
{MyAccountApiError} If the connect request to the My Account API fails.
method createFetcher
createFetcher: <TOutput extends CustomFetchMinimalOutput = Response>( config?: FetcherConfig<TOutput>) => Fetcher<TOutput>;Returns a new
Fetcherclass that will contain afetchWithAuth()method. This is a drop-in replacement for the Fetch API'sfetch()method, but will handle certain authentication logic for you, like building the proper auth headers or managing DPoP nonces and retries automatically.Check the
EXAMPLES.mdfile for a deeper look into this method.
method exchangeToken
exchangeToken: ( options: CustomTokenExchangeOptions) => Promise<TokenEndpointResponse>;Exchanges an external subject token for an Auth0 token via a token exchange request.
Parameter options
The options required to perform the token exchange.
Returns
{Promise} A promise that resolves to the token endpoint response, which contains the issued Auth0 tokens.
This method implements the token exchange grant as specified in RFC 8693 by first validating the provided subject token type and then constructing a token request to the /oauth/token endpoint. The request includes the following parameters:
-
grant_type: Hard-coded to "urn:ietf:params:oauth:grant-type:token-exchange". -subject_token: The external token provided via the options. -subject_token_type: The type of the external token (validated by this function). -scope: A unique set of scopes, generated by merging the scopes supplied in the options with the SDK’s default scopes. -audience: The target audience from the options, with fallback to the SDK's authorization configuration. -organization: Optional organization ID or name for authenticating the user in an organization context. When provided, the organization ID will be present in the access token payload.**Example Usage:**
// Define the token exchange optionsconst options: CustomTokenExchangeOptions = {subject_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...',subject_token_type: 'urn:acme:legacy-system-token',scope: "openid profile",organization: "org_12345"};// Exchange the external token for Auth0 tokenstry {const tokenResponse = await instance.exchangeToken(options);// Use tokenResponse.access_token, tokenResponse.id_token, etc.// The organization ID will be present in the access token payload} catch (error) {// Handle token exchange error}
method generateDpopProof
generateDpopProof: (params: { url: string; method: string; nonce?: string; accessToken: string;}) => Promise<string>;Returns a string to be used to demonstrate possession of the private key used to cryptographically bind access tokens with DPoP.
It requires enabling the Auth0ClientOptions.useDpop option.
method getConfiguration
getConfiguration: () => Readonly<ClientConfiguration>;Returns a readonly copy of the initialization configuration.
Returns
An object containing domain and clientId
Example 1
const auth0 = new Auth0Client({domain: 'tenant.auth0.com',clientId: 'abc123'});const config = auth0.getConfiguration();// { domain: 'tenant.auth0.com', clientId: 'abc123' }
method getDpopNonce
getDpopNonce: (id?: string) => Promise<string | undefined>;Returns the current DPoP nonce used for making requests to Auth0.
It can return
undefinedbecause when starting fresh it will not be populated until after the first response from the server.It requires enabling the Auth0ClientOptions.useDpop option.
Parameter nonce
The nonce value.
Parameter id
The identifier of a nonce: if absent, it will get the nonce used for requests to Auth0. Otherwise, it will be used to select a specific non-Auth0 nonce.
method getIdTokenClaims
getIdTokenClaims: () => Promise<IdToken | undefined>;- const claims = await auth0.getIdTokenClaims();
Returns all claims from the id_token if available.
method getTokenSilently
getTokenSilently: { ( options: GetTokenSilentlyOptions & { detailedResponse: true } ): Promise<GetTokenSilentlyVerboseResponse>; (options?: GetTokenSilentlyOptions): Promise<string>;};Fetches a new access token and returns the response from the /oauth/token endpoint, omitting the refresh token.
Parameter options
Fetches a new access token and returns it.
Parameter options
method getTokenWithPopup
getTokenWithPopup: ( options?: GetTokenWithPopupOptions, config?: PopupConfigOptions) => Promise<string | undefined>;- const token = await auth0.getTokenWithPopup(options);
Opens a popup with the
/authorizeURL using the parameters provided as arguments. Random and securestateandnonceparameters will be auto-generated. If the response is successful, results will be valid according to their expiration times.Parameter options
Parameter config
method getUser
getUser: <TUser extends User>() => Promise<TUser | undefined>;- const user = await auth0.getUser();
Returns the user information if available (decoded from the
id_token).
method handleRedirectCallback
handleRedirectCallback: <TAppState = any>( url?: string) => Promise< RedirectLoginResult<TAppState> | ConnectAccountRedirectResult<TAppState>>;After the browser redirects back to the callback page, call
handleRedirectCallbackto handle success and error responses from Auth0. If the response is successful, results will be valid according to their expiration times.
method isAuthenticated
isAuthenticated: () => Promise<boolean>;- const isAuthenticated = await auth0.isAuthenticated();
Returns
trueif there's valid information stored, otherwise returnsfalse.
method loginWithPopup
loginWithPopup: ( options?: PopupLoginOptions, config?: PopupConfigOptions) => Promise<void>;- try {await auth0.loginWithPopup(options);} catch(e) {if (e instanceof PopupCancelledError) {// Popup was closed before login completed}}
Opens a popup with the
/authorizeURL using the parameters provided as arguments. Random and securestateandnonceparameters will be auto-generated. If the response is successful, results will be valid according to their expiration times.IMPORTANT: This method has to be called from an event handler that was started by the user like a button click, for example, otherwise the popup will be blocked in most browsers.
Parameter options
Parameter config
method loginWithRedirect
loginWithRedirect: <TAppState = any>( options?: RedirectLoginOptions<TAppState>) => Promise<void>;- await auth0.loginWithRedirect(options);
Performs a redirect to
/authorizeusing the parameters provided as arguments. Random and securestateandnonceparameters will be auto-generated.Parameter options
method logout
logout: (options?: LogoutOptions) => Promise<void>;- await auth0.logout(options);
Clears the application session and performs a redirect to
/v2/logout, using the parameters provided as arguments, to clear the Auth0 session.If the
federatedoption is specified it also clears the Identity Provider session. [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).Parameter options
method setDpopNonce
setDpopNonce: (nonce: string, id?: string) => Promise<void>;Sets the current DPoP nonce used for making requests to Auth0.
It requires enabling the Auth0ClientOptions.useDpop option.
Parameter nonce
The nonce value.
Parameter id
The identifier of a nonce: if absent, it will set the nonce used for requests to Auth0. Otherwise, it will be used to select a specific non-Auth0 nonce.
class AuthenticationError
class AuthenticationError extends GenericError {}Thrown when handling the redirect callback fails, will be one of Auth0's Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses
constructor
constructor( error: string, error_description: string, state: string, appState?: any);property appState
appState: any;property state
state: string;class CacheKey
class CacheKey {}constructor
constructor(data: CacheKeyData, prefix?: string, suffix?: string);property audience
audience?: string;property clientId
clientId: string;property prefix
prefix: string;property scope
scope?: string;property suffix
suffix?: string;method fromCacheEntry
static fromCacheEntry: (entry: CacheEntry) => CacheKey;Utility function to build a
CacheKeyinstance from a cache entryParameter entry
The entry
Returns
An instance of
CacheKey
method fromKey
static fromKey: (key: string) => CacheKey;Converts a cache key string into a
CacheKeyinstance.Parameter key
The key to convert
Returns
An instance of
CacheKey
method toKey
toKey: () => string;Converts this
CacheKeyinstance into a string for use in a cacheReturns
A string representation of the key
class ConnectError
class ConnectError extends GenericError {}Thrown when handling the redirect callback for the connect flow fails, will be one of Auth0's Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses
constructor
constructor( error: string, error_description: string, connection: string, state: string, appState?: any);property appState
appState: any;property connection
connection: string;property state
state: string;class Fetcher
class Fetcher<TOutput extends CustomFetchMinimalOutput> {}constructor
constructor(config: FetcherConfig<TOutput>, hooks: FetcherHooks);property config
protected readonly config: Omit<FetcherConfig<TOutput>, 'fetch'> & Required<Pick<FetcherConfig<TOutput>, 'fetch'>>;property hooks
protected readonly hooks: FetcherHooks;method buildBaseRequest
protected buildBaseRequest: ( info: RequestInfo | URL, init: RequestInit | undefined) => Request;method buildUrl
protected buildUrl: ( baseUrl: string | undefined, url: string | undefined) => string;method extractUrl
protected extractUrl: (info: RequestInfo | URL) => string;method fetchWithAuth
fetchWithAuth: ( info: RequestInfo | URL, init?: RequestInit, authParams?: AuthParams) => Promise<TOutput>;method getAccessToken
protected getAccessToken: ( authParams?: AuthParams) => Promise<string | GetTokenSilentlyVerboseResponse>;method getHeader
protected getHeader: (headers: ResponseHeaders, name: string) => string;method handleResponse
protected handleResponse: ( response: TOutput, callbacks: FetchWithAuthCallbacks<TOutput>) => Promise<TOutput>;method hasUseDpopNonceError
protected hasUseDpopNonceError: (response: TOutput) => boolean;method internalFetchWithAuth
protected internalFetchWithAuth: ( info: RequestInfo | URL, init: RequestInit | undefined, callbacks: FetchWithAuthCallbacks<TOutput>, authParams?: AuthParams) => Promise<TOutput>;method isAbsoluteUrl
protected isAbsoluteUrl: (url: string) => boolean;method prepareRequest
protected prepareRequest: ( request: Request, authParams?: AuthParams) => Promise<void>;method setAuthorizationHeader
protected setAuthorizationHeader: ( request: Request, accessToken: string, tokenType?: string) => void;method setDpopProofHeader
protected setDpopProofHeader: ( request: Request, accessToken: string) => Promise<void>;class GenericError
class GenericError extends Error {}Thrown when network requests to the Auth server fail.
constructor
constructor(error: string, error_description: string);property error
error: string;property error_description
error_description: string;method fromPayload
static fromPayload: ({ error, error_description,}: { error: string; error_description: string;}) => GenericError;class InMemoryCache
class InMemoryCache {}property enclosedCache
enclosedCache: ICache;class LocalStorageCache
class LocalStorageCache implements ICache {}class MfaApiClient
class MfaApiClient {}Client for Auth0 MFA API operations
Manages multi-factor authentication including: - Listing enrolled authenticators - Enrolling new authenticators (OTP, SMS, Voice, Push, Email) - Initiating MFA challenges - Verifying MFA challenges
This is a wrapper around auth0-auth-js MfaClient that maintains backward compatibility with the existing spa-js API.
MFA context (scope, audience) is stored internally keyed by mfaToken, enabling concurrent MFA flows without state conflicts.
Example 1
try {await auth0.getTokenSilently({ authorizationParams: { audience: 'https://api.example.com' } });} catch (e) {if (e instanceof MfaRequiredError) {// SDK automatically stores context for this mfaTokenconst authenticators = await auth0.mfa.getAuthenticators({ mfaToken: e.mfa_token });// ... complete MFA flow}}
method challenge
challenge: (params: ChallengeAuthenticatorParams) => Promise<ChallengeResponse>;Initiates an MFA challenge
Sends OTP via SMS, initiates push notification, or prepares for OTP entry
Parameter params
Challenge parameters including mfaToken
Returns
Challenge response with oobCode if applicable
Throws
{MfaChallengeError} If challenge initiation fails
Example 1
OTP challenge
const challenge = await mfa.challenge({mfaToken: mfaTokenFromLogin,challengeType: 'otp',authenticatorId: 'otp|dev_xxx'});// User enters OTP from their authenticator appExample 2
SMS challenge
const challenge = await mfa.challenge({mfaToken: mfaTokenFromLogin,challengeType: 'oob',authenticatorId: 'sms|dev_xxx'});console.log(challenge.oobCode); // Use for verification
method enroll
enroll: (params: EnrollParams) => Promise<EnrollmentResponse>;Enrolls a new MFA authenticator
Requires MFA access token with 'enroll' scope
Parameter params
Enrollment parameters including mfaToken and factorType
Returns
Enrollment response with authenticator details
Throws
{MfaEnrollmentError} If enrollment fails
Example 1
OTP enrollment
const enrollment = await mfa.enroll({mfaToken: mfaToken,factorType: 'otp'});console.log(enrollment.secret); // Base32 secretconsole.log(enrollment.barcodeUri); // QR code URIExample 2
SMS enrollment
const enrollment = await mfa.enroll({mfaToken: mfaToken,factorType: 'sms',phoneNumber: '+12025551234'});
method getAuthenticators
getAuthenticators: (mfaToken: string) => Promise<Authenticator[]>;Gets enrolled MFA authenticators filtered by challenge types from context.
Challenge types are automatically resolved from the stored MFA context (set when mfa_required error occurred).
Parameter mfaToken
MFA token from mfa_required error
Returns
Array of enrolled authenticators matching the challenge types
Throws
{MfaListAuthenticatorsError} If the request fails or context not found
Example 1
Basic usage
try {await auth0.getTokenSilently();} catch (e) {if (e instanceof MfaRequiredError) {// SDK automatically uses challenge types from error contextconst authenticators = await auth0.mfa.getAuthenticators(e.mfa_token);}}
method getEnrollmentFactors
getEnrollmentFactors: (mfaToken: string) => Promise<EnrollmentFactor[]>;Gets available MFA enrollment factors from the stored context.
This method exposes the enrollment options from the mfa_required error's mfaRequirements.enroll array, eliminating the need for manual parsing.
Parameter mfaToken
MFA token from mfa_required error
Returns
Array of enrollment factors available for the user (empty array if no enrollment required)
Throws
{MfaEnrollmentFactorsError} If MFA context not found
Example 1
Basic usage
try {await auth0.getTokenSilently();} catch (error) {if (error.error === 'mfa_required') {// Get enrollment options from SDKconst enrollOptions = await auth0.mfa.getEnrollmentFactors(error.mfa_token);// [{ type: 'otp' }, { type: 'phone' }, { type: 'push-notification' }]showEnrollmentOptions(enrollOptions);}}Example 2
Check if enrollment is required
try {const factors = await auth0.mfa.getEnrollmentFactors(mfaToken);if (factors.length > 0) {// User needs to enroll in MFArenderEnrollmentUI(factors);} else {// No enrollment required, proceed with challenge}} catch (error) {if (error instanceof MfaEnrollmentFactorsError) {console.error('Context not found:', error.error_description);}}
method verify
verify: (params: VerifyParams) => Promise<TokenEndpointResponse>;Verifies an MFA challenge and completes authentication
The scope and audience are retrieved from the stored context (set when the mfa_required error occurred). The grant_type is automatically inferred from which verification field is provided (otp, oobCode, or recoveryCode).
Parameter params
Verification parameters with OTP, OOB code, or recovery code
Returns
Token response with access_token, id_token, refresh_token
Throws
{MfaVerifyError} If verification fails (invalid code, expired, rate limited)
Throws
{MfaVerifyError} If MFA context not found
Throws
{MfaVerifyError} If grant_type cannot be inferred
Rate limits: - 10 verification attempts allowed - Refreshes at 1 attempt per 6 minutes
Example 1
OTP verification (grant_type inferred from otp field)
const tokens = await mfa.verify({mfaToken: mfaTokenFromLogin,otp: '123456'});console.log(tokens.access_token);Example 2
OOB verification (grant_type inferred from oobCode field)
const tokens = await mfa.verify({mfaToken: mfaTokenFromLogin,oobCode: challenge.oobCode,bindingCode: '123456' // Code user received via SMS});Example 3
Recovery code verification (grant_type inferred from recoveryCode field)
const tokens = await mfa.verify({mfaToken: mfaTokenFromLogin,recoveryCode: 'XXXX-XXXX-XXXX'});
class MfaChallengeError
class MfaChallengeError extends MfaError {}Error thrown when initiating an MFA challenge fails.
Example 1
try {const challenge = await mfa.challenge({mfaToken: mfaToken,challengeType: 'otp',authenticatorId: 'otp|dev_123'});} catch (error) {if (error instanceof MfaChallengeError) {console.log(error.error); // 'too_many_attempts'console.log(error.error_description); // 'Rate limit exceeded'}}
constructor
constructor(error: string, error_description: string);class MfaEnrollmentError
class MfaEnrollmentError extends MfaError {}Error thrown when enrolling an MFA authenticator fails.
Example 1
try {const enrollment = await mfa.enroll({authenticator_types: ['otp']});} catch (error) {if (error instanceof MfaEnrollmentError) {console.log(error.error); // 'invalid_phone_number'console.log(error.error_description); // 'Invalid phone number format'}}
constructor
constructor(error: string, error_description: string);class MfaEnrollmentFactorsError
class MfaEnrollmentFactorsError extends MfaError {}Error thrown when getting enrollment factors fails.
Example 1
try {const factors = await mfa.getEnrollmentFactors(mfaToken);} catch (error) {if (error instanceof MfaEnrollmentFactorsError) {console.log(error.error); // 'mfa_context_not_found'console.log(error.error_description); // 'MFA context not found...'}}
constructor
constructor(error: string, error_description: string);class MfaError
class MfaError extends GenericError {}Base class for MFA-related errors in auth0-spa-js. Extends GenericError for unified error hierarchy across the SDK.
constructor
constructor(error: string, error_description: string);method fromPayload
static fromPayload: ({ error, error_description,}: { error: string; error_description: string;}) => MfaError;class MfaListAuthenticatorsError
class MfaListAuthenticatorsError extends MfaError {}Error thrown when listing MFA authenticators fails.
Example 1
try {const authenticators = await mfa.getAuthenticators();} catch (error) {if (error instanceof MfaListAuthenticatorsError) {console.log(error.error); // 'access_denied'console.log(error.error_description); // 'Unauthorized'}}
constructor
constructor(error: string, error_description: string);class MfaRequiredError
class MfaRequiredError extends GenericError {}Error thrown when the token exchange results in a
mfa_requirederror
constructor
constructor( error: string, error_description: string, mfa_token: string, mfa_requirements: MfaRequirements);property mfa_requirements
mfa_requirements: MfaRequirements;property mfa_token
mfa_token: string;class MfaVerifyError
class MfaVerifyError extends MfaError {}Error thrown when verifying an MFA challenge fails.
Example 1
try {const tokens = await mfa.verify({mfaToken: mfaToken,grant_type: 'http://auth0.com/oauth/grant-type/mfa-otp',otp: '123456'});} catch (error) {if (error instanceof MfaVerifyError) {console.log(error.error); // 'invalid_otp' or 'context_not_found'console.log(error.error_description); // Error details}}
constructor
constructor(error: string, error_description: string);class MissingRefreshTokenError
class MissingRefreshTokenError extends GenericError {}Error thrown when there is no refresh token to use
constructor
constructor(audience: string, scope: string);property audience
audience: string;property scope
scope: string;class MyAccountApiError
class MyAccountApiError extends Error {}constructor
constructor({ type, status, title, detail, validation_errors }: ErrorResponse);property detail
readonly detail: string;property status
readonly status: number;property title
readonly title: string;property type
readonly type: string;property validation_errors
readonly validation_errors?: { detail: string; field?: string; pointer?: string; source?: string;}[];class PopupCancelledError
class PopupCancelledError extends GenericError {}constructor
constructor(popup: Window);property popup
popup: Window;class PopupOpenError
class PopupOpenError extends GenericError {}constructor
constructor();class PopupTimeoutError
class PopupTimeoutError extends TimeoutError {}Error thrown when the login popup times out (if the user does not complete auth)
constructor
constructor(popup: Window);property popup
popup: Window;class TimeoutError
class TimeoutError extends GenericError {}Thrown when silent auth times out (usually due to a configuration issue) or when network requests to the Auth server timeout.
constructor
constructor();class UseDpopNonceError
class UseDpopNonceError extends GenericError {}Error thrown when the wrong DPoP nonce is used and a potential subsequent retry wasn't able to fix it.
constructor
constructor(newDpopNonce: string);property newDpopNonce
newDpopNonce: string;class User
class User {}property address
address?: string;property birthdate
birthdate?: string;property email
email?: string;property email_verified
email_verified?: boolean;property family_name
family_name?: string;property gender
gender?: string;property given_name
given_name?: string;property locale
locale?: string;property middle_name
middle_name?: string;property name
name?: string;property nickname
nickname?: string;property phone_number
phone_number?: string;property phone_number_verified
phone_number_verified?: boolean;property picture
picture?: string;property preferred_username
preferred_username?: string;property profile
profile?: string;property sub
sub?: string;property updated_at
updated_at?: string;property website
website?: string;property zoneinfo
zoneinfo?: string;Interfaces
interface Auth0ClientOptions
interface Auth0ClientOptions {}property authorizationParams
authorizationParams?: ClientAuthorizationParams;URL parameters that will be sent back to the Authorization Server. This can be known parameters defined by Auth0 or custom parameters that you define.
property authorizeTimeoutInSeconds
authorizeTimeoutInSeconds?: number;A maximum number of seconds to wait before declaring background calls to /authorize as failed for timeout Defaults to 60s.
property cache
cache?: ICache;Specify a custom cache implementation to use for token storage and retrieval. This setting takes precedence over
cacheLocationif they are both specified.
property cacheLocation
cacheLocation?: CacheLocation;The location to use when storing cache data. Valid values are
memoryorlocalstorage. The default setting ismemory.Read more about [changing storage options in the Auth0 docs](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options)
property clientId
clientId: string;The Client ID found on your Application settings page
property cookieDomain
cookieDomain?: string;The domain the cookie is accessible from. If not set, the cookie is scoped to the current domain, including the subdomain.
Note: setting this incorrectly may cause silent authentication to stop working on page load.
To keep a user logged in across multiple subdomains set this to your top-level domain and prefixed with a
.(eg:.example.com).
property domain
domain: string;Your Auth0 account domain such as
'example.auth0.com','example.eu.auth0.com'or ,'example.mycompany.com'(when using [custom domains](https://auth0.com/docs/custom-domains))
property httpTimeoutInSeconds
httpTimeoutInSeconds?: number;Specify the timeout for HTTP calls using
fetch. The default is 10 seconds.
property issuer
issuer?: string;The issuer to be used for validation of JWTs, optionally defaults to the domain above
property leeway
leeway?: number;The value in seconds used to account for clock skew in JWT expirations. Typically, this value is no more than a minute or two at maximum. Defaults to 60s.
property legacySameSiteCookie
legacySameSiteCookie?: boolean;Sets an additional cookie with no SameSite attribute to support legacy browsers that are not compatible with the latest SameSite changes. This will log a warning on modern browsers, you can disable the warning by setting this to false but be aware that some older useragents will not work, See https://www.chromium.org/updates/same-site/incompatible-clients Defaults to true
property nowProvider
nowProvider?: () => Promise<number> | number;Modify the value used as the current time during the token validation.
**Note**: Using this improperly can potentially compromise the token validation.
property sessionCheckExpiryDays
sessionCheckExpiryDays?: number;Number of days until the cookie
auth0.is.authenticatedwill expire Defaults to 1.
property useCookiesForTransactions
useCookiesForTransactions?: boolean;If
true, the SDK will use a cookie when storing information about the auth transaction while the user is going through the authentication flow on the authorization server.The default is
false, in which case the SDK will use session storage.You might want to enable this if you rely on your users being able to authenticate using flows that may end up spanning across multiple tabs (e.g. magic links) or you cannot otherwise rely on session storage being available.
property useDpop
useDpop?: boolean;If
true, DPoP (OAuth 2.0 Demonstrating Proof of Possession, RFC9449) will be used to cryptographically bind tokens to this specific browser so they can't be used from a different device in case of a leak.The default setting is
false.
property useFormData
useFormData?: boolean;If true, data to the token endpoint is transmitted as x-www-form-urlencoded data, if false it will be transmitted as JSON. The default setting is
true.**Note:** Setting this to
falsemay affect you if you use Auth0 Rules and are sending custom, non-primitive data. If you disable this, please verify that your Auth0 Rules continue to work as intended.
property useMrrt
useMrrt?: boolean;If
true, the SDK will allow the refreshing of tokens using MRRT
property useRefreshTokens
useRefreshTokens?: boolean;If true, refresh tokens are used to fetch new access tokens from the Auth0 server. If false, the standard technique of using a hidden iframe and the
authorization_codegrant withprompt=noneis used. The default setting isfalse.Standard technique relies on cookies. Because browsers increasingly block third-party cookies, it requires a Custom Domain to function reliably. Refresh tokens serve as a fallback for environments where third-party cookies are blocked. Using a Custom Domain with this set to
falseis the most secure and recommended approach.**Note**: Use of refresh tokens must be enabled by an administrator on your Auth0 client application.
property useRefreshTokensFallback
useRefreshTokensFallback?: boolean;If true, fallback to the technique of using a hidden iframe and the
authorization_codegrant withprompt=nonewhen unable to use refresh tokens. If false, the iframe fallback is not used and errors relating to a failedrefresh_tokengrant should be handled appropriately. The default setting isfalse.**Note**: There might be situations where doing silent auth with a Web Message response from an iframe is not possible, like when you're serving your application from the file system or a custom protocol (like in a Desktop or Native app). In situations like this you can disable the iframe fallback and handle the failed
refresh_tokengrant and prompt the user to login interactively withloginWithRedirectorloginWithPopup."E.g. Using the
file:protocol in an Electron application does not support that legacy technique.Example 1
let token: string; try { token = await auth0.getTokenSilently(); } catch (e) { if (e.error === 'missing_refresh_token' || e.error === 'invalid_grant') { auth0.loginWithRedirect(); } }
property workerUrl
workerUrl?: string;If provided, the SDK will load the token worker from this URL instead of the integrated
blob. An example of when this is useful is if you have strict Content-Security-Policy (CSP) and wish to avoid needing to setworker-src: blob:. We recommend either serving the worker, which you can find in the module at<module_path>/dist/auth0-spa-js.worker.production.js, from the same host as your application or using the Auth0 CDNhttps://cdn.auth0.com/js/auth0-spa-js/<version>/auth0-spa-js.worker.production.js.**Note**: The worker is only used when
useRefreshTokens: true,cacheLocation: 'memory', and thecacheis not custom.
interface AuthenticationResult
interface AuthenticationResult {}property code
code?: string;property connect_code
connect_code?: string;This is for the redirect from the connect account flow.
property error
error?: string;property error_description
error_description?: string;property state
state: string;interface Authenticator
interface Authenticator {}Represents an MFA authenticator enrolled by a user
property active
active: boolean;Whether the authenticator is active
property authenticatorType
authenticatorType: AuthenticatorType;Type of authenticator
property createdAt
createdAt?: string;ISO 8601 timestamp when created
property id
id: string;Unique identifier for the authenticator
property lastAuth
lastAuth?: string;ISO 8601 timestamp of last authentication
property name
name?: string;Optional friendly name
property type
type?: string;Types of MFA challenges
interface AuthorizationParams
interface AuthorizationParams {}property acr_values
acr_values?: string;property audience
audience?: string;The default audience to be used for requesting API access.
property connection
connection?: string;The name of the connection configured for your application. If null, it will redirect to the Auth0 Login Page and show the Login Widget.
property display
display?: 'page' | 'popup' | 'touch' | 'wap';-
'page': displays the UI with a full page view -'popup': displays the UI with a popup window -'touch': displays the UI in a way that leverages a touch interface -'wap': displays the UI with a "feature phone" type interface
property id_token_hint
id_token_hint?: string;Previously issued ID Token.
property invitation
invitation?: string;The Id of an invitation to accept. This is available from the user invitation URL that is given when participating in a user invitation flow.
property login_hint
login_hint?: string;The user's email address or other identifier. When your app knows which user is trying to authenticate, you can provide this parameter to pre-fill the email box or select the right session for sign-in.
This currently only affects the classic Lock experience.
property max_age
max_age?: string | number;Maximum allowable elapsed time (in seconds) since authentication. If the last time the user authenticated is greater than this value, the user must be reauthenticated.
property organization
organization?: string;The organization to log in to.
This will specify an
organizationparameter in your user's login request.- If you provide an Organization ID (a string with the prefix
org_), it will be validated against theorg_idclaim of your user's ID Token. The validation is case-sensitive. - If you provide an Organization Name (a string *without* the prefixorg_), it will be validated against theorg_nameclaim of your user's ID Token. The validation is case-insensitive. To use an Organization Name you must have "Allow Organization Names in Authentication API" switched on in your Auth0 settings dashboard. More information is available on the [Auth0 documentation portal](https://auth0.com/docs/manage-users/organizations/configure-organizations/use-org-name-authentication-api)
property prompt
prompt?: 'none' | 'login' | 'consent' | 'select_account';-
'none': do not prompt user for login or consent on reauthentication -'login': prompt user for reauthentication -'consent': prompt user for consent before processing request -'select_account': prompt user to select an account
property redirect_uri
redirect_uri?: string;The default URL where Auth0 will redirect your browser to with the authentication result. It must be whitelisted in the "Allowed Callback URLs" field in your Auth0 Application's settings. If not provided here, it should be provided in the other methods that provide authentication.
property scope
scope?: string;The default scope to be used on authentication requests.
This defaults to
profile emailif not set. If you are setting extra scopes and requireprofileandemailto be included then you must include them in the provided scope.Note: The
openidscope is **always applied** regardless of this setting.
property screen_hint
screen_hint?: 'signup' | 'login' | string;Provides a hint to Auth0 as to what flow should be displayed. The default behavior is to show a login page but you can override this by passing 'signup' to show the signup page instead.
This only affects the New Universal Login Experience.
property ui_locales
ui_locales?: string;The space-separated list of language tags, ordered by preference. For example:
'fr-CA fr en'.
index signature
[key: string]: any;If you need to send custom parameters to the Authorization Server, make sure to use the original parameter name.
interface AuthorizeOptions
interface AuthorizeOptions extends AuthorizationParams {}property code_challenge
code_challenge: string;property code_challenge_method
code_challenge_method: string;property nonce
nonce: string;property redirect_uri
redirect_uri?: string;property response_mode
response_mode: string;property response_type
response_type: string;property scope
scope: string;property state
state: string;interface ChallengeAuthenticatorParams
interface ChallengeAuthenticatorParams {}Parameters for initiating an MFA challenge
property authenticatorId
authenticatorId?: string;Specific authenticator to challenge (optional)
property challengeType
challengeType: 'otp' | 'oob';Type of challenge to initiate
property mfaToken
mfaToken: string;MFA token from mfa_required error or MFA-scoped access token
interface ChallengeResponse
interface ChallengeResponse {}Response from initiating an MFA challenge
property bindingMethod
bindingMethod?: string;Binding method for OOB (e.g., 'prompt')
property challengeType
challengeType: 'otp' | 'oob';Type of challenge created
property oobCode
oobCode?: string;Out-of-band code (for OOB challenges)
interface ClientAuthorizationParams
interface ClientAuthorizationParams extends Omit<AuthorizationParams, 'scope'> {}property scope
scope?: string | Record<string, string>;interface ClientConfiguration
interface ClientConfiguration {}Configuration details exposed by the Auth0Client after initialization.
Main
interface DecodedToken
interface DecodedToken {}interface EnrollEmailParams
interface EnrollEmailParams extends EnrollBaseParams {}Email enrollment parameters
property email
email?: string;Email address (optional, uses user's email if not provided)
property factorType
factorType: 'email';The factor type for enrollment
interface EnrollmentFactor
interface EnrollmentFactor {}Enrollment factor returned by getEnrollmentFactors
property type
type: string;Type of enrollment factor available
interface EnrollOtpParams
interface EnrollOtpParams extends EnrollBaseParams {}OTP (Time-based One-Time Password) enrollment parameters
property factorType
factorType: 'otp';The factor type for enrollment
interface EnrollPushParams
interface EnrollPushParams extends EnrollBaseParams {}Push notification enrollment parameters
property factorType
factorType: 'push';The factor type for enrollment
interface EnrollSmsParams
interface EnrollSmsParams extends EnrollBaseParams {}SMS enrollment parameters
property factorType
factorType: 'sms';The factor type for enrollment
property phoneNumber
phoneNumber: string;Phone number in E.164 format (required for SMS)
interface EnrollVoiceParams
interface EnrollVoiceParams extends EnrollBaseParams {}Voice enrollment parameters
property factorType
factorType: 'voice';The factor type for enrollment
property phoneNumber
phoneNumber: string;Phone number in E.164 format (required for voice)
interface GetTokenSilentlyOptions
interface GetTokenSilentlyOptions {}property authorizationParams
authorizationParams?: { /** * There's no actual redirect when getting a token silently, * but, according to the spec, a `redirect_uri` param is required. * Auth0 uses this parameter to validate that the current `origin` * matches the `redirect_uri` `origin` when sending the response. * It must be whitelisted in the "Allowed Web Origins" in your * Auth0 Application's settings. */ redirect_uri?: string; /** * The scope that was used in the authentication request */ scope?: string; /** * The audience that was used in the authentication request */ audience?: string; /** * If you need to send custom parameters to the Authorization Server, * make sure to use the original parameter name. */ [key: string]: any;};Parameters that will be sent back to Auth0 as part of a request.
property cacheMode
cacheMode?: 'on' | 'off' | 'cache-only';When
off, ignores the cache and always sends a request to Auth0. Whencache-only, only reads from the cache and never sends a request to Auth0. Defaults toon, where it both reads from the cache and sends a request to Auth0 as needed.
property detailedResponse
detailedResponse?: boolean;If true, the full response from the /oauth/token endpoint (or the cache, if the cache was used) is returned (minus
refresh_tokenif one was issued). Otherwise, just the access token is returned.The default is
false.
property timeoutInSeconds
timeoutInSeconds?: number;A maximum number of seconds to wait before declaring the background /authorize call as failed for timeout Defaults to 60s.
interface GetTokenWithPopupOptions
interface GetTokenWithPopupOptions extends PopupLoginOptions {}property cacheMode
cacheMode?: 'on' | 'off' | 'cache-only';When
off, ignores the cache and always sends a request to Auth0. Whencache-only, only reads from the cache and never sends a request to Auth0. Defaults toon, where it both reads from the cache and sends a request to Auth0 as needed.
interface ICache
interface ICache {}interface IdToken
interface IdToken {}property acr
acr?: string;property address
address?: string;property amr
amr?: string[];property at_hash
at_hash?: string;property aud
aud?: string;property auth_time
auth_time?: string;property azp
azp?: string;property birthdate
birthdate?: string;property c_hash
c_hash?: string;property cnf
cnf?: string;property email
email?: string;property email_verified
email_verified?: boolean;property exp
exp?: number;property family_name
family_name?: string;property gender
gender?: string;property given_name
given_name?: string;property iat
iat?: number;property iss
iss?: string;property jti
jti?: string;property locale
locale?: string;property middle_name
middle_name?: string;property name
name?: string;property nbf
nbf?: number;property nickname
nickname?: string;property nonce
nonce?: string;property org_id
org_id?: string;property org_name
org_name?: string;property phone_number
phone_number?: string;property phone_number_verified
phone_number_verified?: boolean;property picture
picture?: string;property preferred_username
preferred_username?: string;property profile
profile?: string;property sid
sid?: string;property sub_jwk
sub_jwk?: string;property updated_at
updated_at?: string;property website
website?: string;property zoneinfo
zoneinfo?: string;index signature
[key: string]: any;interface JWTVerifyOptions
interface JWTVerifyOptions {}interface LogoutOptions
interface LogoutOptions extends LogoutUrlOptions {}property onRedirect
onRedirect?: (url: string) => Promise<void>;Used to control the redirect and not rely on the SDK to do the actual redirect.
Example 1
await auth0.logout({ async onRedirect(url) { window.location.replace(url); } });
Deprecated
since v2.0.1, use
openUrlinstead.
property openUrl
openUrl?: false | ((url: string) => Promise<void> | void);Used to control the redirect and not rely on the SDK to do the actual redirect.
Set to
falseto disable the redirect, or provide a function to handle the actual redirect yourself.Example 1
await auth0.logout({ openUrl(url) { window.location.replace(url); } });
Example 2
import { Browser } from '@capacitor/browser';
await auth0.logout({ async openUrl(url) { await Browser.open({ url }); } });
interface LogoutUrlOptions
interface LogoutUrlOptions {}property clientId
clientId?: string | null;The
clientIdof your application.If this property is not set, then the
clientIdthat was used during initialization of the SDK is sent to the logout endpoint.If this property is set to
null, then no client ID value is sent to the logout endpoint.[Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout)
property logoutParams
logoutParams?: { /** * When supported by the upstream identity provider, * forces the user to logout of their identity provider * and from Auth0. * [Read more about how federated logout works at Auth0](https://auth0.com/docs/logout/guides/logout-idps) */ federated?: boolean; /** * The URL where Auth0 will redirect your browser to after the logout. * * **Note**: If the `client_id` parameter is included, the * `returnTo` URL that is provided must be listed in the * Application's "Allowed Logout URLs" in the Auth0 dashboard. * However, if the `client_id` parameter is not included, the * `returnTo` URL must be listed in the "Allowed Logout URLs" at * the account level in the Auth0 dashboard. * * [Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout) */ returnTo?: string; /** * If you need to send custom parameters to the logout endpoint, make sure to use the original parameter name. */ [key: string]: any;};Parameters to pass to the logout endpoint. This can be known parameters defined by Auth0 or custom parameters you wish to provide.
interface OAuthTokenOptions
interface OAuthTokenOptions extends TokenEndpointOptions {}property audience
audience: string;property code
code: string;property code_verifier
code_verifier: string;property redirect_uri
redirect_uri: string;property scope
scope: string;interface OobEnrollmentResponse
interface OobEnrollmentResponse {}Response when enrolling an OOB authenticator
property authenticatorType
authenticatorType: 'oob';Authenticator type
property barcodeUri
barcodeUri?: string;URI for QR code (for Push/Guardian enrollment)
property bindingMethod
bindingMethod?: string;Binding method (e.g., 'prompt' for user code entry)
property id
id?: string;Authenticator ID
property oobChannel
oobChannel: OobChannel;Delivery channel used
property oobCode
oobCode?: string;Out-of-band code for verification
property recoveryCodes
recoveryCodes?: string[];Recovery codes (generated when enrolling first MFA factor)
interface OtpEnrollmentResponse
interface OtpEnrollmentResponse {}Response when enrolling an OTP authenticator
property authenticatorType
authenticatorType: 'otp';Authenticator type
property barcodeUri
barcodeUri: string;URI for generating QR code (otpauth://...)
property id
id?: string;Authenticator ID
property recoveryCodes
recoveryCodes?: string[];Recovery codes for account recovery
property secret
secret: string;Base32-encoded secret for TOTP generation
interface PopupConfigOptions
interface PopupConfigOptions {}property closePopup
closePopup?: boolean;Controls whether the SDK automatically closes the popup window.
-
true(default): SDK closes the popup automatically after receiving the authorization response -false: SDK does not close the popup. The caller is responsible for closing it, including on errors.Setting this to
falseis useful when you need full control over the popup lifecycle, such as in Chrome extensions where closing the popup too early can terminate the extension's service worker before authentication completes.When
closePopup: false, you should close the popup in a try/finally block:const popup = window.open('', '_blank');try {await auth0.loginWithPopup({}, { popup, closePopup: false });} finally {popup.close();}true
property popup
popup?: any;Accepts an already-created popup window to use. If not specified, the SDK will create its own. This may be useful for platforms like iOS that have security restrictions around when popups can be invoked (e.g. from a user click event)
property timeoutInSeconds
timeoutInSeconds?: number;The number of seconds to wait for a popup response before throwing a timeout error. Defaults to 60s
interface PopupLoginOptions
interface PopupLoginOptions extends BaseLoginOptions {}interface RedirectConnectAccountOptions
interface RedirectConnectAccountOptions<TAppState = any> {}property appState
appState?: TAppState;Optional application state to persist through the transaction.
Example 1
await auth0.connectAccountWithRedirect({ connection: 'google-oauth2', appState: { returnTo: '/settings' } });
property authorization_params
authorization_params?: AuthorizationParams;Additional authorization parameters for the request.
Example 1
await auth0.connectAccountWithRedirect({ connection: 'github', authorization_params: { audience: 'https://api.github.com' } });
property connection
connection: string;The name of the connection to link (e.g. 'google-oauth2').
property openUrl
openUrl?: (url: string) => Promise<void>;Optional function to handle the redirect URL.
Example 1
await auth0.connectAccountWithRedirect({ connection: 'google-oauth2', openUrl: async (url) => { myBrowserApi.open(url); } });
property redirectUri
redirectUri?: string;The URI to redirect back to after connecting the account.
property scopes
scopes?: string[];Array of scopes to request from the Identity Provider during the connect account flow.
Example 1
await auth0.connectAccountWithRedirect({ connection: 'google-oauth2', scopes: ['https://www.googleapis.com/auth/calendar'] });
interface RedirectLoginOptions
interface RedirectLoginOptions<TAppState = any> extends BaseLoginOptions {}property appState
appState?: TAppState;Used to store state before doing the redirect
property fragment
fragment?: string;Used to add to the URL fragment before redirecting
property onRedirect
onRedirect?: (url: string) => Promise<void>;Used to control the redirect and not rely on the SDK to do the actual redirect.
Example 1
const client = new Auth0Client({ async onRedirect(url) { window.location.replace(url); } });
Deprecated
since v2.0.1, use
openUrlinstead.
property openUrl
openUrl?: (url: string) => Promise<void> | void;Used to control the redirect and not rely on the SDK to do the actual redirect.
Example 1
const client = new Auth0Client({ openUrl(url) { window.location.replace(url); } });
Example 2
import { Browser } from '@capacitor/browser';
const client = new Auth0Client({ async openUrl(url) { await Browser.open({ url }); } });
interface RedirectLoginResult
interface RedirectLoginResult<TAppState = any> {}property appState
appState?: TAppState;State stored when the redirect request was made
property response_type
response_type: ResponseType.Code;The type of response, for login it will be
code
interface RefreshTokenOptions
interface RefreshTokenOptions extends TokenEndpointOptions {}property refresh_token
refresh_token: string;interface TokenEndpointOptions
interface TokenEndpointOptions {}property auth0Client
auth0Client: any;property baseUrl
baseUrl: string;property client_id
client_id: string;property dpop
dpop?: Pick<Dpop, 'generateProof' | 'getNonce' | 'setNonce'>;property grant_type
grant_type: string;property timeout
timeout?: number;property useFormData
useFormData?: boolean;index signature
[key: string]: any;interface VerifyParams
interface VerifyParams {}Parameters for verifying an MFA challenge.
The grant_type is automatically inferred from which verification field is provided: -
otpfield → MFA-OTP grant type -oobCodefield → MFA-OOB grant type -recoveryCodefield → MFA-RECOVERY-CODE grant type
property bindingCode
bindingCode?: string;Binding code (for OOB challenges with binding)
property mfaToken
mfaToken: string;MFA token from challenge flow
property oobCode
oobCode?: string;Out-of-band code (for OOB challenges)
property otp
otp?: string;One-time password (for OTP challenges)
property recoveryCode
recoveryCode?: string;Recovery code (for recovery code verification)
Enums
enum ResponseType
enum ResponseType { Code = 'code', ConnectCode = 'connect_code',}The types of responses expected from the authorization server. -
code: used for the standard login flow. -connect_code: used for the connect account flow.
member Code
Code = 'code'member ConnectCode
ConnectCode = 'connect_code'Type Aliases
type AuthenticatorType
type AuthenticatorType = 'otp' | 'oob' | 'recovery-code';Supported authenticator types. Note: Email authenticators use 'oob' type with oobChannel: 'email'
type Cacheable
type Cacheable = WrappedCacheEntry | KeyManifestEntry;type CacheEntry
type CacheEntry = { id_token?: string; token_type?: string; access_token: string; expires_in: number; decodedToken?: DecodedToken; audience: string; scope: string; client_id: string; refresh_token?: string; oauthTokenScope?: string;};type CacheKeyData
type CacheKeyData = { audience?: string; scope?: string; clientId: string;};type CacheLocation
type CacheLocation = 'memory' | 'localstorage';The possible locations where tokens can be stored
type ConnectAccountRedirectResult
type ConnectAccountRedirectResult<TAppState = any> = CompleteResponse & { /** * State stored when the redirect request was made */ appState?: TAppState; /** * The type of response, for connect account it will be `connect_code` */ response_type: ResponseType.ConnectCode;};The result returned after a successful account connection redirect.
Combines the redirect login result (including any persisted app state) with the complete response from the My Account API.
TAppState - The type of application state persisted through the transaction.
Example 1
const result = await auth0.connectAccountWithRedirect(options); console.log(result.appState); // Access persisted app state console.log(result.connection); // The connection of the account you connected to. console.log(result.response_type === 'connect_code'); // The response type will be 'connect_code'
type CustomFetchMinimalOutput
type CustomFetchMinimalOutput = { status: number; headers: ResponseHeaders;};type CustomTokenExchangeOptions
type CustomTokenExchangeOptions = { /** * The type identifier for the subject token being exchanged * * @pattern * - Must be a namespaced URI under your organization's control * - Forbidden patterns: * - `^urn:ietf:params:oauth:*` (IETF reserved) * - `^https:\/\/auth0\.com/*` (Auth0 reserved) * - `^urn:auth0:*` (Auth0 reserved) * * @example * "urn:acme:legacy-system-token" * "https://api.yourcompany.com/token-type/v1" */ subject_token_type: string; /** * The opaque token value being exchanged for Auth0 tokens * * @security * - Must be validated in Auth0 Actions using strong cryptographic verification * - Implement replay attack protection * - Recommended validation libraries: `jose`, `jsonwebtoken` * * @example * "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" */ subject_token: string; /** * The target audience for the requested Auth0 token * * @remarks * Must match exactly with an API identifier configured in your Auth0 tenant. * If not provided, falls back to the client's default audience. * * @example * "https://api.your-service.com/v1" */ audience?: string; /** * Space-separated list of OAuth 2.0 scopes being requested * * @remarks * Subject to API authorization policies configured in Auth0 * * @example * "openid profile email read:data write:data" */ scope?: string; /** * ID or name of the organization to use when authenticating a user. * When provided, the user will be authenticated using the organization context. * The organization ID will be present in the access token payload. */ organization?: string; /** * Additional custom parameters for Auth0 Action processing * * @remarks * Accessible in Action code via `event.request.body` * * @example * ```typescript * { * custom_parameter: "session_context", * device_fingerprint: "a3d8f7...", * } * ``` */ [key: string]: unknown;};Represents the configuration options required for initiating a Custom Token Exchange request following RFC 8693 specifications.
See Also
type EnrollmentResponse
type EnrollmentResponse = OtpEnrollmentResponse | OobEnrollmentResponse;Union type for all enrollment response types
type EnrollParams
type EnrollParams = | EnrollOtpParams | EnrollSmsParams | EnrollVoiceParams | EnrollEmailParams | EnrollPushParams;Union type for all enrollment parameter types
type FetcherConfig
type FetcherConfig<TOutput extends CustomFetchMinimalOutput> = { getAccessToken?: AccessTokenFactory; baseUrl?: string; fetch?: CustomFetchImpl<TOutput>; dpopNonceId?: string;};type FetchOptions
type FetchOptions = { method?: string; headers?: Record<string, string>; credentials?: 'include' | 'omit'; body?: string; signal?: AbortSignal;};type FetchResponse
type FetchResponse = { ok: boolean; headers: Record<string, string | undefined>; json: any;};type GetTokenSilentlyVerboseResponse
type GetTokenSilentlyVerboseResponse = Omit<TokenEndpointResponse, 'refresh_token'>;type KeyManifestEntry
type KeyManifestEntry = { keys: string[];};type MaybePromise
type MaybePromise<T> = Promise<T> | T;type MfaFactorType
type MfaFactorType = 'otp' | 'sms' | 'email' | 'push' | 'voice';Supported MFA factors for enrollment
type MfaGrantType
type MfaGrantType = (typeof MfaGrantTypes)[keyof typeof MfaGrantTypes];Grant types for MFA verification (derived from MfaGrantTypes constants)
type OobChannel
type OobChannel = 'sms' | 'voice' | 'auth0' | 'email';Out-of-band delivery channels. Includes 'email' which is also delivered out-of-band.
type TokenEndpointResponse
type TokenEndpointResponse = { id_token: string; token_type: string; access_token: string; refresh_token?: string; expires_in: number; scope?: string;};type WrappedCacheEntry
type WrappedCacheEntry = { body: Partial<CacheEntry>; expiresAt: number;};Package Files (13)
- dist/typings/Auth0Client.d.ts
- dist/typings/MyAccountApiClient.d.ts
- dist/typings/TokenExchange.d.ts
- dist/typings/cache/cache-localstorage.d.ts
- dist/typings/cache/cache-memory.d.ts
- dist/typings/cache/shared.d.ts
- dist/typings/errors.d.ts
- dist/typings/fetcher.d.ts
- dist/typings/global.d.ts
- dist/typings/index.d.ts
- dist/typings/mfa/MfaApiClient.d.ts
- dist/typings/mfa/errors.d.ts
- dist/typings/mfa/types.d.ts
Dependencies (4)
Dev Dependencies (47)
- @auth0/component-cdn-uploader
- @babel/core
- @babel/preset-env
- @rollup/plugin-babel
- @rollup/plugin-commonjs
- @rollup/plugin-node-resolve
- @rollup/plugin-replace
- @types/cypress
- @types/jest
- @typescript-eslint/eslint-plugin-tslint
- @typescript-eslint/parser
- browserstack-cypress-cli
- cli-table
- concurrently
- cypress
- es-check
- eslint
- eslint-plugin-security
- fake-indexeddb
- gzip-size
- husky
- idtoken-verifier
- jest
- jest-environment-jsdom
- jest-fetch-mock
- jest-junit
- jest-localstorage-mock
- jsonwebtoken
- oidc-provider
- prettier
- pretty-quick
- rimraf
- rollup
- rollup-plugin-analyzer
- rollup-plugin-dev
- rollup-plugin-livereload
- rollup-plugin-sourcemaps
- rollup-plugin-terser
- rollup-plugin-typescript2
- rollup-plugin-visualizer
- rollup-plugin-web-worker-loader
- serve
- ts-jest
- tslib
- typedoc
- typescript
- wait-on
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@auth0/auth0-spa-js.
- Markdown[](https://www.jsdocs.io/package/@auth0/auth0-spa-js)
- HTML<a href="https://www.jsdocs.io/package/@auth0/auth0-spa-js"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 7188 ms. - Missing or incorrect documentation? Open an issue for this package.
