auth0-spa-js

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 SPA JS Integration

Auth0 SPA JS 集成

Add authentication to any browser-based single-page application using
@auth0/auth0-spa-js
— the low-level Auth0 SDK for Vanilla JS, Svelte, SolidJS, and any SPA not using React, Angular, or Vue.
Agent instruction: Before providing SDK setup instructions, fetch the latest release version by running:
gh api repos/auth0/auth0-spa-js/releases/latest --jq '.tag_name'
Use the returned version in all dependency lines instead of any hardcoded version below. If the command fails, fall back to checking https://github.com/auth0/auth0-spa-js/releases.
使用
@auth0/auth0-spa-js
为任何基于浏览器的单页应用添加认证功能——这是适用于Vanilla JS、Svelte、SolidJS以及未使用React、Angular或Vue的SPA的底层Auth0 SDK。
Agent 指令: 在提供SDK设置说明前,运行以下命令获取最新版本:
gh api repos/auth0/auth0-spa-js/releases/latest --jq '.tag_name'
将返回的版本替换下方所有依赖行中的硬编码版本。若命令执行失败,可访问https://github.com/auth0/auth0-spa-js/releases查询。

Prerequisites

前置条件

  • Modern browser with ES2017+ support
  • npm or yarn (or use CDN for no-bundler apps)
  • Auth0 account with a Single Page Application configured
  • If you don't have Auth0 set up, see auth0-quickstart
  • 支持ES2017+的现代浏览器
  • npm或yarn(无打包工具的应用可使用CDN)
  • 已配置单页应用的Auth0账户
  • 若未设置Auth0,可查看auth0-quickstart

When NOT to Use

不适用于以下场景

Quick Start Workflow

快速开始流程

1. Install SDK

1. 安装SDK

bash
npm install @auth0/auth0-spa-js
Or via CDN (no bundler). Run this to get the latest version, then use it in your HTML:
bash
VERSION=$(npm view @auth0/auth0-spa-js version)
html
<script src="https://cdn.auth0.com/js/auth0-spa-js/$VERSION/auth0-spa-js.production.js"></script>
bash
npm install @auth0/auth0-spa-js
或通过CDN(无需打包工具)。先运行以下命令获取最新版本,再在HTML中使用:
bash
VERSION=$(npm view @auth0/auth0-spa-js version)
html
<script src="https://cdn.auth0.com/js/auth0-spa-js/$VERSION/auth0-spa-js.production.js"></script>

2. Configure Auth0

2. 配置Auth0

For automated setup with Auth0 CLI, see Setup Guide for complete scripts.
For manual setup, create
.env
(Vite):
bash
VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-id
In Auth0 Dashboard, set for your Single Page Application:
  • Allowed Callback URLs:
    http://localhost:5173
  • Allowed Logout URLs:
    http://localhost:5173
  • Allowed Web Origins:
    http://localhost:5173
使用Auth0 CLI自动配置,可查看设置指南获取完整脚本。
手动配置,创建
.env
文件(适用于Vite):
bash
VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-id
在Auth0控制台中,为你的单页应用设置:
  • 允许回调URL
    http://localhost:5173
  • 允许登出URL
    http://localhost:5173
  • 允许Web源
    http://localhost:5173

3. Initialize Auth0 Client

3. 初始化Auth0客户端

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

const auth0 = await createAuth0Client({
  domain: import.meta.env.VITE_AUTH0_DOMAIN,
  clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
  authorizationParams: {
    redirect_uri: window.location.origin
  }
});

// Handle redirect callback after login
const query = new URLSearchParams(window.location.search);
if ((query.has('code') || query.has('error')) && query.has('state')) {
  await auth0.handleRedirectCallback();
  window.history.replaceState({}, document.title, window.location.pathname);
}
js
import { createAuth0Client } from '@auth0/auth0-spa-js';

const auth0 = await createAuth0Client({
  domain: import.meta.env.VITE_AUTH0_DOMAIN,
  clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
  authorizationParams: {
    redirect_uri: window.location.origin
  }
});

// 处理登录后的重定向回调
const query = new URLSearchParams(window.location.search);
if ((query.has('code') || query.has('error')) && query.has('state')) {
  await auth0.handleRedirectCallback();
  window.history.replaceState({}, document.title, window.location.pathname);
}

4. Add Login / Logout

4. 添加登录/登出功能

