@auth0/auth0-spa-js

中文文档
2.30.0发布于 2026/10/29MITTypeScriptESM + CJS构建来源已验证近 30 天下载 1177.5万

Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE

原始使用文档
文档目录17 节
  1. Documentation
  2. Getting Started
  3. Installation
  4. Configure Auth0
  5. Configure the SDK
  6. Logging In
  7. Online Access
  8. Experiment Center
  9. Anonymous Sessions
  10. More Examples
  11. API Reference
  12. Enterprise Connect
  13. Feedback
  14. Contributing
  15. Raise an issue
  16. Vulnerability Reporting
  17. What is Auth0?

Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE.

npm version Codecov Ask DeepWiki Downloads License CircleCI

📚 Documentation - 🚀 Getting Started - 💻 API Reference - 💬 Feedback

Documentation

  • Quickstart - our interactive guide for quickly adding login, logout and user information to your app using Auth0.
  • Sample app - a full-fledged sample app integrated with Auth0.
  • FAQs - frequently asked questions about auth0-spa-js SDK.
  • Examples - code samples for common scenarios.
  • Docs Site - explore our Docs site and learn more about Auth0.

Getting Started

Installation

Using npm in your project directory run the following command:

npm install @auth0/auth0-spa-js

From the CDN:

<script src="https://cdn.auth0.com/js/auth0-spa-js/2.30/auth0-spa-js.production.js"></script>

Configure Auth0

Create a Single Page Application in the Auth0 Dashboard.

If you're using an existing application, verify that you have configured the following settings in your Single Page Application:

  • Click on the "Settings" tab of your application's page.
  • Scroll down and click on the "Show Advanced Settings" link.
  • Under "Advanced Settings", click on the "OAuth" tab.
  • Ensure that "JsonWebToken Signature Algorithm" is set to RS256 and that "OIDC Conformant" is enabled.

Next, configure the following URLs for your application under the "Application URIs" section of the "Settings" page:

  • Allowed Callback URLs: http://localhost:3000
  • Allowed Logout URLs: http://localhost:3000
  • Allowed Web Origins: http://localhost:3000

These URLs should reflect the origins that your application is running on. Allowed Callback URLs may also include a path, depending on where you're handling the callback (see below).

Take note of the Client ID and Domain values under the "Basic Information" section. You'll need these values in the next step.

Configure the SDK

Create an Auth0Client instance before rendering or initializing your application. You should only have one instance of the client.

import { createAuth0Client } from '@auth0/auth0-spa-js';

//with async/await
const auth0 = await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  authorizationParams: {
    redirect_uri: '<MY_CALLBACK_URL>'
  }
});

//or, you can just instantiate the client on its own
import { Auth0Client } from '@auth0/auth0-spa-js';

const auth0 = new Auth0Client({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  authorizationParams: {
    redirect_uri: '<MY_CALLBACK_URL>'
  }
});

//if you do this, you'll need to check the session yourself
try {
  await auth0.getTokenSilently();
} catch (error) {
  if (error.error !== 'login_required') {
    throw error;
  }
}

Logging In

You can then use login using the Auth0Client instance you created:

<button id="login">Click to Login</button>
//redirect to the Universal Login Page
document.getElementById('login').addEventListener('click', async () => {
  await auth0.loginWithRedirect();
});

//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', async () => {
  const redirectResult = await auth0.handleRedirectCallback();
  //logged in. you can get the user profile like this:
  const user = await auth0.getUser();
  console.log(user);
});

Online Access

[!NOTE] Online Access (Online Refresh Tokens) support via SDKs is currently in Early Access. To request access to this feature, contact your Auth0 representative.

[!WARNING] Online Refresh Tokens do not currently support resource servers with Ephemeral Sessions enabled. Enabling both allow_online_access and "Allow for Ephemeral Sessions" on the same resource server results in the authorization server issuing an Online Refresh Token that is then rejected (invalid_grant) on the very next refresh. Until Ephemeral Sessions support is added for Online Refresh Tokens, disable "Allow for Ephemeral Sessions" on any resource server used with refreshTokenMode: RefreshTokenMode.Online.

Set refreshTokenMode to RefreshTokenMode.Online (together with the required useRefreshTokens: true and useDpop: true) to use Online Refresh Tokens — non-rotating refresh tokens bound to the Auth0 session lifetime. The SDK injects the online_access scope and routes renewal through the refresh-token grant.

