> ## Documentation Index
> Fetch the complete documentation index at: https://docs.worthai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

API reference for all Onboarding SDK methods, types, and options.

## createWorthOnboarding

### Import

```typescript theme={null}
import { createWorthOnboarding } from '@worthai/onboarding-sdk';
```

### Parameters

`createWorthOnboarding` accepts a single argument object with the following properties:

| Property            | Type                       | Required | Description                                                                                                                                               |
| ------------------- | -------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inviteToken`       | `string`                   | Yes      | The invite token used to authenticate and load the onboarding session. Must be a non-empty string                                                         |
| `onStepSubmit`      | `callback`                 | No       | Called each time the applicant submits a step. Receives `{ inviteToken, stepId, values }` and returns either `Promise<void>` or `void`                    |
| `onComplete`        | `callback`                 | No       | Called once the applicant submits the final step of the onboarding flow. Receives `{ inviteToken, values }` and returns either `Promise<void>` or `void`  |
| `onError`           | `callback`                 | No       | Called whenever the SDK encounters an error. See [Error Handling](#error-handling)                                                                        |
| `onAuthenticated`   | `callback`                 | No       | Called when the invite token successfully authenticates                                                                                                   |
| `onAuthUnsupported` | `callback`                 | No       | Called when the invite token's auth mode isn't supported by the embedded flow                                                                             |
| `styleNonce`        | `string`                   | No       | A CSP nonce applied to the styles that the SDK injects during `mount()`. Required only if your page enforces a strict `style-src` Content Security Policy |
| `storageNamespace`  | `string`                   | No       | Overrides the default browser storage namespace (`worth:onboarding-sdk`) that the SDK uses                                                                |
| `routeBasePath`     | `string`                   | No       | Overrides the base path that the SDK's internal router mounts under                                                                                       |
| `apiBaseUrl`        | `string`                   | No       | Overrides the default Worth API origin. This is for environments where traffic must be routed through a proxy                                             |
| `flowInput`         | `WorthOnboardingFlowInput` | No       | Supplies a custom flow definition instead of resolving one from an invite token                                                                           |

<Note>
  `createWorthOnboarding` validates its options synchronously. An invalid or missing `inviteToken` or other malformed option throws a `WorthOnboardingError` immediately rather than surfacing it later through `mount()` or `onError`. See [Error Handling](#error-handling).
</Note>

### Example

```typescript theme={null}
import { createWorthOnboarding } from '@worthai/onboarding-sdk';

const onboarding = createWorthOnboarding({
  apiBaseUrl: 'https://api-dev.joinworth.ai',
  inviteToken,
  onStepSubmit: ({ inviteToken, stepId, values }) => {
    console.log('Step submitted', { inviteToken, stepId, values });
  },
  onComplete: ({ inviteToken, values }) => {
    console.log('Onboarding completed', { inviteToken, values });
  },
  onError: (error) => {
    console.error(error);
  },
});

await onboarding.mount('#worth-onboarding');

// Later, for route cleanup:
onboarding.unmount();
```

SDK 3 also ships a browser-global build at `dist-sdk/sdk3/worthai-onboarding-sdk.global.js`.
When loaded directly in a browser page, use the global namespace configured by the SDK build:

```html theme={null}
<script src="/path/to/worthai-onboarding-sdk.global.js"></script>
<script>
  const onboarding = WorthAI.createWorthOnboarding({
    inviteToken: 'INVITE_TOKEN',
    onStepSubmit: (event) => console.log(event),
    onComplete: (event) => console.log(event),
    onError: (error) => console.error(error),
  });

  onboarding.mount('#worth-onboarding');