Agent instruction: Before adding new UI elements, search the project for existing click handlers for login, logout, sign-in, or sign-out buttons. If existing handlers are found, hook the Auth0 code into them without modifying the existing UI. Only create new buttons if no existing handlers are found.
js
// Login
document.getElementById('login-btn').addEventListener('click', async () => {
  await auth0.loginWithRedirect();
});

// Logout
document.getElementById('logout-btn').addEventListener('click', () => {
  auth0.logout({
    logoutParams: { returnTo: window.location.origin }
  });
});

// Update UI based on auth state
const isAuthenticated = await auth0.isAuthenticated();
if (isAuthenticated) {
  const user = await auth0.getUser();
  console.log(user.name, user.email);
}
Agent 指令: 在添加新UI元素前,搜索项目中已有的登录、登出按钮点击处理器。若存在已有处理器,将Auth0代码接入其中,无需修改现有UI。仅在无现有处理器时创建新按钮。
js
// 登录
document.getElementById('login-btn').addEventListener('click', async () => {
  await auth0.loginWithRedirect();
});

// 登出
document.getElementById('logout-btn').addEventListener('click', () => {
  auth0.logout({
    logoutParams: { returnTo: window.location.origin }
  });
});

// 根据认证状态更新UI
const isAuthenticated = await auth0.isAuthenticated();
if (isAuthenticated) {
  const user = await auth0.getUser();
  console.log(user.name, user.email);
}

5. Get Access Tokens for API Calls

5. 获取访问令牌用于API调用

js
const accessToken = await auth0.getTokenSilently();

const response = await fetch('https://your-api.example.com/data', {
  headers: { Authorization: `Bearer ${accessToken}` }
});
js
const accessToken = await auth0.getTokenSilently();

const response = await fetch('https://your-api.example.com/data', {
  headers: { Authorization: `Bearer ${accessToken}` }
});

6. Build & Verify

6. 构建与验证

Agent instruction: After completing the integration, build the project to verify it compiles successfully:
bash
npm run build
If the build fails, analyze the error output and fix the issues. Common integration build failures include:
  • Module not found: Missing
    npm install @auth0/auth0-spa-js
    — run the install command
  • Cannot find name 'import.meta': TypeScript target too low — set
    "target": "ES2020"
    or higher in
    tsconfig.json
  • createAuth0Client
    is not a function
    : Wrong import path or CDN usage without bundle step
  • Env vars undefined at runtime: Vite requires
    VITE_
    prefix; webpack/CRA requires
    REACT_APP_
    prefix
Re-run the build after each fix. Track the number of build-fix iterations.
Failcheck: If the build still fails after 5–6 fix attempts, stop and ask the user using
AskUserQuestion
: "The build is still failing after several fix attempts. How would you like to proceed?"
  • Let the skill continue fixing iteratively — continue the build-fix loop for another 5–6 attempts
  • Fix it manually — show the remaining errors and let the user resolve them
  • Skip build verification — proceed without a successful build
Agent 指令: 完成集成后,构建项目以验证编译是否成功:
bash
npm run build
若构建失败,分析错误输出并修复问题。常见集成构建失败原因包括:
  • 模块未找到:缺少
    npm install @auth0/auth0-spa-js
    ——执行安装命令
  • 找不到名称'import.meta':TypeScript目标版本过低——在
    tsconfig.json
    中设置
    "target": "ES2020"
    或更高版本
  • createAuth0Client
    不是函数
    :导入路径错误或未通过打包步骤使用CDN
  • 运行时环境变量未定义:Vite要求变量前缀为
    VITE_
    ;webpack/CRA要求前缀为
    REACT_APP_
每次修复后重新运行构建。记录构建-修复迭代次数。
失败检查: 若经过5-6次修复尝试后构建仍失败,停止操作并使用
AskUserQuestion
询问用户: "经过多次修复尝试后,构建仍失败。你希望如何继续?"
  • 让技能继续迭代修复——继续进行5-6次构建-修复循环
  • 手动修复——显示剩余错误,由用户自行解决
  • 跳过构建验证——无需成功构建直接继续

Detailed Documentation

详细文档

  • Setup Guide — Automated setup scripts (Bash/PowerShell), Auth0 CLI commands,
    .env
    configuration, callback URL setup
  • Integration Patterns — Token management, calling APIs, refresh tokens, organizations, MFA, DPoP, error handling, advanced patterns
  • Testing & Reference — Configuration options, claims reference, testing checklist, common issues, security considerations
  • 设置指南——自动化设置脚本(Bash/PowerShell)、Auth0 CLI命令、
    .env
    配置、回调URL设置
  • 集成模式——令牌管理、API调用、刷新令牌、组织、MFA、DPoP、错误处理、进阶模式
  • 测试与参考——配置选项、声明参考、测试清单、常见问题、安全注意事项