import { createAuth0Client, RefreshTokenMode } from '@auth0/auth0-spa-js';

const auth0 = await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  useRefreshTokens: true,
  refreshTokenMode: RefreshTokenMode.Online,
  useDpop: true,
  authorizationParams: {
    redirect_uri: '<MY_CALLBACK_URL>'
  }
});

refreshTokenMode is a sub-option of useRefreshTokens: it defaults to RefreshTokenMode.Offline (the rotating refresh tokens described above) and must be set to RefreshTokenMode.Online for Online Refresh Tokens. Online mode requires both useRefreshTokens: true and useDpop: true. See Online Access for the full guide.

Experiment Center

[!NOTE] Experiment Center support via SDKs is currently in Early Access. To request access to this feature, contact your Auth0 representative.

Experiment Center lets you A/B test your login flow. Auth0 assigns each user to a variant server-side. When you need to force a specific variant — for testing or to apply a decision from a feature-flag tool — pass experiment_id and variation_id on the login call:

await auth0.loginWithRedirect({
  authorizationParams: {
    experiment_id: '<EXPERIMENT_ID>',
    variation_id: '<VARIATION_ID>'
  }
});

The override applies to that request only. The next login without these params reverts to normal server-side assignment.

Pass these per-call rather than in the authorizationParams at client construction time, so the override does not affect silent prompt=none token-renewal calls (Experiment Center does not run on those).

For testing: drive from test automation (e.g. Cypress, Playwright) with IDs read from a CI environment variable against a staging tenant. Do not hard-code variant IDs in shipped application code.

For production: pass the variant decision from a feature-flag tool (e.g. LaunchDarkly) that has already decided which variant the user should see.

Anonymous Sessions

[!NOTE] Anonymous Sessions support via SDKs is currently in Early Access. To request access to this feature, contact your Auth0 representative.

Anonymous sessions assign a persistent identity to a visitor before they log in. Set createAnonymousSessionOnFailedSilentAuth: true to have the SDK create an anonymous session automatically when checkSession() finds no authenticated user.

// createAuth0Client calls checkSession() internally — the anonymous session is ready on init
const auth0 = await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  createAnonymousSessionOnFailedSilentAuth: true,

  // default is 'localStorage'; use 'memory' if you don't want persistence
  anonymousSessionsCacheMode: 'localStorage'
});

const { accessToken } = await auth0.anonymous.getTokenSilently({
  audience: 'https://api.example.com'
});

See Anonymous Sessions for the full guide including explicit session creation with metadata, multiple audiences, and logout.

More Examples

For comprehensive examples covering various scenarios including logging out, calling APIs, refresh tokens, online access, organizations, passkeys, MFA, DPoP, and more, see the EXAMPLES.md document.

API Reference

Explore API Methods available in auth0-spa-js.

Enterprise Connect

Enterprise Connect lets B2B SaaS applications add enterprise SSO without replacing their existing auth stack. The SDK exports isFederatedDomain for email-domain discovery; you then start the login with loginWithRedirect using the email as login_hint. See EXAMPLES.md#enterprise-connect for the full setup and flow.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

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 Logo

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/auth0-spa-js 共发布 138 个版本,首次发布于 2019/03/26;过去 12 个月发布了 41 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.30.0latest2026/10/299 天前
2.29.02026/10/2117 天前
2.28.42026/10/1424 天前
2.28.32026/10/0929 天前
2.28.22026/10/021 个月前
2.28.12026/10/011 个月前

其他发布通道:beta → 2.0.0-beta.1。

关于 @auth0/auth0-spa-js 的常见问题

@auth0/auth0-spa-js 是什么?

Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE

如何安装 @auth0/auth0-spa-js?

在项目目录运行 npm install @auth0/auth0-spa-js,或使用 pnpm add / yarn add / bun add。

@auth0/auth0-spa-js 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@auth0/auth0-spa-js 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@auth0/auth0-spa-js 可以商用吗?

@auth0/auth0-spa-js 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@auth0/auth0-spa-js 的下载量有多少?

根据 npm 官方下载统计,@auth0/auth0-spa-js 在 2026/10/07 – 2026/11/05 这 30 天内被下载 11,775,270 次,日均约 392,509 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@auth0/auth0-spa-js 还在维护吗?

最新版本 2.30.0 发布于 2026/10/29(9 天前);至今共发布 138 个版本,其中过去 12 个月发布了 41 个;首次发布于 2019/03/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。