@descope/web-component

中文文档
4.7.0发布于 2026/11/08MITTypeScriptESM + CJS近 30 天下载 153.9万

Descope WC

原始使用文档
文档目录17 节
  1. Usage
  2. Install the package
  3. As a library
  4. In HTML file
  5. Run Example
  6. Security Features
  7. Subresource Integrity (SRI)
  8. Cross-origin OAuth popups
  9. Optional Attributes
  10. Optional Properties
  11. errorTransformer - A function that receives an error object…
  12. logger - An object that defines how to log error, warning a…
  13. onScreenUpdate
  14. Events
  15. error - Fired when an error occurs. The event detail contai…
  16. success - Fired when the flow is completed successfully. Th…
  17. ready - Fired when the page is ready.

@descope/web-component

Create your login pages on our console-app, once done, you can use this library to inject those pages to your app
it registers- a web component and update the web-component content based on the relevant page, See usage example below

Usage

Install the package

npm install @descope/web-component

As a library

import '@descope/web-component' // This import will define `descope-wc` custom element
import { DescopeWc } // In case you need types definition or you want to use the class directly

// Render Descope Web Component, for example:
render(){
  return (
    <descope-wc project-id="myProjectId"/>
  )
}

In HTML file

  • Copy the file @descope/web-component/dist/index.js rename it to descope-wc.js and place it where your HTML file is located

  • Add the following script tag to your HTML file

<head>
  <script src="./descope-wc.js"></script>
</head>
  • Now you can add the custom element to your HTML
<descope-wc project-id="<project-id>" flow-id="<flow-id>" form='{ "email": "[email protected]", "myCustomInput": "12" }' client='{ "browserVersion": window.navigator.appVersion }'></descope-wc>
  • Note: the form and client are optional parameters to add additional information that can be used in the flow. For more information click here.

Run Example

To run the example:

  1. Install dependencies pnpm i
  2. Create a .env file and the following variables:
// .env
# Descope Project ID
DESCOPE_PROJECT_ID=<project-id>
# Flow ID to run, e.g. sign-up-or-in
DESCOPE_FLOW_ID=<flow-id>
# Optional - Descope base URL
DESCOPE_BASE_URL
# Optional - Descope locale (according to the target locales configured in the flow)
DESCOPE_LOCALE=<locale>

# Telemetry fallback config (AWS CloudWatch RUM).
# Optional — used by the SDK only when the backend's config.json doesn't
# ship a `telemetry` block. Once it does, these are ignored.
# Leave DESCOPE_TELEMETRY_ENABLED unset or set to anything other than
# "true" to keep the fallback off.
DESCOPE_TELEMETRY_ENABLED=<true|false>
DESCOPE_TELEMETRY_APPLICATION_ID=<cloudwatch-rum-app-monitor-id>
DESCOPE_TELEMETRY_IDENTITY_POOL_ID=<aws-cognito-identity-pool-id>
DESCOPE_TELEMETRY_REGION=<aws-region>
# Optional — only required for the classic Cognito flow.
DESCOPE_TELEMETRY_GUEST_ROLE_ARN=<iam-guest-role-arn>
# Optional — 0..1, defaults to 1 (capture every session).
DESCOPE_TELEMETRY_SESSION_SAMPLE_RATE=1
  1. Run the sample pnpm run start / pnpm run start-web-sample

NOTE: This package is a part of a monorepo. so if you make changes in a dependency, you will have to rerun npm run start / pnpm run start-web-sample (this is a temporary solution until we improve the process to fit to monorepo).

Security Features

Subresource Integrity (SRI)

The web component automatically applies Subresource Integrity (SRI) checks to the web-components-ui loader when the SRI hash is available in the project configuration. This provides cryptographic verification that the loaded script has not been tampered with.

How it works:

  1. The Descope orchestration service generates SRI hashes for each version of the web-components-ui library
  2. The hash is included in the config.json as componentsVersionSri
  3. The web component automatically adds integrity and crossorigin attributes to the script tag
  4. The browser verifies the script integrity before executing it

Example generated script tag:

<script src="https://descopecdn.com/npm/@descope/[email protected]/dist/umd/index.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K..." crossorigin="anonymous"></script>

Content Security Policy (CSP) compatibility:

SRI works seamlessly with CSP. For strict CSP configurations, combine SRI with the nonce attribute:

<descope-wc project-id="myProjectId" flow-id="sign-up-or-in" nonce="random-nonce-value"></descope-wc>

CSP header example:

Content-Security-Policy:
  script-src 'self'
    https://descopecdn.com
    https://static.descope.com
    https://cdn.jsdelivr.net
    'nonce-random-nonce-value';

Backward compatibility:

If the SRI hash is not available in the configuration (older projects), the component will load normally without integrity checks. No breaking changes required.