Common Mistakes

常见错误

MistakeFix
Callback URL port mismatch (e.g.,
localhost:3001
vs
localhost:5173
)
Match Allowed Callback URLs exactly to your dev server port in Auth0 Dashboard
client_secret
in SPA code
SPAs must never have a client secret — remove it. Auth0 sets auth method to
None
for SPA apps
Tokens stored in
localStorage
Use in-memory storage (default) or
sessionStorage
. Never
localStorage
— XSS risk
getTokenSilently()
throws
login_required
on page refresh
Add your app origin to Allowed Web Origins in Auth0 Dashboard
handleRedirectCallback()
not called after redirect
Must call after login redirect to exchange the auth code; without this the URL params persist and re-trigger
Domain includes
https://
prefix
Auth0 domain should be hostname only:
your-tenant.auth0.com
, not
https://your-tenant.auth0.com
loginWithPopup()
called from async init code
Popups must be triggered directly from a user gesture (click handler). Never call from init or page load code
Using
Auth0Provider
from
@auth0/auth0-react
in Vanilla JS
For Vanilla JS, use
createAuth0Client()
directly — no provider component needed
错误修复方案
回调URL端口不匹配(如
localhost:3001
vs
localhost:5173
在Auth0控制台中,确保允许回调URL与开发服务器端口完全一致
SPA代码中包含
client_secret
SPA绝不能包含客户端密钥——删除该密钥。Auth0会为SPA应用设置认证方式为
None
令牌存储在
localStorage
使用内存存储(默认)或
sessionStorage
。绝不能使用
localStorage
——存在XSS风险
页面刷新时
getTokenSilently()
抛出
login_required
错误
在Auth0控制台中,将应用源添加至允许Web源
重定向后未调用
handleRedirectCallback()
登录重定向后必须调用该方法以交换认证码;否则URL参数会保留并重复触发
域名包含
https://
前缀
Auth0域名应仅为主机名:
your-tenant.auth0.com
,而非
https://your-tenant.auth0.com
在异步初始化代码中调用
loginWithPopup()
弹窗必须由用户手势(点击处理器)直接触发。绝不能在初始化或页面加载代码中调用
在Vanilla JS中使用
@auth0/auth0-react
Auth0Provider
对于Vanilla JS,直接使用
createAuth0Client()
——无需Provider组件

Related Skills

相关技能

Quick Reference

快速参考

Core Methods

核心方法

MethodDescription
createAuth0Client(options)
Create and initialize client (calls
checkSession
internally)
new Auth0Client(options)
Instantiate without auto session check
auth0.loginWithRedirect(options?)
Redirect to Auth0 Universal Login
auth0.loginWithPopup(options?)
Open Auth0 login in a popup
auth0.logout(options?)
Clear session and redirect
auth0.handleRedirectCallback(url?)
Process redirect result after login
auth0.isAuthenticated()
Promise<boolean>
auth0.getUser()
Promise<User | undefined>
auth0.getTokenSilently(options?)
Promise<string>
— access token
auth0.checkSession()
Attempt silent re-authentication
方法描述
createAuth0Client(options)
创建并初始化客户端(内部调用
checkSession
new Auth0Client(options)
实例化客户端,不自动检查会话
auth0.loginWithRedirect(options?)
重定向至Auth0 Universal Login
auth0.loginWithPopup(options?)
在弹窗中打开Auth0登录界面
auth0.logout(options?)
清除会话并重定向
auth0.handleRedirectCallback(url?)
处理登录后的重定向结果
auth0.isAuthenticated()
返回
Promise<boolean>
auth0.getUser()
返回
Promise<User | undefined>
auth0.getTokenSilently(options?)
返回
Promise<string>
——访问令牌
auth0.checkSession()
尝试静默重新认证

Common Use Cases

常见使用场景

  • Login/Logout → See Step 4 above
  • Protecting content → Integration Guide
  • API calls with tokens → Integration Guide
  • Refresh tokens → Integration Guide
  • Organizations → Integration Guide
  • MFA handling → Integration Guide
  • Error handling → Integration Guide
  • 登录/登出 → 见上方步骤4
  • 内容保护 → 集成指南
  • 使用令牌调用API → 集成指南
  • 刷新令牌 → 集成指南
  • 组织管理 → 集成指南
  • MFA处理 → 集成指南
  • 错误处理 → 集成指南

References

参考链接