</script>
```

### Returned Methods

`createWorthOnboarding` returns a `WorthOnboarding` object with two methods:

#### `mount(target)`

Mounts the embedded onboarding runtime into a DOM target. SDK styles are injected automatically as part of this call.

**Parameters:**

* `target: HTMLElement | string` - The element to mount into, or a CSS selector string that resolves to one

**Returns:**

* `Promise<HTMLElement>` - Resolves with the mounted host element once the runtime has rendered

**Example:**

```typescript theme={null}
try {
  await onboarding.mount('#worth-onboarding');
} catch (error) {
  console.error('Failed to mount onboarding:', error);
}
```

Only one onboarding instance can be mounted at a time. Call `unmount()` before mounting a new instance on the same page.

***

#### `unmount()`

Tears down the mounted runtime, removes its DOM element, and releases the mount target so that a new instance can be mounted later.

**Parameters:** None

**Returns:** `void`

**Example:**

```typescript theme={null}
// Call when the containing route or component unloads
onboarding.unmount();
```

If the runtime fails to tear down cleanly, `unmount()` will throw a `WorthOnboardingError` with the code `UNMOUNT_FAILED`.

***

## Callbacks

### `onComplete(event)`

Observes the completion of the onboarding flow once the applicant has submitted the final step.

**Event shape (`WorthOnboardingCompleteEvent`):**

```typescript theme={null}
{
  inviteToken: string;
  values: Record<string, unknown>;
}
```

If `onComplete` fails or rejects, it will throw a `WorthOnboardingError` with the code `CALLBACK_FAILED`.

### `onStepSubmit(event)`

Observes submitted step payloads as an applicant progresses through the onboarding flow.

**Event shape (`WorthOnboardingStepSubmitEvent`):**

```typescript theme={null}
{
  inviteToken: string;
  stepId: string;
  values: Record<string, unknown>;
}
```

If `onStepSubmit` fails or rejects, it will throw a `WorthOnboardingError` with the code `CALLBACK_FAILED`.

### `onError(error)`

Observes every SDK and runtime error, including validation failures, mount failures, and callback failures. See [Error Handling](#error-handling) for a complete list of codes.

### `onAuthenticated(result)` / `onAuthUnsupported(result)`

Observes authentication outcomes for the invite token.

* `onAuthenticated` fires when the invite token authenticates successfully. The result includes `authMode`, `authResponse`, and `status: 'authenticated'`
* `onAuthUnsupported` fires when the invite token's auth mode isn't supported by the embedded flow. The result includes `authMode`, `message`, an optional `redirectPath`, and `status: 'unsupported'`

***

## Error Handling

Every error that the SDK raises is an instance of `WorthOnboardingError`, an `Error` subclass with a stable `code`:

```typescript theme={null}
import { isWorthOnboardingError } from '@worthai/onboarding-sdk';

onError: (error) => {
  if (isWorthOnboardingError(error)) {
    console.error(`[${error.code}] ${error.message}`);
  } else {
    console.error(error);
  }
};
```

`WorthOnboardingError` has the following shape:

| Property  | Type                                   | Description                                     |
| --------- | -------------------------------------- | ----------------------------------------------- |
| `code`    | `WorthOnboardingErrorCode`             | A stable string identifying the error condition |
| `message` | `string`                               | A human-readable description                    |
| `details` | `Record<string, unknown> \| undefined` | Optional structured context                     |

### Error Codes

| Code                     | Raised From               | Description                                                                           |
| ------------------------ | ------------------------- | ------------------------------------------------------------------------------------- |
| `MISSING_INVITE_TOKEN`   | `createWorthOnboarding()` | `inviteToken` was omitted or is an empty string. Thrown synchronously at construction |
| `INVALID_OPTIONS`        | `createWorthOnboarding()` | The options object failed validation. Thrown synchronously at construction            |
| `ALREADY_MOUNTED`        | `mount()`                 | The onboarding instance is already mounted                                            |
| `MOUNT_IN_PROGRESS`      | `mount()`                 | `mount()` was called while a previous `mount()` call was still in progress            |
| `INVALID_MOUNT_TARGET`   | `mount()`                 | The `target` passed to `mount()` isn't an `HTMLElement` or a valid selector string    |
| `MOUNT_TARGET_NOT_FOUND` | `mount()`                 | The selector string passed to `mount()` did not match any element in the document     |
| `MOUNT_CANCELLED`        | `mount()`                 | The mount was interrupted before the runtime finished rendering                       |
| `RUNTIME_RENDER_FAILED`  | `mount()`                 | The onboarding runtime threw an error while rendering                                 |
| `UNMOUNT_FAILED`         | `unmount()`               | The mounted runtime failed to tear down cleanly                                       |
| `CALLBACK_FAILED`        | Onboarding instance       | `onStepSubmit` or `onComplete` threw or rejected                                      |
| `RUNTIME_ERROR`          | Onboarding instance       | The onboarding runtime reported an error during normal operation                      |

<Note>
  Every error raised from `mount()` and `unmount()` is delivered to `onError` (if provided) before the returned promise rejects with the same error object.
</Note>

## Next Steps

* New to SDK 3? Follow the [Quick Start Guide](/onboarding-sdk-3/quickstart)
* Migrating from SDK 2? Read the [Migration Guide](/onboarding-sdk-3/migrate)

***

## Support

For questions or issues, please contact your Worth Customer Success team or reach out to [support@joinworth.com](mailto:support@joinworth.com).