Cross-origin OAuth popups

When the OAuth popup's redirect page is on a different origin than the page that opens it (see popup-origin), the popup sends the OAuth result only to the opener origin Descope attests for that popup. Descope attests the origin of the page that opened the popup when it is one of the project's approved domains, or when the project has no approved domains. Otherwise the popup answers only over a same-origin BroadcastChannel, so list the main application's domain in the project's approved domains.

Optional Attributes

AttributeAvailable optionsDefault value
base-urlCustom Descope base URL""
theme"light" - Light theme
"dark" - Dark theme
"os" - Auto select a theme based on the OS theme settings
"light"
debug"true" - Enable debugger
"false" - Disable debugger
"false"
preview"true" - Run flow in a preview mode
"false" - Do run flow in a preview mode
"false"
auto-focus"true" - Automatically focus on the first input of each screen
"false" - Do not automatically focus on screen's inputs
"skipFirstScreen" - Automatically focus on the first input of each screen, except first screen
"true"
validate-on-blur"true" - Triggers the input validation upon blur in addition to the validation on submit
"false" - Do not triggers validation upon blur
"false"
restart-on-error"true" - In case of flow version mismatch, will restart the flow if the components version was not changed
"false" - Do not restart the flow automatically
"false"
send-session-token"true" - Send the current session JWT on flow start/next requests, exposing its validated claims to the flow via the sessionJwtClaims context key
"false" - Do not send the session JWT
"false"
storage-prefixString - A prefix to add to the key of the local storage when persisting tokens""
store-last-authenticated-user"true" - Stores last-authenticated user details in local storage when flow is completed
"false" - Do not store last-auth user details. Disabling this flag may cause last-authenticated user features to not function properly
"true"
keep-last-authenticated-user-after-logout"true" - Do not clear the last authenticated user details from the browser storage after logout
"false" - Clear the last authenticated user details from the browser storage after logout
"false"
style-id"String" - Set a specific style to load rather then the default style""
nonce"String" - Set a CSP nonce that will be used for style and script tags. Works with SRI for enhanced security""
popup-origin"String" - Sets the expected origin for OAuth popup communication when redirect URL is on different origin than the main application. Required for cross-origin OAuth popup flows""
dismiss-screen-error-on-input"true" - Clear screen error message on user input
"false" - Do not clear screen error message on user input
"false"
outbound-app-id"String" - Outbound application ID to use for connecting to external services""
outbound-app-scopes"String[]" - JSON array of scopes to request from the outbound application (e.g., '["email", "profile"]')null

Optional Properties

errorTransformer - A function that receives an error object and returns a string. The returned string will be displayed to the user.

The function can be used to translate error messages to the user's language or to change the error message.

Usage example:

function translateError(error) {
  const translationMap = {
    SAMLStartFailed: 'No es posible iniciar sesión en este momento, por favor intenta nuevamente más tarde',
  };
  return translationMap[error.type] || error.text;
}

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];

descopeWcEle.errorTransformer = translateError;

logger - An object that defines how to log error, warning and info. Defaults to console.error, console.warn and console.info respectively

Usage example:

const logger = {
  info: (message: string, description: string, state: any) => {
    console.log(message, description);
  },
  warn: (title: string, description: string) => {
    console.warn(`WARN: ${title}`, description);
  },
  error: (title: string, description: string) => {
    console.error(`ERROR: ${title}`, description);
  },
};

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];

descopeWcEle.logger = logger;

onScreenUpdate

A function that is called whenever there is a new screen state and after every next call. It receives the following parameters:

  • screenName: The name of the screen that is about to be rendered
  • context: An object containing the upcoming screen state
  • next: A function that, when called, continues the flow execution
  • ref: A reference to the descope-wc node

The function can be sync or async, and should return a boolean indicating whether a custom screen should be rendered:

  • true: Render a custom screen
  • false: Render the default flow screen

Breaking change (v4.0.0): server-produced screen data that used to sit directly on context now lives under context.data — e.g. context.totp → context.data.totp, context.inboundAppApproveScopes → context.data.inboundAppApproveScopes. Status, form, and identity fields (user / project / lastAuth) stay at the top level. See The context object below for the full list of context.data fields.

This function allows rendering custom screens instead of the default flow screens. It can be useful for highly customized UIs or specific logic not covered by the default screens

To render a custom screen, its elements should be appended as children of the descope-wc component

Usage example:

function onScreenUpdate(screenName, context, next, ref) {
  if (screenName === 'My Custom Screen') {
    ref.innerHTML = `
          <form>
            <input type="text" name="email" placeholder="Email" />
            <button type="submit">Submit</button>
          </form>
        `;

    ref.closest('form').addEventListener('submit', (e) => {
      e.preventDefault();
      const formData = new FormData(e.target);
      const data = Object.fromEntries(formData.entries());

      // replace with the button interaction id
      next('interactionId', data);
    });

    return true;
  }

  return false;
}

