Returning.AIDocs
v1

Guides / Custom Widget SDK

.md

Reference

Configuration

Start with the three required custom-widget attributes. Add presentation options or environment overrides only when the integration needs them.

Required attributes

AttributeTypeDefaultDescription
widget-idstring-Required. The supplied base64 CustomWidget identifier that selects the configured experience.
bundle-urlURL-Required. The complete widget.js URL supplied for that widget ID.
embed-tokenJWT-Required. Short-lived user token minted by your server through the Access Key API.

Common attributes

AttributeTypeDefaultDescription
theme"light" | "dark"Widget settingOptional host-page override. Omit it to use the configured widget theme.
widthCSS length"100%"Width of the custom element.
heightCSS length"600px"Use auto for natural bundle height and host-page scrolling.
languagelanguage tagBrowser languageRequested language such as fr-FR. Regional tags are normalized by the SDK. See language codes and fallback.
banner"on" | "off""on"Set off to disable automatic widget-mounted banners.
eagerboolean attributefalseLoad immediately instead of waiting until the element becomes visible.
debugboolean attributefalsePrint verbose SDK diagnostics to the browser console.
custom-dataJSON string-JSON object forwarded to the custom bundle.
retry-labelstring"Retry"Text shown on the SDK error retry button.

Language codes and fallback

SDK 1.8.11 accepts these language codes: en, de, es, fr, it, pt, pl, da, nl, ru, chs, el, ko, cht, th, ja, id, vt, ms, hi, fil, ta, tr, ar, mn, sw.

Regional tags are normalized: fr-FR selects fr, zh-Hans or zh-CN selects chs, zh-Hant or zh-TW selects cht, and vi selects vt. Unsupported or malformed values are not forced; a non-empty invalid value warns once and leaves browser-language fallback to the widget.

This is SDK language selection, not a promise of translated content in every bundle. Ask the setup owner which translations and fallback the supplied widget supports, and record a visible check for each required locale in the handover.

Advanced environment overrides

The current SDK already defaults to Returning.AI production hosts. Do not copy these overrides into a normal production embed.

AttributeTypeDefaultDescription
api-urlURLProduction widget APIOptional override for private deployments or a supplied migration configuration.
v2-api-urlURLProduction V2 APIOptional override. Production defaults to https://api-v2.returning.ai.
domain-keystringProduction settingOptional environment hint. Set it only when Returning.AI supplies a value.
max-retriesnumber3Maximum authentication retries.
retry-delaymilliseconds500Wait between authentication retries.

DOM events

EventDetailWhen it fires
rai-authenticated{}The embed token was validated and authentication completed.
rai-mounted{}The custom bundle mounted into the page.
rai-error{ message, hint?, status? }Startup or authentication failed.
rai-logout{}The widget session was cleared.
rai-session-expired{ communityId, widgetType, lastAuthError }The SDK could not recover the session. See manual renewal.
rai-banner-clickBanner event detailA widget-mounted banner was clicked.
rai-banner-dismissBanner event detailA widget-mounted banner was dismissed.
widget-events.js
const widget = document.querySelector('rai-custom-widget')

widget.addEventListener('rai-authenticated', () => {
  console.log('Widget user authenticated')
})

widget.addEventListener('rai-mounted', () => {
  console.log('Widget bundle mounted')
})

widget.addEventListener('rai-error', (event) => {
  console.error(event.detail.message)
})

JavaScript API

The SDK exposes one global controller after it loads.

widget-control.js
const sdk = window.ReturningAIWidget

sdk.version
sdk.isAuthenticated()
sdk.getTokenInfo()

await sdk.reload()
await sdk.logout()

Embed token renewal

SDK 1.8.14 and later invoke embedTokenRequest for Access Key Embed. Your host callback receives { reason } and returns { embedToken }. The SDK calls this callback directly.

  • expired means the SDK needs a new token to sign in, for example at mount.
  • session-expired means renewal of a running session failed and signing in again needs a new token.

Follow the renewal example in Authentication for registration, timing, and manual recovery.

Bundle callbacks

Register callbacks on the specific custom element before calling lockCallbacks(). Store bundles may also use callbackFieldOptions to request signed choices from your backend.

widget-callbacks.js
const widget = document.querySelector('rai-custom-widget')

widget.registerCallback('storePurchaseSuccess', (purchase) => {
  console.log('Purchase completed', purchase)
})

widget.registerCallback('milestoneCtaClick', ({ buttonName }) => {
  console.log('CTA clicked', buttonName)
})

widget.lockCallbacks()

Store field options

Register callbackFieldOptions on your Store widget to forward the callback payload to your authenticated backend route and return its JSON response. The Store bundle must support the optional ineligibleOptions and optionDescriptions fields to display them. SDK 1.8.14 and later include both fields in the public type.

  • fieldOptions lists selectable accounts by requested field ID.
  • ineligibleOptions lists accounts to show as disabled under those same field IDs.
  • optionDescriptions adds plain-text hints. For each field ID, use the exact account strings from either list as keys.

Sign only result: { fieldOptions }. In this backend example, signCallbackResult sends the signature request with your server credentials and returns data.signature. Add the display fields to the response after signing. For a request with multiple fields, return a fieldOptions entry for every requested field ID.

store-field-options.ts
import type {
  StoreCallbackFieldOptionsPayload,
  StoreCallbackFieldOptionsResult,
} from '@returningai/widget-sdk'
import { signCallbackResult } from './callback-signing'

async function buildStoreFieldOptions(
  { scope, callbackName, context }: StoreCallbackFieldOptionsPayload,
): Promise<StoreCallbackFieldOptionsResult> {
  // This example assumes one account field in the request.
  const [field] = context.fields
  if (!field) throw new Error('Expected an account field')

  const fieldOptions = { [field.id]: ['100001'] }
  const signature = await signCallbackResult({
    scope,
    callbackName,
    context,
    result: { fieldOptions },
  })

  return {
    fieldOptions,
    signature,
    ineligibleOptions: { [field.id]: ['100002'] },
    optionDescriptions: {
      [field.id]: {
        '100001': 'Standard account',
        '100002': 'Account is suspended',
      },
    },
  }
}

Legacy attributes

These fields remain documented for existing integrations. They are outside the custom-widget starter path.

AttributeTypeDefaultDescription
community-idstring-Required by standard widget tags and standalone banners. Custom widgets use widget-id instead of community-id.
channel-idstring-Channel widget identifier for older standard-widget integrations.
widget-typestringInferredStandard-widget or script-loader type override.
widget-urlURLProduction frontendHosted frontend URL used by older iframe integrations.
auth-urlURL-Older token-auth callback. For Access Key Embed, see embed token renewal.
auto-refreshbooleantrueAutomatic refresh for the older auth-url flow. It does not mint Access Key embed tokens.
localelanguage tag-Deprecated alias for language.
storage-prefixstring"returning-ai-widget"Storage namespace used by older refresh-token flows.

See Architecture for the custom bundle lifecycle.