The @auth0/auth0-auth-js library provides API's to interact with Auth0's Authentication Api's from withing JavaScript applications.
It contains methods to build Authorization URLs and Logout URLs, implement Backchannel Logout, verifying a logout token, to request Tokens using the Authorization Code Flow and Refresh Tokens, as well as retrieving a Token for a Connection, and managing Multi-Factor Authentication (MFA).
The AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET can be obtained from the Auth0 Dashboard once you've created an application.
3. Build the Authorization URL
Build the URL to redirect the user-agent to to request authorization at Auth0.
const authClient = newAuthClient({
// ...authorizationParams: {
redirect_uri: '<AUTH0_REDIRECT_URI>',
},
// ...
});
The`AUTH0_REDIRECT_URI` is needed to tell Auth0 what URL to redirect back to after successfull authentication, e.g. `http://localhost:3000/auth/callback`.
[!IMPORTANT]
You will need to register the AUTH0_REDIRECT_URI in your Auth0 Application as an Allowed Callback URL via the Auth0 Dashboard.
In order to build the authorization URL, call buildAuthorizationUrl(), and redirect the user to the returned URL.
[!IMPORTANT]
You will need to register the AUTH0_LOGOUT_RETURN_URL in your Auth0 Application as an Allowed Logout URL via the Auth0 Dashboard.
The AUTH0_LOGOUT_RETURN_URL is needed to tell Auth0 what URL to redirect back to after successfully logging out, e.g. http://localhost:3000.
5. Token Exchange
The SDK supports RFC 8693 OAuth 2.0 Token Exchange for first-party on-behalf-of flows, enabling secure token exchanges while preserving user identity.
When to Use Which Flow
Custom Token Exchange: Use when you control the subject token format. Common scenarios:
Exchanging MCP server tokens for Auth0 tokens
Migrating from legacy authentication systems
Federating with partner systems using custom token formats
Exchanging tokens issued by your own services
Access Token Exchange with Token Vault (via exchangeToken): Use when exchanging for external provider's access tokens:
Accessing Google APIs with a user's Google token
Calling Facebook Graph API with a user's Facebook token
Any scenario where Auth0 manages the external provider's refresh tokens in the Token Vault
Deprecated:getTokenForConnection() is deprecated. Use exchangeToken({ connection, subjectToken, subjectTokenType, ... }) instead.
Custom Token Exchange Example
Note: In this SDK, Custom Token Exchange currently requires a confidential client. Supported client authentication methods: client_secret_post, private_key_jwt, and mTLS (via customFetch). Public clients are not yet supported by this method.
import { AuthClient } from'@auth0/auth0-auth-js';
const authClient = newAuthClient({
domain: '<AUTH0_DOMAIN>',
clientId: '<AUTH0_CLIENT_ID>',
clientSecret: '<AUTH0_CLIENT_SECRET>',
});
// Exchange a custom token (e.g., from an MCP server or legacy system)// The subjectTokenType identifies your token format (configured in your Token Exchange Profile)const response = await authClient.exchangeToken({
subjectTokenType: 'urn:example:custom-token', // Your custom token type URNsubjectToken: userAccessToken, // The token to exchangeaudience: 'https://api.backend.com',
});
// Handle token expiry - check expiresAt and re-exchange when needed// Note: expiresAt is in seconds, Date.now() is in millisecondsconst tokenIsValid = Math.floor(Date.now() / 1000) < response.expiresAt;
if (!tokenIsValid) {
// Re-exchange the token or use a refresh token if availableconst refreshed = await authClient.exchangeToken({
subjectTokenType: 'urn:example:custom-token',
subjectToken: newSubjectToken,
audience: 'https://api.backend.com',
});
}
Security Note: Never include PII, secrets, or sensitive data in the extra parameter.
These values may be logged by Auth0 or intermediary systems. Use extra only for
non-sensitive metadata like device IDs, session identifiers, or request context.
Token Vault Example
import { AuthClient } from'@auth0/auth0-auth-js';
const authClient = newAuthClient({
domain: '<AUTH0_DOMAIN>',
clientId: '<AUTH0_CLIENT_ID>',
clientSecret: '<AUTH0_CLIENT_SECRET>',
});
// Exchange an Auth0 access token for an external provider's access token (e.g., Google)const response = await authClient.exchangeToken({
connection: 'google-oauth2',
subjectToken: auth0AccessToken,
subjectTokenType: 'urn:ietf:params:oauth:token-type:access_token',
loginHint: 'user@example.com', // Optional: specify which account when user has multiplescope: 'https://www.googleapis.com/auth/calendar.readonly', // Optional: specific scopes
});
// Or exchange an Auth0 refresh token insteadconst responseFromRefresh = await authClient.exchangeToken({
connection: 'google-oauth2',
subjectToken: auth0RefreshToken,
subjectTokenType: 'urn:ietf:params:oauth:token-type:refresh_token',
});
// Use the external provider's access tokenconsole.log('External access token:', response.accessToken);
Migration from deprecated getTokenForConnection()
// ❌ Deprecated (still works, but will be removed in v2.0)const response = await authClient.getTokenForConnection({
connection: 'google-oauth2',
accessToken: auth0AccessToken,
loginHint: 'user@example.com',
});
// âś… New unified APIconst response = await authClient.exchangeToken({
connection: 'google-oauth2',
subjectToken: auth0AccessToken,
subjectTokenType: 'urn:ietf:params:oauth:token-type:access_token',
loginHint: 'user@example.com',
});
[!WARNING]
This flow should only be used from highly-trusted applications that cannot do redirects. If you can use redirect-based flows from your app, we recommend using the Authorization Code Flow instead.
The SDK supports Resource Owner Password Grant (ROPG) for scenarios where users authenticate by providing their username and password directly:
The SDK provides built-in support for managing Multi-Factor Authentication. You can enroll authenticators (OTP, SMS, email), list enrolled authenticators, challenge them for verification, and delete them.
// Access the MFA client via the authClient.mfa propertyconst mfaToken = '<mfa_token_from_mfa_error>';
// Enroll an OTP authenticator (Google Authenticator, Auth0, etc.)const enrollment = await authClient.mfa.enrollAuthenticator({
authenticatorTypes: ['otp'],
mfaToken
});
// List all enrolled authenticatorsconst authenticators = await authClient.mfa.listAuthenticators({ mfaToken });
// Challenge an authenticatorconst challenge = await authClient.mfa.challengeAuthenticator({
challengeType: 'otp',
mfaToken
});
// Delete an authenticatorawait authClient.mfa.deleteAuthenticator({
authenticatorId: 'totp|dev_abc123',
mfaToken
});
For detailed MFA examples including SMS enrollment, OOB challenges, and more, see the MFA section in EXAMPLES.md.
8. More Examples
A full overview of examples can be found in EXAMPLES.md.
Feedback
Contributing
We appreciate feedback and contribution to this repo! Before you get started, please read the following:
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
What is Auth0?
Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?
This project is licensed under the MIT license. See the LICENSE file for more info.
Auth0 Authentication Client for JavaScript runtimes.
The npm package @auth0/auth0-auth-js receives a total of 697,911 weekly downloads. As such, @auth0/auth0-auth-js popularity was classified as popular.
We found that @auth0/auth0-auth-js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 16 open source maintainers collaborating on the project.
Package last updated on 24 Mar 2026
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
The remediated findings include organization permission bugs, stale project access after transfers, OIDC replay edge cases, audit logging gaps, and an IDOR in API token deletion.
GitHub account BufferZoneCorp published sleeper packages that later added credential theft, GitHub Actions tampering, fake go wrappers, and SSH persistence.