const descopeWcEle = document.querySelector('descope-wc');

descopeWcEle.onScreenUpdate = onScreenUpdate;

The context object

context carries the upcoming screen's state:

  • Top level — error, action, form (the input/output channel), and the acting user's context: user, project, lastAuth.
  • context.data — all server-produced screen data, in one clean, stable place, so you don't have to read internal, deeply-nested paths.

For example, a screen that generates MFA recovery codes exposes them as a plain array:

function onScreenUpdate(screenName, context, next, ref) {
  if (screenName === 'Display recovery codes') {
    const codes = context.data.recoveryCodes; // string[]
    // render the codes in your custom UI…
    return true;
  }
  return false;
}

context.data may include (each present only when the screen produces it):

  • recoveryCodes — generated MFA recovery codes (string[])
  • totp / notp — MFA setup (image, provisioning/redirect URL)
  • sentTo — where an OTP/code was sent (masked email/phone)
  • inboundAppApproveScopes — scopes an inbound app is asking the user to approve
  • passwordPolicy — password rules to show/enforce
  • securityQuestionsSetup / securityQuestionsVerify — security questions
  • userTenants, userRoles, ssoApplications, ssoConfigurations — selection options
  • samlAttributeMappings, oidcAttributeMappings, samlGroupMappings — SSO mappings
  • sso — SSO service-provider config
  • selfProvisionDomains — tenant self-provision domains
  • outboundApp — outbound OAuth app button info

context.data is a supported, stable field owned by the SDK — prefer it over reading raw screen-state internals. It exposes only the documented fields above; any other internal screen-state data is intentionally omitted. New fields are added in SDK releases.

Every key on context.data is an SDK-owned, documented name. The SDK never puts arbitrary, flow-defined keys directly on context.data, so new fields are always added without breaking existing ones.

Not exposed yet: dynamic-select options (a select component whose options are computed by the flow). Their keys are the flow's own field names, so they don't fit the fixed shape above; they are omitted for now and reserved for a future context.data.selects map. This data was not available to custom screens before, so nothing changes for existing code.

Breaking change (v4.0.0): screen-data fields that used to sit directly on context now live under context.data. Migrate reads accordingly, e.g. context.inboundAppApproveScopes → context.data.inboundAppApproveScopes, context.totp → context.data.totp. Status, form, and identity fields (user/project/lastAuth) stay at the top level.

Events

error - Fired when an error occurs. The event detail contains the error object.

Usage example:

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
descopeWcEle.addEventListener('error', (e) => alert(`Error! - ${e.detail.errorMessage}`));

success - Fired when the flow is completed successfully. The event detail contains the flow result.

Usage example:

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
descopeWcEle.addEventListener('success', (e) => alert(`Success! - ${JSON.stringify(e.detail)}`));

ready - Fired when the page is ready.

This event is useful for showing/hiding a loading indication before the page is loading. Note: in cases where the flow involves redirection to a non-initial stage of the process, such as with Magic Link or OAuth, this event is also dispatched.

Usage example:

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
descopeWcEle.addEventListener('ready', () => {
  // Remove/hide the loading indication
});

版本与发布记录

@descope/web-component 共发布 658 个版本,首次发布于 2022/09/05;过去 12 个月发布了 165 个版本。

版本发布日期距今
4.7.0latest2026/11/083 天前
0.0.0-next-8d9f5c5a-20261108next2026/11/083 天前
0.0.0-next-4d93b95d-202611052026/11/056 天前
4.6.32026/11/056 天前
0.0.0-next-41289441-202611042026/11/047 天前
4.6.22026/11/038 天前

其他发布通道:alpha → 3.0.0-alpha.6,custom-screens → 0.0.0-custom-screens.1,next → 0.0.0-next-8d9f5c5a-20261108。

关于 @descope/web-component 的常见问题

@descope/web-component 是什么?

Descope WC

如何安装 @descope/web-component?

在项目目录运行 npm install @descope/web-component,或使用 pnpm add / yarn add / bun add。

@descope/web-component 支持 TypeScript 吗?

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

@descope/web-component 支持 ESM 还是 CommonJS?

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

@descope/web-component 可以商用吗?

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

@descope/web-component 的下载量有多少?

根据 npm 官方下载统计,@descope/web-component 在 2026/10/12 – 2026/11/10 这 30 天内被下载 1,539,045 次,日均约 51,302 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@descope/web-component 还在维护吗?

最新版本 4.7.0 发布于 2026/11/08(3 天前);至今共发布 658 个版本,其中过去 12 个月发布了 165 个;首次发布于 2022/09/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。