---
title: "Onboarding SDK for JavaScript & React"
url: "https://platformdocs.coinme.com/#/docs/onboarding-sdk-react"
markdown: "https://platformdocs.coinme.com/docs/onboarding-sdk-react.md"
summary: "The Coinme Onboarding SDK onboards a customer to Coinme-as-a-Service (CAAS) from your web app, returns the new `customerId`, and then verifies the customer's phone with a code texted to the number they onboarded with. Use it from a React app through its drop-in form, field components and hooks, or from any JavaScript web app (vanilla JS, Vue, Angular, Svelte, …) through the framework-agnostic core the React layer is built on; see Core API (without React). Either way it is the one package, `@coinme-security/onboarding-sdk-react`."
surface: "caas"
platform: "web"
package: "@coinme-security/onboarding-sdk-react"
version: "1.7.1"
peerDependencies: {"react":">=18","react-dom":">=18"}
updated: "2026-11-06"
---

# Onboarding SDK for JavaScript & React

The Coinme Onboarding SDK onboards a customer to Coinme-as-a-Service (CAAS) from your web app, returns the new `customerId`, and then verifies the customer's phone with a code texted to the number they onboarded with. Use it from a React app through its drop-in form, field components and hooks, or from any JavaScript web app (vanilla JS, Vue, Angular, Svelte, …) through the framework-agnostic core the React layer is built on; see [Core API (without React)](#core-api-without-react). Either way it is the one package, `@coinme-security/onboarding-sdk-react`.

This SDK leverages the Coinme Vault so that the customer's Social Security Number is typed into a secure field hosted by the vault, and the raw SSN never touches your JavaScript or your servers. Everything else (email, name, address, phone, date of birth) is collected in ordinary inputs that you style however you like.

The endpoint itself is described in Coinme's [customer onboarding guide](https://docs.coinme.com/docs/customer-onboarding-overview).

> **See it running.**
>
> Every approach in this guide, from the drop-in form to the bare fields, is on the [examples page](https://platformdocs.coinme.com/docs/onboarding-sdk-examples.md) as the code and the live form it produces, with simulated submits you can try.

## Why use it

Collecting an SSN yourself puts your app, your logs and your servers in scope for handling it. This SDK keeps it out of your code: the customer types it into the vault's secure field, an iframe, and it goes from that iframe to the vault without passing through your page's code. Your code only sees whether the SSN is valid, never the number.

You get:

- **A drop-in form.** `<CustomerOnboardingForm>` collects every field the endpoint requires and calls you back with `{ customerId, phoneNumber }` or a typed error.
- **Headless building blocks.** A provider, individual field components (including the secure SSN field) and a `useCustomerOnboarding` hook, for teams that build their own UI.
- **Phone verification after onboarding.** `<PhoneVerificationStep>` (or the `usePhoneVerification` hook) texts the new customer a code and checks it, so you know the number they onboarded with is verified before you treat their KYC as complete.
- **Pass-through styling.** Every field accepts the same props or options as the element underneath it. There's no theme contract to learn and no Coinme branding.
- **A framework-agnostic core.** `@coinme-security/onboarding-sdk-react/core` has no React code, for vanilla JS and every other stack.
- **Typed outcomes.** `CoinmeOnboardingError` tells you whether a failure is terminal (duplicate, age, jurisdiction, sanctions) or worth retrying.

## Install

The package is published to Coinme's private npm registry. Configure the `@coinme-security` scope with the registry token Coinme provides, then install.

`.npmrc` (npm / Yarn Classic):

```properties
@coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/
//npm.coinme.com/coinme-security-wrapper/:_authToken=${COINME_REGISTRY_TOKEN}
//npm.coinme.com/coinme-security-wrapper/:always-auth=true
```

`.yarnrc.yml` (Yarn Berry v2+):

```yaml
nodeLinker: node-modules

npmScopes:
  coinme-security:
    npmRegistryServer: 'https://npm.coinme.com/coinme-security-wrapper/'
    npmAuthToken: '${COINME_REGISTRY_TOKEN}'
    npmAlwaysAuth: true
```

Then export the token and install:

```bash
export COINME_REGISTRY_TOKEN=<your-token>
npm install @coinme-security/onboarding-sdk-react
# or: yarn add @coinme-security/onboarding-sdk-react
```

`COINME_REGISTRY_TOKEN` is the registry access token. Request it from your Coinme integration contact.

`react` and `react-dom` 18 or later are peer dependencies of the React API (the package root). They're optional: an app without React imports from `@coinme-security/onboarding-sdk-react/core` and doesn't install them. The Coinme Vault SDK (`@coinme-security/vault-sdk-js`), which loads the secure field, is installed with the package.

## Compatibility

| Requirement | Supported |
| --- | --- |
| React | 18 or later (`react` and `react-dom` peers), for the React API only; the `/core` entry needs no React |
| Browsers | Chrome / Edge 111+, Firefox 114+, Safari 16.4+ (desktop and iOS) |
| Secure field script | Pinned by the SDK and loaded from our vault provider's CDN at runtime |
| Server-side rendering | Importing the package on the server is safe; the secure field is created in the browser after mount (see [Server-side rendering](#server-side-rendering)) |
| TypeScript | Full typings ship with the package |

### Content-Security-Policy

If your site sets a CSP, allow our vault provider's domains and the two Coinme hosts for your environment. The secure SSN field is an iframe served by the vault provider, its script loads from the vault provider's CDN, the onboarding submit goes to the Coinme onboarding host, and the phone verification calls go to the Coinme API host.

| Environment | Coinme onboarding host | Coinme API host |
| --- | --- | --- |
| `live` | `https://secure.apis.coinme.com` | `https://caas.coinme.com` |
| `sandbox` | `https://secure.apis.coinme.org` | `https://caas-staging.coinme.com` |

With `<coinme-host>` and `<coinme-api-host>` replaced by the hosts above:

```
script-src  https://js.verygoodvault.com https://js3.verygoodvault.com
frame-src   https://js.verygoodvault.com https://js3.verygoodvault.com
connect-src https://js.verygoodvault.com https://js3.verygoodvault.com https://vgs-collect-keeper.apps.verygood.systems <coinme-host> <coinme-api-host>
```

`js3.verygoodvault.com` is the vault provider's fallback CDN, and `vgs-collect-keeper` receives its product-interaction analytics.

## Before you start

The SDK covers two steps: onboarding the customer, then verifying their phone. Before a customer reaches your onboarding form:

1. **Have a way to get two tokens from your backend.** The onboarding request needs a token minted for the customer's sign-up session. Phone verification needs a second token, minted for the `customerId` that onboarding returns. Never your partner access token. You write the backend routes that mint them; [You build](#you-build) lists what each one does.
2. **Plan for phone verification right after onboarding, and on later sign-ins with incomplete 2FA.** A newly onboarded customer needs to confirm the code texted to the phone number they onboarded with. If the code isn't confirmed, the customer should not be considered to have completed KYC. See the [recommended integration flow](#recommended-integration-flow).

## Recommended integration flow

Onboarding is complete only once the customer's phone is verified. Build your integration in this order:

> **Every call after onboarding uses a token for that customer.**
>
> Sending the code and checking it are authorized by a Transient Auth Token your backend mints for the `customerId` that onboarding returned (step 4). Never use your partner access token or the sign-up session token for them. That token is the only thing that ties the two calls to the customer: there's no challenge ID, session or cookie to carry from one call to the other. See [You build](#you-build) for the backend routes this takes.

1. **Mint an onboarding token for the sign-up session.** When the customer reaches your onboarding screen, your app asks your backend for a token. Your backend calls `POST /services/browserAuth` with `scope=onboarding` and your own identifier for the sign-up session as `customerId`: any ID you choose, such as your internal session ID. The customer doesn't exist at Coinme yet.
2. **Onboard the customer with that token.** Return it from the form's (or provider's) `getHeaders`. When onboarding succeeds, `onSuccess` receives `{ customerId, phoneNumber }`.
3. **Send the real `customerId` to your backend.** From `onSuccess`, send the `customerId` to your backend and link it to the sign-up session, together with `phoneNumber`, the number the customer onboarded with. Keep both: you need them for verification now and whenever the customer comes back.
4. **Mint a new token for the real `customerId`.** Your backend calls `POST /services/browserAuth` again, this time with the `customerId` from onboarding as `customerId`. Use **this** token for every phone verification call; the sign-up session token from step 1 won't work for them. Your backend reads the `customerId` from the record it saved in step 3, not from the browser, so a page can only ever get a token for its own customer.
5. **Start phone verification with that same number.** Your page renders `PhoneVerificationStep` (or uses `usePhoneVerification`) with `phoneNumber` from the onboarding result, and its `getHeaders` returns the token from step 4. Coinme texts the customer a code.
6. **Validate the code for that number.** The customer types the code. Once it checks out, `onVerified` runs; record on your backend that this customer's phone is verified.
7. **Only now treat the customer as onboarded.** A customer whose phone isn't verified hasn't completed KYC. Don't give them access to anything that needs a completed onboarding.
8. **Send a returning customer back to verification.** If a customer whose phone isn't verified signs in again later, take them to phone verification before anything else: mint a fresh token for their `customerId` as in step 4, and use the `phoneNumber` you stored in step 3.

Two rules hold in every case:

- **No verified phone, no completed onboarding.** Never consider a customer onboarded or KYC-complete until their phone number is verified, whatever your own records or UI show.
- **The verification number is the onboarding number.** Never let the customer give one phone number for onboarding and another for verification. Pass `phoneNumber` from the onboarding result (or the copy you stored in step 3), and don't offer a phone input at the verification step. Coinme texts whatever number the SDK sends and, once the code checks out, records it as the customer's verified phone. It doesn't compare it with the onboarded number, so passing the onboarded number is up to you.

## Quickstart

The quickest integration is the drop-in form followed by the drop-in phone verification step. The form collects every field the endpoint needs, the SSN included, and calls you back with the new `customerId` and the phone number it onboarded. The step then texts that number a code and checks it.

The SDK runs in your page, but it needs a few routes on **your** backend, which you write. The code below calls them; the [You build](#you-build) table after it says what each one does.

```tsx
import { useState } from 'react';
import {
  CustomerOnboardingForm, // Coinme SDK
  PhoneVerificationStep, // Coinme SDK
  type CustomerOnboardingResult, // Coinme SDK
} from '@coinme-security/onboarding-sdk-react';

// YOUR code, not part of the SDK. These two helpers call routes on YOUR backend (see "You build"
// below). The paths are examples. Keep the tokens in memory only: never store or log them.
const getTokenFromYourBackend = async (path: string): Promise<string> => {
  const response = await fetch(path, { method: 'POST', credentials: 'include' });
  if (!response.ok) throw new Error(`Token request failed (${response.status})`);
  const { token } = await response.json();
  return token;
};

const postToYourBackend = async (path: string, body: unknown): Promise<void> => {
  const response = await fetch(path, {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!response.ok) throw new Error(`Request to ${path} failed (${response.status})`);
};

export const Onboarding = () => {
  const [onboarded, setOnboarded] = useState<CustomerOnboardingResult>();

  if (!onboarded) {
    return (
      <CustomerOnboardingForm
        environment="sandbox"
        // Called before every submit. YOUR route returns a token for this sign-up session.
        getHeaders={async () => ({
          Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
        })}
        // Save the result on YOUR backend before moving on: the next token is minted from it.
        onSuccess={(result) => {
          void postToYourBackend('/your-api/onboarding/complete', result).then(() =>
            setOnboarded(result)
          );
        }}
      />
    );
  }
  return (
    <PhoneVerificationStep
      environment="sandbox"
      phoneNumber={onboarded.phoneNumber} // the number from onboarding; never ask for another
      // Called before every send and every check. It sends no customerId: YOUR route already
      // knows which customer this is (see "You build").
      getHeaders={async () => ({
        Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
      })}
      onVerified={() => {
        void postToYourBackend('/your-api/phone-verification/verified', {}).then(() => {
          // YOUR code: take the customer to your next screen.
        });
      }}
    />
  );
};
```

> **This is one way to do it, not the only way.**
>
> The route paths, the helper names, the use of cookies (`credentials: 'include'`) and how you show errors are all yours to choose. What matters is what each route does, in the table below. A real integration also handles a failed request (show a retry), and shows the verification step again to a customer who signs back in before verifying (step 8 of the [recommended integration flow](#recommended-integration-flow)).

### You build

These routes run on **your** backend. Coinme doesn't provide them: the paths are examples, so name them however you like. Only the Coinme API calls they make are fixed.

| Your route (example path) | What it does |
| --- | --- |
| `POST /your-api/onboarding/token` | Mints a Transient Auth Token for the sign-up session: calls Coinme's `POST /services/browserAuth` with `scope=onboarding` and your own ID for the session as `customerId`. Returns `{ token }`. |
| `POST /your-api/onboarding/complete` | Saves the `customerId` and `phoneNumber` from the onboarding result on the signed-in user, in your own database. |
| `POST /your-api/phone-verification/token` | Looks up the signed-in user, reads the `customerId` you saved for them, and mints a Transient Auth Token for **that** `customerId` (`scope=onboarding`). Returns `{ token }`. It never takes a `customerId` from the page. |
| `POST /your-api/phone-verification/verified` | Records on the signed-in user that their phone is verified. |

Your partner access token (from Coinme's `POST /services/authorize`) is what these routes use to call `browserAuth`. It stays on your backend and never reaches the page.

**This is how customer IDs can't get mixed up.** Each of your users has one saved `customerId`, and the verification token route only ever mints for that one. The page never says which customer it is, so it can't ask for the wrong one. Example code for all four routes is in [Example: both tokens, end to end](#example-both-tokens-end-to-end).

The later examples reuse `getTokenFromYourBackend`, `postToYourBackend` and these route paths, and `getHeaders` and `onSuccess` stand for the onboarding form's functions shown here. `goToWelcome`, `startPhoneVerification`, `reportOnboardingFailure` and `reportVerificationFailure` stand for your own navigation and error display.

Switch `environment` to `'live'` for real customers.

## How it works

- **`environment` selects everything else.** `'sandbox'` or `'live'` picks the onboarding vault and the Coinme onboarding endpoint, both built into the package. You never configure a vault ID or URL.
- **The vault is created in the browser.** The form (or `CoinmeOnboardingProvider`) creates it after mount, which loads the secure field script from the vault provider's CDN, and disposes of it on unmount.
- **The SSN goes from the secure field to the vault.** The customer types the SSN into the vault's iframe. When you submit, the iframe sends the request to the vault with the SSN in it. The SSN never passes through your page's code.
- **The other fields are plain inputs.** Their values are in React state, so you can prefill, read and validate them.
- **You see only metadata for the SSN.** Whether it's valid, empty, focused or touched. Never the number.
- **Every failure is one error type.** Client-side validation failures, network failures, HTTP errors and CAAS error codes all become a `CoinmeOnboardingError` with a `kind` and a `retryable` flag.

**Terms used in this guide:**

- **Vault:** the Coinme Vault connection that holds the secure SSN field. The form or `CoinmeOnboardingProvider` creates one and cleans it up for you.
- **Secure field / SSN field:** the vault's iframe the customer types the SSN into.
- **Plain fields:** every other field. They're ordinary inputs whose values live in React state.
- **Mount:** when React first puts a component on the page. A prop that's "read once on mount" is read then; changing it later has no effect.
- **Touched:** a field the customer has left (blurred) at least once. After a submit attempt, every field counts as touched. Inline errors show only for touched fields.

## Authentication and headers

You supply the request headers through `getHeaders`, which the SDK calls just before each request. It can be async, so fetch a fresh token inside it. Whatever it returns is sent as the request headers.

| Header | Value |
| --- | --- |
| `Authorization` | `Bearer <token>`, with a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend minted with `scope=onboarding`. |
| `X-Device-Fingerprint` | Optional from 1.7.0, which always sends one; see [Device fingerprint](#device-fingerprint). With an older release, send the value you give the Risk SDK. |

> **Never give the Onboarding SDK your partner access token.**
>
> `getHeaders` must always return a Transient Auth Token your backend mints from `POST /services/browserAuth` with `scope=onboarding`, never your partner access token (from `POST /services/authorize`).

The two steps need different tokens, both minted by your backend with `POST /services/browserAuth` and both lasting 10 minutes:

| Step | Minted for (`customerId` when minting) | Passed through |
| --- | --- | --- |
| Onboarding | Your identifier for the customer's sign-up session, with `scope=onboarding`. The customer doesn't exist at Coinme yet. | The form's or provider's `getHeaders` |
| Phone verification | The `customerId` that onboarding returned, with `scope=onboarding`. | `PhoneVerificationStep`'s or `usePhoneVerification`'s `getHeaders` |

> **`scope=onboarding` is sandbox-only for now.**
>
> Coinme's `live` environment doesn't mint `scope=onboarding` tokens yet, so neither step can run in `live` until it does. Check with your Coinme integration contact before going live.

Each phone verification call (sending a code, checking it) asks `getHeaders` again, so mint a fresh token there rather than reusing one: a customer who waits for the text can easily pass the 10 minutes.

- **Never put your Coinme credentials or your partner access token in the browser.** Only the Transient Auth Tokens reach the page, and only for the requests that need them. Never pass your partner access token (from `POST /services/authorize`) to this SDK.
- **Don't store the token.** Fetch it just in time and don't keep it in `localStorage`, `sessionStorage` or cookies.

**The verification token is what ties verification to the customer.** Sending the code sends only the phone number, and checking it sends only the code. Coinme works out which customer the calls are for from the token, so there's no challenge ID, session or cookie to carry between them. That's why the token must be minted for that one `customerId`, and why your partner access token must never be used in its place: it isn't tied to any customer, and it must never reach the browser.

The SDK refuses a request whose `Authorization` header carries a partner access token and throws a `configuration` `CoinmeOnboardingError` before anything is sent. If you see it, your backend is returning the partner access token to the browser. Change that route to mint a Transient Auth Token from `POST /services/browserAuth` (with `scope=onboarding`) and return only its `access_token`. The partner access token is a long-lived credential that must stay on your backend.

The SDK also adds tracing headers (`X-B3-TraceId`, `X-B3-SpanId`) to each request.

### Device fingerprint

Coinme ties risk checks to a device ID sent as the `X-Device-Fingerprint` header, and phone verification is refused without it. From 1.7.0, with Risk SDK for Web 1.2.0 or later, the SDK adds it to the onboarding submit and to both phone verification calls, so you don't have to supply one. With an older release of either, send it yourself from `getHeaders`, with the same value you give the Risk SDK.

- If you pass a fingerprint (an `X-Device-Fingerprint` header from `getHeaders`, any casing), this SDK uses it and shares it with the other Coinme SDKs in your app. Pass the same value to every Coinme SDK, or pass it to the Risk SDK first, which shares it with the others.
- If you don't, the SDK uses the one another Coinme SDK already set in your app, or creates one.
- Every Coinme SDK in your app must send the same value. If they differ, adding a payment method and placing orders fail with `WEB_SESSION_ID_MISMATCH`.
- Calls your server makes to Coinme for this user (for example orders) must send the same value. Read it in the browser with `getDeviceFingerprint()` and send it to your server with the request. Never call `getDeviceFingerprint()` on your server.
- A `:` in the value is replaced with `-`.
- A risk session tag lives 30 minutes from when it was first issued. Call the Risk SDK's `getSessionTag()` right before adding a payment method or placing an order, and send the tag it returns as `webSessionId`.

The value is shared through `localStorage` under `coinme.deviceFingerprint`, so it survives page reloads. Like `localStorage`, it belongs to your site's origin, not to the device. If storage is blocked, it is shared for the current page only.

### Questions about the two tokens

**How do I make sure I don't mix up customer IDs? How does my backend know which customer to mint the verification token for?** From its own records, never from the page. When onboarding succeeds, the page sends the result to your backend, which saves the `customerId` on the signed-in user. When the page later asks for the verification token, your backend looks up the signed-in user and mints the token for the `customerId` it saved. Each user has one saved `customerId`, so the page can't ask for someone else's.

**Do I pass the `customerId` to the send or check calls?** No. Neither takes one. The token carries the customer, which is why it has to be minted for that `customerId`.

**Can I use my partner access token for phone verification?** No. It isn't tied to any customer, and it must never reach the browser. Use it only on your backend, to mint Transient Auth Tokens.

**Can I reuse the onboarding token?** No. It was minted for the sign-up session, before the customer existed at Coinme. Mint a new one for the `customerId` that onboarding returned.

### Example: both tokens, end to end

> **This is one way to do it, not the only way.**
>
> The route names, paths, session handling, framework and storage are yours to choose; only the Coinme API calls and the SDK's props are fixed. It does follow what we recommend:
>
> - your backend reads the `customerId` from its own record, never from the browser;
> - your partner access token is minted and cached on your server only;
> - each `getHeaders` call fetches a fresh token, kept in memory only and never stored or logged;
> - the phone number is the one from the onboarding result.

Who provides what:

|  | What | Where it runs |
| --- | --- | --- |
| **Coinme provides** | `POST https://caas-staging.coinme.com/services/authorize`: your partner access token (Coinme API) | Called from your backend only |
| **Coinme provides** | `POST https://caas-staging.coinme.com/services/browserAuth`: a Transient Auth Token (Coinme API) | Called from your backend only |
| **Coinme provides** | `CustomerOnboardingForm`, `PhoneVerificationStep` and their props (this SDK) | Your page |
| **You build** | `POST /your-api/onboarding/token`, `/your-api/onboarding/complete`, `/your-api/phone-verification/token`, `/your-api/phone-verification/verified` (what each does: [You build](#you-build)) | Your backend. These are examples: Coinme doesn't provide them, so name and shape them however you like. |

In production, use the base URL your Coinme integration contact gives you in place of `https://caas-staging.coinme.com`.

**Your backend** (YOUR code, shown with Express; the routes are examples):

```typescript
import express from 'express';
// Your own code: `requireSession` loads YOUR app's session for the person on the page, and `users` is
// YOUR user store. `mintTransientAuthToken` wraps the two Coinme API calls above; the
// Transient Auth Token guide has a complete version.
import { mintTransientAuthToken, requireSession, users } from './your-app';

const app = express();
app.use(express.json());

// Token 1: for the sign-up session. The customer doesn't exist at Coinme yet.
app.post('/your-api/onboarding/token', requireSession, async (req, res) => {
  const { token } = await mintTransientAuthToken(req.session.id, 'onboarding');
  res.json({ token });
});

// Save what onboarding returned against YOUR user, so later tokens come from your record.
app.post('/your-api/onboarding/complete', requireSession, async (req, res) => {
  const { customerId, phoneNumber } = req.body;
  await users.update(req.session.userId, {
    coinmeCustomerId: customerId,
    onboardedPhone: phoneNumber,
    phoneVerified: false,
  });
  res.sendStatus(204);
});

// Token 2: for this customer. The browser never says which customer: the ID comes from your
// record, so a page can only get a token for its own customer.
app.post('/your-api/phone-verification/token', requireSession, async (req, res) => {
  const user = await users.get(req.session.userId);
  if (!user?.coinmeCustomerId) return res.sendStatus(409);
  const { token } = await mintTransientAuthToken(user.coinmeCustomerId, 'onboarding');
  res.json({ token });
});

// The page reports that the code checked out. Coinme checked the code itself.
app.post('/your-api/phone-verification/verified', requireSession, async (req, res) => {
  await users.update(req.session.userId, { phoneVerified: true });
  res.sendStatus(204);
});
```

**Your page** is the [Quickstart](#quickstart) code: it calls these four routes through `getTokenFromYourBackend` and `postToYourBackend`.

## Field keys and field paths

Each field has two names, used by different props:

- **Field key**, such as `firstName`. Used by the drop-in form and `OnboardingFormField`: `fieldProps`, `labels`, `hiddenFields`, the custom layout's `fields`, `OnboardingFormField`'s `field` and each row's `data-field` attribute.
- **Field path**, such as `fullName.firstName`. The field's place in the onboarding data, used for values and errors: `defaultValues`, `values`, `setValue`, `fieldErrors`, `touched` and `OnboardingInputField`'s `path`.

| Field | Field key | Field path | Required | In the drop-in form |
| --- | --- | --- | --- | --- |
| Email | `email` | `email` | yes | yes |
| First name | `firstName` | `fullName.firstName` | yes | yes |
| Middle name | `middleName` | `fullName.middleName` | no | yes; can be hidden |
| Last name | `lastName` | `fullName.lastName` | yes | yes |
| Other names (for example a second last name) | — | `fullName.otherNames.0`, `fullName.otherNames.1`, … | no | no; render with `OnboardingInputField` |
| Street address | `addressLine1` | `address.line1` | yes | yes |
| Apartment, suite, etc. | `addressLine2` | `address.line2` | no | yes; can be hidden |
| City | `city` | `address.city` | yes | yes |
| State | `state` | `address.state` | yes | yes |
| ZIP code | `postalCode` | `address.postalCode` | yes | yes |
| Country | — | `address.country` | no; defaults to `USA` | no |
| Phone number | `phoneNumber` | `phoneNumber` | yes | yes |
| Date of birth | `dateOfBirth` | `dateOfBirth` | yes | yes |
| SSN | `ssn` | none: the SSN never leaves the secure field, so it can't be prefilled or read | yes | yes |

Other-name paths are numbered with whole numbers from `0`, with no gaps; any other index is ignored.

```tsx
<CoinmeOnboardingProvider
  environment="sandbox"
  defaultValues={{ email: user.email, 'address.state': 'WA' }}
>
  <OnboardingInputField path="fullName.otherNames.0" placeholder="Second last name" />
  …
</CoinmeOnboardingProvider>
```

## Drop-in form

`<CustomerOnboardingForm>` renders:

- a label, field and inline error for each of: email, first, middle and last name, street address, apartment, city, state, ZIP, phone number, date of birth and SSN;
- a message for submit failures;
- a submit button.

Inline errors appear once a field has been left (blurred). The submit button stays disabled until every field, including the SSN, is valid, while a submit is in flight, and after a successful submit.

It doesn't collect other names or a country; the country is sent as `USA`.

No CSS is bundled. Unstyled, each row stacks label, field and error.

**Style it through pass-through props:**

```tsx
<CustomerOnboardingForm
  environment="sandbox"
  getHeaders={getHeaders}
  onSuccess={onSuccess}
  className="my-form"
  classNames={{
    row: 'field',
    label: 'field-label',
    control: 'field-control',
    fieldError: 'field-error',
    alert: 'banner',
    submit: 'button',
  }}
  fieldProps={{
    email: { className: 'input', placeholder: 'you@example.com' },
    state: { className: 'input' },
    ssn: {
      placeholder: '123-45-6789',
      css: { fontSize: '16px', fontFamily: 'Inter, sans-serif' },
      containerProps: { className: 'input' },
    },
  }}
  submitProps={{ children: 'Create my account' }}
/>
```

The SSN is an iframe, so give its container a fixed height and make the iframe fill it, or it keeps the browser's default 150px height:

```css
.input { height: 44px; box-sizing: border-box; padding: 0 12px; }
.input iframe { display: block; width: 100%; height: 100%; border: 0; }
```

See [Styling](#styling) for the rest.

**Essential**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | — | **Required.** Which Coinme environment to onboard into: `'sandbox'` for testing, `'live'` for real customers. Read once on mount. |
| `getHeaders` | `() => Record<string, string> \| Promise<Record<string, string>>` | — | Returns the headers for the onboarding request, for example `{ Authorization: 'Bearer <token>' }`. Called just before each submit, so it can fetch a fresh token. Optional in the types but needed in practice: without an `Authorization` header, every submit fails as `unauthorized`. See [Authentication and headers](#authentication-and-headers). |
| `verifiedPhone` | `{ countryCode: string; number: string }` (`VerifiedPhone`) | — | Optional: a phone number the customer already verified with your own checks, for example `{ countryCode: '1', number: '2065550100' }`. While it's set, the phone field is read-only and shows this number, and the request sends it. Changes apply as they happen. See [Lock the phone to the verified number](#lock-the-phone-to-the-verified-number). |

**Callbacks**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `onSuccess` | `(result: { customerId: string; phoneNumber: string }) => void` (`CustomerOnboardingResult`) | — | Called once the customer is onboarded, with their new Coinme customer ID and the phone number they onboarded with (10 digits). Send the `customerId` to your backend from here, since the phone verification token is minted for it, then move the customer on to [phone verification](#phone-verification) (see below). If it throws, the form still counts the submit as a success and stays locked, so the customer can't be sent twice. |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when a submit fails: Coinme rejected it, or it didn't complete. Branch on `error.kind`; see [Error handling](#error-handling). |
| `onVaultError` | `(error: CoinmeOnboardingError) => void` | — | Called when the form can't load its secure SSN field, for example because the vault provider is blocked. The form can't be submitted until it's mounted again. |

**Text**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultValues` | `Partial<Record<OnboardingFieldPath, string>>` | `{}` | Values to prefill, keyed by [field path](#field-keys-and-field-paths), for example `{ email: user.email, 'address.state': 'WA' }`. The SSN can't be prefilled. Read once on mount. |
| `labels` | `Partial<Record<CustomerOnboardingFormFieldKey, ReactNode>>` | English (`DEFAULT_FORM_LABELS`) | Label per field, keyed by [field key](#field-keys-and-field-paths), for example `{ ssn: 'SSN' }`. Text or JSX. |
| `validationMessages` | `Partial<Record<OnboardingValidationCode \| 'invalidSsn', string>>` | English (`DEFAULT_VALIDATION_MESSAGES`) | Inline error text per validation code (listed under [Input and validation](#input-and-validation)), for example `{ required: 'Required' }`. `invalidSsn` is the SSN field's message. |
| `errorMessages` | `Partial<Record<CoinmeOnboardingErrorKind, string>>` | English (`DEFAULT_ERROR_MESSAGES`) | Text shown when a submit fails, per error kind (listed under [Error handling](#error-handling)), for example `{ duplicate: 'You already have an account.' }`. Without an entry, a non-retryable `invalidRequest` shows the terminal text rather than "try again". |
| `hiddenFields` | `('middleName' \| 'addressLine2')[]` | `[]` | Optional fields to leave out, for example `['middleName']`. Required fields can't be hidden. |

**Styling**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `fieldProps` | `CustomerOnboardingFormFieldProps` (an object keyed by [field key](#field-keys-and-field-paths)) | `{}` | Props passed straight to each field, for example `{ email: { className: 'input', placeholder: 'you@example.com' } }`. Every key except `ssn` takes anything an `<input>` accepts (a `<select>` for `state`). `ssn` takes the secure field's options (`css`, `placeholder`, `ariaLabel`, …) and `containerProps` for its container; see [Styling](#styling). |
| `className` | `string` | — | Extra class for the `<form>`. Same as `classNames.form`. |
| `classNames` | `{ form?, row?, label?, control?, fieldError?, alert?, submit?: string }` | — | Extra classes for each part of the form, added to the built-in ones. [Styling](#styling) lists which element each key targets. |
| `submitProps` | `<button>` props, except `type` | — | Props for the submit button. `children` is its label (default `'Continue'`). The button is always `type="submit"`, and stays disabled while the form is invalid or submitting, and after a successful submit, whatever `disabled` says. |

**Advanced**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `timeoutMs` | `number` | `60000` | Fail the submit with a `network` error if no response arrives within this many milliseconds. The request may still have reached Coinme; see [Error handling](#error-handling). |
| `children` | `(layout: CustomerOnboardingFormLayout) => ReactNode` | — | Your own layout instead of the default single column. `layout` holds `fields` (one ready-made row per field key), `alert`, `submitButton`, `isValid`, `status` and `error`. See [Layout control](#layout-control). |
| `vault` | `CoinmeVault` | — | A vault you created with `createOnboardingVault`, used instead of the form creating its own. Most integrations leave it out. |
| `testId` | `string` | — | Rendered as `data-testid` on the `<form>`, for your tests. |

**Change the text or translate it** with `labels`, `validationMessages` and `errorMessages`. Anything you leave out keeps its English default:

```tsx
<CustomerOnboardingForm
  environment="live"
  getHeaders={getHeaders}
  onSuccess={onSuccess}
  labels={{ email: 'Correo electrónico', firstName: 'Nombre' }}
  validationMessages={{ required: 'Campo obligatorio.' }}
  errorMessages={{ duplicate: 'Ya tienes una cuenta.' }}
/>
```

The English defaults are exported as `DEFAULT_FORM_LABELS`, `DEFAULT_VALIDATION_MESSAGES` and `DEFAULT_ERROR_MESSAGES`, as a checklist of every key to translate.

By default, an `invalidRequest` that isn't retryable shows the terminal text instead of "try again". An `errorMessages.invalidRequest` you provide is shown in both cases, so word it to fit both, for example by not promising that a retry will work.

**After `onSuccess`, move the customer on to phone verification.** Replace the form with `<PhoneVerificationStep>` (see [Phone verification](#phone-verification)). Otherwise the form stays on screen with its values; the submit button stays disabled, so the same customer can't be submitted twice.

### Lock the phone to the verified number

Optional. If you already verified the customer's phone with your own checks before onboarding, pass the number as `verifiedPhone`. The phone field then shows it read-only, and the request sends it, whatever was typed or set in `defaultValues`. This doesn't replace [phone verification](#phone-verification) after onboarding.

```tsx
import {
  CustomerOnboardingForm,
  type VerifiedPhone,
} from '@coinme-security/onboarding-sdk-react';

const Onboarding = ({ verifiedPhone }: { verifiedPhone: VerifiedPhone }) => (
  <CustomerOnboardingForm
    environment="sandbox"
    getHeaders={getHeaders}
    onSuccess={onSuccess}
    verifiedPhone={verifiedPhone} // for example { countryCode: '1', number: '2065550100' }
  />
);
```

- **Pass exactly `countryCode: '1'` and a 10-digit `number`, digits only.** Onboarding takes US numbers only, and neither the area code nor the exchange (the first and fourth digits) can be `0` or `1`. Anything else, such as another country code, a `+`, a 9-digit typo or `1005550100`, shows as invalid (`invalidPhone`), and `submit()` rejects with a `'validation'` error.
- **Check the number before you pass it.** The customer can't edit a locked field, so they can't fix a bad verified number themselves: the phone row stays invalid and submit stays disabled. If your own checks can verify a non-US number, catch that before showing the form, for example by telling the customer onboarding needs a US number.
- **The lock can't be lifted from `fieldProps`.** The SDK sets `readOnly` on the phone input after your props, so `fieldProps={{ phoneNumber: { readOnly: false } }}` has no effect. Style the read-only state with `[readonly]` or `:read-only` in your CSS.
- **It follows the prop.** Unlike `defaultValues`, a new `verifiedPhone` applies straight away. Set it to `undefined` to unlock the field; it then shows what the customer typed before, if anything.

`CoinmeOnboardingProvider` takes the same prop for a [headless](#headless-react) form, where `PhoneField` locks the same way. If you render a phone input of your own instead, make it read-only when `lockedPaths` from `useCustomerOnboarding()` includes `'phoneNumber'`:

```tsx
const MyPhoneInput = () => {
  const { values, setValue, lockedPaths } = useCustomerOnboarding();
  return (
    <input
      type="tel"
      value={values.phoneNumber}
      onChange={(event) => setValue('phoneNumber', event.target.value)}
      readOnly={lockedPaths.includes('phoneNumber')}
    />
  );
};
```

## Layout control

Choose how much of the structure you control. Styling works the same way at every level.

| Level | What you control | How |
| --- | --- | --- |
| **Drop-in** | Styling and copy | `<CustomerOnboardingForm>` with `fieldProps`, `classNames`, `labels`, … |
| **CSS layout** | Column and row arrangement, order | Target each row's `data-field` attribute with CSS grid or flexbox. No code changes. |
| **Custom layout** | The whole structure: sections, headings, columns, your own content between fields | The form's `children` render prop, which receives the pre-wired rows, the alert and the submit button |
| **Headless** | Everything, including the submit button and the form element | `CoinmeOnboardingProvider` with `OnboardingFormField` rows or the bare field components, and `useCustomerOnboarding` |

**CSS layout.** Every row is `<div class="coinme-onboarding-form__row" data-field="…">`, where `data-field` is the field's key (`email`, `firstName`, …, `ssn`). For example, to put fields side by side and keep some full width:

```css
.my-form {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
  gap: 0 16px;
}
.my-form [data-field='email'],
.my-form [data-field='addressLine1'],
.my-form [data-field='ssn'],
.my-form .coinme-onboarding-form__alert,
.my-form .coinme-onboarding-form__submit {
  grid-column: 1 / -1;
}
.my-form input,
.my-form select {
  width: 100%;
  box-sizing: border-box;
}
```

```tsx
<CustomerOnboardingForm className="my-form" environment="sandbox" getHeaders={getHeaders} onSuccess={onSuccess} />
```

Give inputs `width: 100%` and use `minmax(0, 1fr)` columns, so narrow screens don't overflow.

**Custom layout.** The render prop keeps the SDK's labels, inline errors, `aria-*` wiring, failure alert and submit button, and lets you place them:

```tsx
<CustomerOnboardingForm environment="sandbox" getHeaders={getHeaders} onSuccess={onSuccess}>
  {({ fields, alert, submitButton }) => (
    <>
      <h2>About you</h2>
      <div className="two-columns">
        {fields.firstName}
        {fields.lastName}
      </div>
      {fields.email}
      {fields.dateOfBirth}
      <h2>Home address</h2>
      {fields.addressLine1}
      <div className="three-columns">
        {fields.city}
        {fields.state}
        {fields.postalCode}
      </div>
      <MyDisclosure />
      {fields.phoneNumber}
      {fields.ssn}
      {alert}
      {submitButton}
    </>
  )}
</CustomerOnboardingForm>
```

- `fields` holds one row per field. Rows in `hiddenFields` are `null`, and optional fields you don't place are left out.
- **Place every required field**, or the form can never become valid.
- The render prop also receives `isValid`, `status` and `error`.
- The SDK keeps the `<form>` element and the submit handling.

**Headless with the SDK's rows.** `OnboardingFormField` is one labelled row (label, field and linked inline error). Use it anywhere inside `CoinmeOnboardingProvider`:

```tsx
<CoinmeOnboardingProvider environment="sandbox">
  <fieldset>
    <legend>About you</legend>
    <OnboardingFormField field="firstName" fieldProps={{ className: 'input' }} />
    <OnboardingFormField field="lastName" fieldProps={{ className: 'input' }} />
  </fieldset>
  <OnboardingFormField field="ssn" label="SSN" fieldProps={{ css: { fontSize: '16px' } }} />
  <SubmitButton />
</CoinmeOnboardingProvider>
```

`SubmitButton` is yours; see [Headless React](#headless-react).

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `field` | `CustomerOnboardingFormFieldKey` | — | **Required.** Which field the row renders, by [field key](#field-keys-and-field-paths), for example `'email'` or `'ssn'`. |
| `label` | `ReactNode` | The English label | The row's label. Text or JSX. |
| `fieldProps` | Depends on `field` | — | As the drop-in form's `fieldProps` entry for that field, for example `{ className: 'input' }`. |
| `validationMessages` | `Partial<Record<OnboardingValidationCode \| 'invalidSsn', string>>` | English | As for the drop-in form. |
| `classNames` | `{ row?, label?, control?, fieldError?: string }` | — | Extra classes for the row's parts. |

## Headless React

Build your own onboarding UI from a provider, field components and one hook.

```tsx
import {
  AddressLine1Field,
  CityField,
  CoinmeOnboardingError,
  CoinmeOnboardingProvider,
  CoinmeSsnField,
  DateOfBirthField,
  EmailField,
  FirstNameField,
  LastNameField,
  PhoneField,
  PostalCodeField,
  StateField,
  useCustomerOnboarding,
} from '@coinme-security/onboarding-sdk-react';

const SubmitButton = () => {
  const { isValid, submit, status, error } = useCustomerOnboarding({
    getHeaders: async () => ({
      // YOUR backend route; see "You build".
      Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
    }),
    onSuccess: (result) => {
      // Save the result on YOUR backend first: the verification token is minted from it.
      void postToYourBackend('/your-api/onboarding/complete', result).then(() =>
        startPhoneVerification(result)
      );
    },
  });

  return (
    <>
      <button
        // Also disabled after success, so the same customer isn't submitted twice.
        disabled={!isValid || status === 'submitting' || status === 'success'}
        onClick={() =>
          submit().catch((failure: unknown) => {
            // Shown below from `error`; rethrow anything your onSuccess threw.
            if (!(failure instanceof CoinmeOnboardingError)) throw failure;
          })
        }
      >
        Continue
      </button>
      {error && (
        <p role="alert">
          {error.retryable ? 'Please try again.' : "We couldn't onboard you."}
        </p>
      )}
    </>
  );
};

export const Onboarding = () => (
  <CoinmeOnboardingProvider environment="sandbox">
    <EmailField placeholder="Email" className="input" />
    <FirstNameField placeholder="First name" className="input" />
    <LastNameField placeholder="Last name" className="input" />
    <AddressLine1Field placeholder="Street address" className="input" />
    <CityField placeholder="City" className="input" />
    <StateField className="input" />
    <PostalCodeField placeholder="ZIP" className="input" />
    <PhoneField className="input" />
    <DateOfBirthField className="input" />
    <CoinmeSsnField
      placeholder="123-45-6789"
      ariaLabel="Social Security Number"
      containerProps={{ className: 'input' }}
      css={{ fontSize: '16px', fontFamily: 'Inter, sans-serif' }}
    />
    <SubmitButton />
  </CoinmeOnboardingProvider>
);
```

`submit()` returns a promise that rejects when the submit fails, and the hook also exposes the failure as `error`. When you render from `error`, as above, catch the `CoinmeOnboardingError` so the rejection isn't reported as unhandled, and rethrow anything else, such as an error thrown by your `onSuccess`.

The fields in this example have placeholders but no labels. In a real form, give each one a `<label htmlFor>` (pass the input an `id`), or use `OnboardingFormField` rows, which come labelled.

### `CoinmeOnboardingProvider`

Creates the onboarding vault for `environment` (`'sandbox'` or `'live'`), disposes of it on unmount, and holds the form's values and submit state. Render the field components and use `useCustomerOnboarding` anywhere inside it.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | — | **Required.** As for the drop-in form. Read once on mount; mount the provider again to switch. |
| `defaultValues` | `Partial<Record<OnboardingFieldPath, string>>` | `{}` | As for the drop-in form: values to prefill, keyed by [field path](#field-keys-and-field-paths). Read once on mount. |
| `verifiedPhone` | `VerifiedPhone` | — | As for the drop-in form: the number the customer verified. `PhoneField` (and any `OnboardingInputField` with `path="phoneNumber"`) becomes read-only and shows it, and the request sends it. Changes apply as they happen. See [Lock the phone to the verified number](#lock-the-phone-to-the-verified-number). |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when the vault can't be created, for example because the vault provider is blocked. This matches the drop-in form's `onVaultError`, not its `onError`: submit failures go to `useCustomerOnboarding`'s `onError`. |
| `vault` | `CoinmeVault` | — | A vault you created with `createOnboardingVault`, used instead of the provider creating its own. The provider won't clean it up. Most integrations leave it out. |
| `children` | `ReactNode` | — | Your form: field components, and components that call `useCustomerOnboarding`. |

### Field components

| Component | Field path | Default attributes |
| --- | --- | --- |
| `EmailField` | `email` | `type="email"`, `autoComplete="email"` |
| `FirstNameField` | `fullName.firstName` | `autoComplete="given-name"` |
| `MiddleNameField` | `fullName.middleName` | `autoComplete="additional-name"` |
| `LastNameField` | `fullName.lastName` | `autoComplete="family-name"` |
| `AddressLine1Field` | `address.line1` | `autoComplete="address-line1"` |
| `AddressLine2Field` | `address.line2` | `autoComplete="address-line2"` |
| `CityField` | `address.city` | `autoComplete="address-level2"` |
| `StateField` (`<select>`) | `address.state` | `autoComplete="address-level1"`; lists the US states and DC by full name; each option's value is the two-letter code |
| `PostalCodeField` | `address.postalCode` | `autoComplete="postal-code"`, `inputMode="numeric"` |
| `PhoneField` | `phoneNumber` | `type="tel"`, `autoComplete="tel-national"`, `inputMode="tel"`, `placeholder="(000) 000-0000"`, formats as `(206) 555-0100` |
| `DateOfBirthField` | `dateOfBirth` | `inputMode="numeric"`, `autoComplete="bday"`, `placeholder="mm/dd/yyyy"`, formats as `MM/DD/YYYY` |
| `OnboardingInputField` | any (`path` prop) | none; use it for fields without a named component |
| `CoinmeSsnField` | the secure SSN | see below |

- **The SDK owns only what binds a field:** `name`, `value` and `onChange`. Every other prop goes straight onto the `<input>` or `<select>` (`className`, `style`, `placeholder`, `aria-*`, `data-*`, and the defaults above, which you can override).
- **The one exception is a locked field.** While the provider has a `verifiedPhone`, the SDK also owns the phone input's `readOnly` and always sets it, so your `readOnly={false}` can't unlock it.
- Your `onBlur` still runs.
- `aria-invalid` is set once a field is touched and invalid, unless you pass your own.
- Each field forwards its `ref` to the element.
- **`PhoneField` and `DateOfBirthField` format as the customer types.** The phone takes US numbers only (see [Phone verification](#phone-verification)): it keeps only digits, so `+` and other characters can't be entered, and it drops a pasted, autofilled or typed `+1`. A longer number keeps all its digits and is reported as `invalidPhone`, never shortened into a different US number. A digit typed into a complete phone number is ignored. The date of birth is typed as `MM/DD/YYYY` and sent as the `YYYY-MM-DD` the endpoint expects. A one-digit month or day followed by `/` gets a leading zero (`6/15/1990` shows as `06/15/1990`), and a pasted, autofilled or `defaultValues` date in `YYYY-MM-DD` form is shown as `MM/DD/YYYY`. Pass `mask={undefined}` to turn formatting off, or `type="date"` on `DateOfBirthField` for the browser's date picker. Any plain field takes a `mask` of your own (see below).
- `StateField` takes an `emptyOptionLabel` (default `Select a State`), or your own `<option>` children. Option values must be two-letter state codes. The built-in names are in English; pass your own options to show them in another language: `<StateField><option value="NY">Nueva York</option>…</StateField>`.

**Format a field as the customer types.** Give any plain field a `mask`, an `OnboardingInputMask` with two functions: `toDigits` keeps the digits the field allows, and `format` shows them. `toDigits` gets the stored value, and the field's full new text (separators included) when the customer types, pastes or autofills; after a deletion it gets only the digits left. Add each separator only once a digit follows it, so backspace never gets stuck on one:

```tsx
import type { OnboardingInputMask } from '@coinme-security/onboarding-sdk-react';

// ZIP+4: 98101-1234
const zipMask: OnboardingInputMask = {
  toDigits: (value) => value.replace(/\D/g, '').slice(0, 9),
  format: (digits) =>
    digits.length > 5 ? `${digits.slice(0, 5)}-${digits.slice(5)}` : digits,
};

<PostalCodeField mask={zipMask} className="input" />;
// In the drop-in form: fieldProps={{ postalCode: { mask: zipMask } }}
```

The value is stored as shown, so the formatted value must still pass [validation](#input-and-validation) (`98101-1234` does). It's also read back through `toDigits` on every render, so `format(toDigits(format(digits)))` must equal `format(digits)`. A `format` that adds digits, such as a `+1 ` prefix, breaks this: `+1 (206` reads back as `1206`. Keep such text outside the value, for example in the label.

**`CoinmeSsnField`** renders a container that the vault's iframe mounts into.

- The SDK owns the field's name, `type: 'ssn'`, its validation, the `###-##-####` mask and a serializer that submits the nine digits without dashes.
- Typed digits are hidden by default. Pass `hideValue={false}` to show them, or add a show/hide button (see below).
- The input sits inside an iframe, so a `<label>` on your page can't name it for screen readers. The SDK sets the secure field's `ariaLabel` to `'Social Security Number'` (in `OnboardingFormField` and `CustomerOnboardingForm`, to the row's label when it's a string). Pass `ariaLabel` to change it, for example when you translate the form.
- Every other secure field option passes straight through: `css`, `classes`, `placeholder`, `autoComplete`, and options the vault provider adds later.
- Use `containerProps` for the container's `className` and `style`, and `testId` for its `data-testid`. Size the container yourself; see [Styling](#styling).
- Options apply on mount. Its `ref` is the secure field instance, so call `ref.current.update(...)` to change them later, for example when switching themes.

**Let the customer show the SSN digits.** Toggle `hideValue` on the secure field through the `ref`:

```tsx
const ssnRef = useRef<CollectField>(null);
const [hidden, setHidden] = useState(true);

const toggle = () => {
  ssnRef.current?.update({ hideValue: !hidden });
  setHidden(!hidden);
};

<>
  <CoinmeSsnField ref={ssnRef} containerProps={{ className: 'input' }} />
  <button type="button" onClick={toggle} aria-pressed={!hidden}>
    {hidden ? 'Show' : 'Hide'}
  </button>
</>;
```

Only the display changes; the SSN stays inside the vault's iframe. `CollectField` is exported from this package; see [Types for the vault and the SSN field](#types-for-the-vault-and-the-ssn-field).

### `useCustomerOnboarding(options)`

Call it in any component inside `CoinmeOnboardingProvider`. Its options:

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `getHeaders` | `() => Record<string, string> \| Promise<Record<string, string>>` | — | As for the drop-in form: returns the request headers, called just before each submit. Needed in practice. |
| `timeoutMs` | `number` | `60000` | Fail the submit with a `network` error if no response arrives within this many milliseconds. The request may still have reached Coinme; see [Error handling](#error-handling). |
| `onSuccess` | `(result: { customerId: string }) => void` | — | Called when a submit made with this hook's `submit` succeeds. If it throws, `status` stays `'success'` and `submit()` rejects with your error. It isn't awaited, so only a synchronous throw reaches `submit()`; a rejected `async` callback is an unhandled rejection. |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when a submit made with this hook's `submit` fails, including when client-side validation stops it (`kind: 'validation'`). |

It returns:

| Property | Type | Description |
| --- | --- | --- |
| `values` | `OnboardingFormValues` | The current value of each plain field as shown, keyed by [field path](#field-keys-and-field-paths), for example `values['address.city']`. A formatted field holds its formatted value, such as `'(206) 555-0100'` or `'06/15/1990'`; it's converted to the request's format on submit. With a `verifiedPhone`, `phoneNumber` holds it formatted the same way, `'(206) 555-0100'` (or, for a number that isn't a US one, `'+65 91234567'`, marked `invalidPhone`). |
| `setValue` | `(path: OnboardingFieldPath, value: string) => void` | Sets a plain field's value. The field components call it for you; use it for inputs of your own. Ignored for a locked field, so unlocking brings back what was entered before the lock. |
| `fieldErrors` | `Partial<Record<OnboardingFieldPath, OnboardingValidationCode>>` | The validation code for each plain field that's currently invalid, touched or not, for example `{ 'address.postalCode': 'invalidPostalCode' }`. Empty when every plain field is valid. |
| `touched` | `Partial<Record<OnboardingFieldPath, boolean>>` | Which fields are touched, for example `{ email: true }`. Show a field's error only once it's touched. |
| `lockedPaths` | `readonly OnboardingFieldPath[]` | The fields the customer can't edit: `['phoneNumber']` while the provider has a `verifiedPhone`, otherwise `[]`. The field components handle this; check it to make inputs of your own read-only too. |
| `ssnState` | `OnboardingSsnState \| null` | The SSN field's state: `isValid`, `isEmpty`, `isDirty`, `isFocused`, `isTouched`, `errorMessages` and `last4`. `null` until the field has loaded. Never the SSN itself. |
| `isValid` | `boolean` | `true` when the vault is ready and every field, including the SSN, is valid. Use it to enable your submit button. |
| `vaultStatus` | `'loading' \| 'ready' \| 'error'` | Whether the secure SSN field has loaded. |
| `vaultError` | `CoinmeOnboardingError \| null` | Why the secure SSN field failed to load, when `vaultStatus` is `'error'`. |
| `submit` | `() => Promise<CustomerOnboardingResult>` | Validates and submits. Resolves with `{ customerId, phoneNumber }`, or rejects with a `CoinmeOnboardingError`, or with your own error if `onSuccess` throws. Calling it again while a submit is in flight returns the same promise instead of submitting twice. |
| `status` | `'idle' \| 'submitting' \| 'success' \| 'error'` | The state of the most recent submit; `'idle'` before the first one. |
| `error` | `CoinmeOnboardingError \| null` | Why the most recent submit failed. |
| `result` | `CustomerOnboardingResult \| null` | The result of the most recent successful submit: `{ customerId, phoneNumber }`. |

To show an error only after the customer has left a field:

```tsx
import {
  DEFAULT_VALIDATION_MESSAGES,
  useCustomerOnboarding,
  type OnboardingFieldPath,
} from '@coinme-security/onboarding-sdk-react';

const FieldError = ({ path }: { path: OnboardingFieldPath }) => {
  const { fieldErrors, touched } = useCustomerOnboarding();
  const code = touched[path] ? fieldErrors[path] : undefined;
  return code ? <span className="error">{DEFAULT_VALIDATION_MESSAGES[code]}</span> : null;
};

// Inside CoinmeOnboardingProvider:
<EmailField />
<FieldError path="email" />
```

### Types for the vault and the SSN field

The types you need to name in your code are all exported from this package:

- `CoinmeVault`: the `vault` prop, and what `createOnboardingVault` returns.
- `CollectField`: the `ref` of `CoinmeSsnField`.
- `CoinmeSsnFieldProps`: the SSN field's options, including `containerProps` and `testId`.

```tsx
import {
  CoinmeSsnField,
  type CollectField,
} from '@coinme-security/onboarding-sdk-react';
import { useRef } from 'react';

const ssnRef = useRef<CollectField>(null);
// …
<CoinmeSsnField ref={ssnRef} css={lightCss} />;
// Later, for example when switching themes:
ssnRef.current?.update({ css: darkCss });
```

`CoinmeVault` and `CollectField` come from the Coinme Vault SDK, which this package installs for you. You don't need to add it to your own dependencies.

## Styling

Styling is pass-through at every level: no theme object, no bundled CSS, no Coinme branding.

**Built-in class names.** The drop-in form and `OnboardingFormField` render these classes; add your own alongside them with `className`/`classNames`:

| Element | Built-in class | `classNames` key |
| --- | --- | --- |
| `<form>` | `coinme-onboarding-form` | `form` (or `className`) |
| Each row | `coinme-onboarding-form__row`, plus `data-field="<field key>"` | `row` |
| Each label | `coinme-onboarding-form__label` | `label` |
| Wrapper around each input, select or SSN container | `coinme-onboarding-form__control` | `control` |
| Inline field error | `coinme-onboarding-form__field-error` | `fieldError` |
| Submit-failure message | `coinme-onboarding-form__alert` | `alert` |
| Submit button | `coinme-onboarding-form__submit` | `submit` |

**Plain fields.** Pass any element prop through `fieldProps` (drop-in) or directly on the field component (headless): `className`, `style`, `placeholder`, `data-*`, …. Style the invalid state with `[aria-invalid='true']`.

**The SSN field is an iframe, so page CSS can't reach inside it.**

- **Inside the field**, use the secure field's `css` option. It takes JSON-CSS with pseudo-classes, state classes (`valid`, `invalid`, `empty`, `dirty`, `touched`) and `@font-face` for web fonts:

  ```tsx
  <CoinmeSsnField
    css={{
      fontFamily: 'Inter, sans-serif',
      fontSize: '16px',
      color: '#1a1a1a',
      '&::placeholder': { color: '#9ca3af' },
      '&.invalid.touched': { color: '#b91c1c' },
    }}
  />
  ```
- **Size the container**, and make the iframe fill it. The SDK doesn't style either, so without this the iframe keeps the browser's default 150px height. Give the container the same class as your inputs, with a fixed `height`:

  ```css
  .input {
    height: 44px;
    box-sizing: border-box;
    padding: 0 12px;
  }
  .input iframe {
    display: block;
    width: 100%;
    height: 100%;
    border: 0;
  }
  ```
- **Around the field**, style the container with `containerProps` (`className`, `style`). The vault provider also adds state classes to the container (`vgs-collect-container__focused`, `__invalid`, `__empty`, `__dirty`, `__touched`). Map them to your own class names with the `classes` option, for example `classes={{ focused: 'is-focused', invalid: 'is-invalid' }}`. In `OnboardingFormField` and `CustomerOnboardingForm` the container also gets `aria-invalid="true"` while its inline error shows, so one rule styles every field:

  ```css
  .input:focus,
  .input.vgs-collect-container__focused {
    border-color: #4f46e5;
  }
  .input[aria-invalid='true'] {
    border-color: #dc2626;
  }
  ```
- Media queries inside `css` use the iframe's width, not the page's.

For every option, see our vault provider's [customization reference](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/customization); all of it passes through `CoinmeSsnField`.

## Phone verification

> **A first version.**
>
> Phone verification is a first version of this step and will be extended.

> **US phone numbers only.**
>
> Onboarding and SMS verification presently support US phone numbers only: a 10-digit number with country code `1`, whose area code and exchange don't start with `0` or `1`. If Coinme adds support for other jurisdictions, it will release an update.

> **Authorize it with a token for this customer.**
>
> Every send and every check needs a Transient Auth Token your backend mints for the `customerId` that onboarding returned. Not your partner access token, and not the sign-up session token you onboarded with. The token is the only thing that ties the calls to the customer. Your backend mints it for the `customerId` it saved when onboarding succeeded; the page never sends one. See [You build](#you-build).

Coinme doesn't consider KYC complete until a newly onboarded customer verifies their phone. Verification covers steps 4 to 8 of the [recommended integration flow](#recommended-integration-flow): it runs right after onboarding, and again whenever an unverified customer signs back in, always against the phone number the customer onboarded with. It succeeds only when the code checks out; anything else is a failure, and the customer hasn't completed KYC.

Pass `phoneNumber` from the onboarding result (or the copy you stored on your backend) as is. Don't let the customer type a different number at this step. Coinme texts whatever number it's sent and, once the code checks out, records that number as the customer's verified phone; it doesn't check it against the onboarded number. Making sure it's the onboarded number is up to you.

A code works for about a minute (60 seconds) after it's sent. Coinme currently reports an expired code as `codeIncorrect`, not `codeExpired`, so when a code is rejected, offer to send a new one as well as to type it again. The drop-in step always shows a resend button for this.

### `PhoneVerificationStep`

The drop-in step. It shows where the code will go (all but the last 4 digits hidden), sends the code when the customer presses the button, takes the code, and calls `onVerified` once it checks out. Nothing is sent until the customer presses the button. See the [Quickstart](#quickstart) for it in context:

```tsx
<PhoneVerificationStep
  environment="sandbox"
  phoneNumber={onboarded.phoneNumber}
  // YOUR backend route; it mints the token for the customerId it saved. See "You build".
  getHeaders={async () => ({
    Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
  })}
  onVerified={() => goToWelcome(onboarded.customerId)}
  onError={(error) => reportVerificationFailure(error.kind)}
/>
```

It moves through three screens, shown as `data-screen` on its `<form>`:

- `'send'`: "we'll text a code to (•••) •••-0100" and the send button. A failed send stays here.
- `'code'`: one box per digit (6 by default; set `codeLength` to change it), the verify button and a resend button. The code is checked as soon as the last box is filled; Verify stays as a fallback. Typing moves to the next box, Backspace on an empty box goes back, the arrow keys move between boxes, and non-digits are ignored. Pasting a code, or the phone's SMS autofill (the first box has `autocomplete="one-time-code"`), fills every box at once. A paste with fewer or more digits than the code replaces the boxes but isn't checked until the customer completes it or taps Verify. So is a code typed or autofilled into a box already holding its first or last digit, because it can't be told apart from a partial entry merged with that digit. A failed check stays here, with the error alert:
  - a wrong or expired code clears the boxes and puts the customer back in the first one;
  - too many attempts with a wait (`retryAfterSeconds`) disables the boxes, Verify and resend and shows a countdown until the customer can try again;
  - once every attempt is used (`attemptsExhausted`), everything stays disabled and the alert points the customer to support.
- `'verified'`: the phone is verified.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | — | **Required.** The environment you onboarded in. |
| `phoneNumber` | `string` | — | **Required.** `phoneNumber` from the onboarding result. |
| `getHeaders` | `() => Record<string, string> \| Promise<Record<string, string>>` | — | Returns the headers for each verification call: `{ Authorization: 'Bearer <token>' }` with a Transient Auth Token your backend mints for the new `customerId`, never your partner access token or the sign-up session token. Called before every send and every check, so fetch a fresh token inside it. |
| `onVerified` | `() => void` | — | Called once the code checks out. If it throws, the step stays verified. |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when a send or a check fails. See the kinds below. |
| `codeLength` | `number` | `6` | How many digits the code has: one box per digit. |
| `timeoutMs` | `number` | `60000` | Fail a call as `network` if no response arrives in this many milliseconds. |
| `apiBaseUrl` | `string` | Coinme's | Send the calls to this base URL instead, for example a route on your own server that forwards them to Coinme. |
| `labels` | `Partial<PhoneVerificationStepLabels>` | English | The step's text. `sendPrompt`, `codeSent` and `verified` are functions that get the masked number; `digit(position, length)` is each box's accessible name (default `'Digit 1 of 6'`); `retryIn(seconds)` is the countdown text. The defaults are exported as `DEFAULT_PHONE_VERIFICATION_LABELS`. |
| `errorMessages` | `Partial<Record<CoinmeOnboardingErrorKind, string>>` | English | The error alert text per kind. Without an entry, the step uses the form's `DEFAULT_ERROR_MESSAGES`, and points the customer to support once every attempt is used. |
| `inputProps` | input props | — | Pass-through props spread onto every code box `<input>`, except `name`, `value`, `defaultValue` and `onChange`. `type`, `inputMode`, `pattern`, `autoComplete` and `aria-label` default to a numeric one-time code and can be replaced. Your `onKeyDown`, `onPaste` and `onFocus` run first; call `preventDefault()` to skip the step's handling. `testId` becomes each box's `data-testid` with `_<index>` appended, for example `code_0`. |
| `submitProps`, `resendProps` | button props | — | Pass-through props for the send/verify button and the resend button. The step owns `type`, the text and (for resend) `onClick`, and keeps them disabled while a call is in flight. |
| `className`, `classNames` | `string`, `PhoneVerificationStepClassNames` | — | Class names added to the step's built-in `coinme-phone-verification*` classes: `form`, `row`, `label`, `control`, `codeGroup` (the boxes' container), `codeBox` (each box), `message`, `hint` (the countdown), `alert`, `submit`, `resend`. The step ships no CSS, so lay the boxes out yourself, for example `.code-boxes { display: flex; gap: 8px }`. |
| `children` | `(layout: PhoneVerificationStepLayout) => ReactNode` | — | A custom layout. Receives the pre-wired `codeField` (the labelled boxes), `submitButton`, `resendButton`, `message`, `retryHint` (the countdown) and `alert` (each `null` when it doesn't belong on the current `screen`), plus `screen`, `status`, `error` and `retryInSeconds`. The `<form>` and its submit handling stay with the SDK. |
| `testId` | `string` | — | Rendered as `data-testid` on the `<form>`. |

### `usePhoneVerification(options)`

The hook the step is built on, for your own UI. It takes the same `environment`, `phoneNumber`, `getHeaders`, `onVerified`, `onError`, `timeoutMs` and `apiBaseUrl`, and works without `CoinmeOnboardingProvider`.

| Returns | Type | Description |
| --- | --- | --- |
| `status` | `'idle' \| 'sending' \| 'codeSent' \| 'verifying' \| 'verified' \| 'error'` | Where verification is. |
| `error` | `CoinmeOnboardingError \| null` | Why the last call failed, when `status` is `'error'`. |
| `codeSentAt` | `number \| null` | When the last code was sent (milliseconds since the epoch). `null` until one is sent, so after a failure it tells you whether to keep showing the code input. |
| `sendCode` | `() => Promise<void>` | Texts a code to `phoneNumber`. Calling it again sends a new code, and the previous one stops working. |
| `verifyCode` | `(code: string) => Promise<void>` | Checks the code the customer typed. Spaces and dashes are ignored. |
| `reset` | `() => void` | Back to `'idle'`, dropping any result in flight. |

`sendCode` and `verifyCode` reject with the same `CoinmeOnboardingError` that's put in `error` and passed to `onError`, so catch them. While a call is in flight, calling the same one again returns that call's promise instead of sending a second request, and calling the other one waits for it to settle first. After `reset` or unmount, a call in flight resolves without changing anything, so act on success in `onVerified` (or when `status` is `'verified'`), not on the promise alone.

```tsx
const VerifyPhone = ({ customerId, phoneNumber }: CustomerOnboardingResult) => {
  const [code, setCode] = useState('');
  const { status, error, codeSentAt, sendCode, verifyCode } = usePhoneVerification({
    environment: 'sandbox',
    phoneNumber,
    // YOUR backend route; it mints the token for the customerId it saved. See "You build".
    getHeaders: async () => ({
      Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
    }),
    onVerified: () => goToWelcome(customerId),
  });
  const ignoreSdkError = (caught: unknown) => {
    // SDK failures are in `error`; rethrow anything your callbacks threw.
    if (!(caught instanceof CoinmeOnboardingError)) throw caught;
  };

  if (status === 'verified') return <p>Your phone is verified.</p>;
  if (codeSentAt === null) {
    return (
      <>
        {error && <p role="alert">{error.message}</p>}
        <button disabled={status === 'sending'} onClick={() => sendCode().catch(ignoreSdkError)}>
          Text me a code
        </button>
      </>
    );
  }
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        verifyCode(code).catch(ignoreSdkError);
      }}
    >
      <input
        autoComplete="one-time-code"
        inputMode="numeric"
        value={code}
        onChange={(event) => setCode(event.target.value)}
      />
      {error && <p role="alert">{error.message}</p>}
      <button disabled={status === 'verifying'}>Verify</button>
      <button type="button" onClick={() => sendCode().catch(ignoreSdkError)}>
        Send a new code
      </button>
    </form>
  );
};
```

### When verification fails

The failures specific to this step (see [Error handling](#error-handling) for the full list):

| `kind` | What to tell the customer |
| --- | --- |
| `codeIncorrect` | The code is wrong, or it expired (a code works for about a minute). Let them type it again or send a new one. |
| `codeExpired` | The code expired. Send a new one. |
| `tooManyAttempts` | Too many failed checks, or the account's phone number has been changed too often. `error.retryAfterSeconds` says how long to wait. When `error.attemptsExhausted` is `true`, they've used every attempt: point them to support. |
| `smsNotSent` | Coinme didn't confirm the text was sent. Try again. |
| `phoneNotSupported` | The number can't receive verification texts (not a mobile number, a carrier that isn't allowed, or recently used by another account). Point them to support. |
| `phoneAlreadyInUse` | The number belongs to another Coinme account. Point them to support. |
| `unauthorized` | The token was missing or expired, or wasn't a Transient Auth Token minted for this `customerId`: a partner access token or the sign-up session token is rejected too. Mint a fresh one for the customer and try again. |

Until a code checks out, the customer hasn't completed KYC, whatever your UI shows. A customer who leaves before verifying still exists at Coinme: a second onboarding with the same details fails as `duplicate`. Send them back to verification when they return (step 8 of the [recommended integration flow](#recommended-integration-flow)).

## Core API (without React)

The core works in any JavaScript app: vanilla JS, Vue, Angular, Svelte, or React if you'd rather build on it directly. The React layer is built on it.

Import it from the `/core` entry, which contains no React code, so a non-React app doesn't need `react` installed:

```typescript
import { submitCustomerOnboarding } from '@coinme-security/onboarding-sdk-react/core';
```

Every core export is also available from the package root. That root entry includes the React API, so it needs `react` installed. The examples below import from `/core`.

The package ships ES modules and CommonJS for a bundler (Vite, webpack, Rollup, esbuild, …). It has no `<script>` tag build.

### 1. Create the onboarding vault and the secure SSN field

```typescript
import {
  createOnboardingVault,
  ONBOARDING_FIELD_NAMES,
} from '@coinme-security/onboarding-sdk-react/core';

// Browser-only: call after the page (or view) has mounted.
const vault = await createOnboardingVault({ environment: 'sandbox' });

// Mounts the vault's secure field iframe into <div id="ssn"></div>.
const ssnField = vault.createTextField('#ssn', {
  name: ONBOARDING_FIELD_NAMES.ssn,
  type: 'ssn',
  validations: ['required', 'validSSN'],
  hideValue: true,
  serializers: [{ name: 'replace', options: { old: '-', new: '' } }],
  placeholder: '123-45-6789',
  ariaLabel: 'Social Security Number',
});
// The secure field accepts an options object here, but its TypeScript type only
// declares the positional form, so cast to call the object form.
(ssnField as unknown as { mask: (options: object) => void }).mask({
  mask: '999-99-9999',
  maskChar: null,
  formatChars: { 9: '[0-9]' },
  hideValue: true,
});
```

- Name the field `ONBOARDING_FIELD_NAMES.ssn`; the request builder reads the SSN by that name.
- The `replace` serializer strips the mask's dashes, so nine digits are sent.
- `hideValue: true` hides the typed digits. Pass it to `mask()` too, in the object form: the positional form, `mask('999-99-9999', …)`, turns hiding back off. The field's type declares only the positional form, hence the cast.
- Size the field's container yourself, as in [Styling](#styling).
- Every other secure field option (`css`, `classes`, …) passes straight through.
- Read the field's validity from `vault.getFormState().fields.ssn`, and call `vault.subscribe` to be notified of changes.
- Call `vault.dispose()` when the form goes away.

### 2. Collect the other details and submit

```typescript
import {
  CoinmeOnboardingError,
  submitCustomerOnboarding,
} from '@coinme-security/onboarding-sdk-react/core';

try {
  const { customerId } = await submitCustomerOnboarding(
    vault,
    {
      email: 'jane.doe@example.com',
      fullName: { firstName: 'Jane', lastName: 'Doe' },
      address: {
        line1: '123 Main St',
        city: 'Seattle',
        state: 'WA',
        postalCode: '98101',
      },
      phoneNumber: '(206) 555-0100',
      dateOfBirth: '1990-06-15',
    },
    {
      headers: {
        // YOUR backend route; see "You build".
        Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
      },
    }
  );
} catch (error) {
  if (error instanceof CoinmeOnboardingError) {
    // See "Error handling" below.
  }
}
```

`submitCustomerOnboarding` validates the input first. If validation fails, it throws a `'validation'` error and sends nothing. The SSN comes from the secure field; you never pass it in.

Its options are `headers`, `timeoutMs` (default 60 000; after a timeout the request may still have reached Coinme, see [Error handling](#error-handling)) and `now` (the date ages are measured against; defaults to today).

**Submitting through the vault yourself.** In the next examples, `input` is the customer details object from the example above, and `headers` the headers object. For full control of the request, `buildCustomerOnboardingRequest(input)` returns the `{ data }` descriptor for `vault.submit`, and `toCoinmeOnboardingError` normalizes whatever it throws:

```typescript
try {
  const result = await vault.submit({
    ...buildCustomerOnboardingRequest(input),
    headers,
  });
} catch (error) {
  throw toCoinmeOnboardingError(error);
}
```

This skips client-side validation, so call `validateCustomerOnboardingInput` first.

### 3. Verify the phone

Once onboarding returns, text the customer a code with `sendPhoneVerificationCode`, then check the code they type with `validatePhoneVerificationCode`. Both take a Transient Auth Token your backend mints for the new `customerId`, never your partner access token (see [You build](#you-build)), so fetch fresh headers for each call. This example reuses the Quickstart's helpers; it's one way to do it, not the only way:

```typescript
import {
  CoinmeOnboardingError,
  sendPhoneVerificationCode,
  validatePhoneVerificationCode,
} from '@coinme-security/onboarding-sdk-react/core';

const result = await submitCustomerOnboarding(vault, input, { headers });
// Save customerId and phoneNumber on YOUR backend first: the verification token is minted from it.
await postToYourBackend('/your-api/onboarding/complete', result);

const verificationOptions = async () => ({
  environment: 'sandbox' as const,
  // YOUR backend route; it mints the token for the customerId it saved. See "You build".
  headers: {
    Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
  },
});

// When the customer asks for the code:
await sendPhoneVerificationCode({ phoneNumber: result.phoneNumber }, await verificationOptions());

// When they submit it:
try {
  await validatePhoneVerificationCode(
    { validationCode: codeInput.value },
    await verificationOptions()
  );
  showVerified();
} catch (error) {
  if (!(error instanceof CoinmeOnboardingError)) throw error;
  // An expired code is currently reported as codeIncorrect, so offer a new code there too.
  if (error.kind === 'codeIncorrect') showTryAgainOrSendNewCode();
  else if (error.kind === 'codeExpired') showSendNewCode();
  else showVerificationFailed(error.kind); // see "When verification fails"
}
```

- `sendPhoneVerificationCode` rejects with `'validation'` (`fieldErrors.phoneNumber: 'invalidPhone'`) before sending when the number isn't a US number, and with `'smsNotSent'` when Coinme's response doesn't confirm the text went out. A code works for about a minute. Calling it again sends a new code, and the previous one stops working.
- `validatePhoneVerificationCode` ignores spaces and dashes in the code, and rejects with `'codeIncorrect'` before sending when what's left isn't all digits. It sends the code to Coinme as `phoneValidationCode`.
- Both take `environment`, `headers`, `timeoutMs` (default 60 000), `apiBaseUrl` and `signal` (an `AbortSignal`; an aborted call rejects with the signal's reason rather than a `CoinmeOnboardingError`).
- A resolved `validatePhoneVerificationCode` means Coinme accepted the code. Coinme is the authority on whether the phone is verified: record the result on your backend, and don't rely on client-side state alone.

### Vanilla JS example

A complete page: the plain inputs are ordinary form controls, the SSN goes in a container the vault mounts its iframe into, and the submit button stays disabled until the SSN field is valid.

```markup
<form id="onboarding" novalidate>
  <input name="email" type="email" autocomplete="email" placeholder="Email" />
  <input name="firstName" autocomplete="given-name" placeholder="First name" />
  <input name="lastName" autocomplete="family-name" placeholder="Last name" />
  <input name="line1" autocomplete="address-line1" placeholder="Street address" />
  <input name="city" autocomplete="address-level2" placeholder="City" />
  <input name="state" autocomplete="address-level1" placeholder="State (WA)" />
  <input name="postalCode" autocomplete="postal-code" placeholder="ZIP code" />
  <input name="phoneNumber" type="tel" autocomplete="tel-national" placeholder="Phone" />
  <input name="dateOfBirth" type="date" autocomplete="bday" />
  <div id="ssn"></div>
  <button type="submit" disabled>Submit</button>
  <p id="message" role="alert"></p>
</form>

<script type="module">
  import {
    CoinmeOnboardingError,
    createOnboardingVault,
    ONBOARDING_FIELD_NAMES,
    submitCustomerOnboarding,
  } from '@coinme-security/onboarding-sdk-react/core';

  const form = document.querySelector('#onboarding');
  const button = form.querySelector('button');
  const message = document.querySelector('#message');

  const vault = await createOnboardingVault({ environment: 'sandbox' });

  const ssnField = vault.createTextField('#ssn', {
    name: ONBOARDING_FIELD_NAMES.ssn,
    type: 'ssn',
    validations: ['required', 'validSSN'],
    hideValue: true,
    serializers: [{ name: 'replace', options: { old: '-', new: '' } }],
    placeholder: '123-45-6789',
    ariaLabel: 'Social Security Number',
  });
  ssnField.mask({
    mask: '999-99-9999',
    maskChar: null,
    formatChars: { 9: '[0-9]' },
    hideValue: true,
  });

  // Enable submit once the SSN is valid. The other fields are validated on submit.
  vault.subscribe(() => {
    button.disabled = !vault.getFormState().fields.ssn?.isValid;
  });

  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    const value = (name) => form.elements[name].value;
    button.disabled = true;
    message.textContent = '';
    try {
      const result = await submitCustomerOnboarding(
        vault,
        {
          email: value('email'),
          fullName: { firstName: value('firstName'), lastName: value('lastName') },
          address: {
            line1: value('line1'),
            city: value('city'),
            state: value('state'),
            postalCode: value('postalCode'),
          },
          phoneNumber: value('phoneNumber'),
          dateOfBirth: value('dateOfBirth'), // <input type="date"> gives YYYY-MM-DD
        },
        {
          headers: {
            // YOUR backend route; see "You build".
            Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
          },
        }
      );
      // Save customerId and phoneNumber on YOUR backend, then verify the phone.
      await postToYourBackend('/your-api/onboarding/complete', result);
      startPhoneVerification(result);
    } catch (error) {
      if (!(error instanceof CoinmeOnboardingError)) throw error;
      // error.fieldErrors maps each invalid field path to a code; see "Input and validation".
      message.textContent =
        error.kind === 'validation'
          ? 'Check your details and try again.'
          : error.retryable
            ? 'Something went wrong. Try again.'
            : 'We could not complete your onboarding.';
    } finally {
      button.disabled = !vault.getFormState().fields.ssn?.isValid;
    }
  });
</script>
```

- In plain JavaScript, `mask()` takes the options object directly; the cast in the TypeScript example above isn't needed.
- On a classic multi-page site, the page unload cleans up the vault. In any view system that swaps DOM (Vue, Angular, Svelte, a router), create the vault when the view mounts and call `vault.dispose()` when it's removed.
- Validate as the customer types with `validateCustomerOnboardingInput`, as in [Input and validation](#input-and-validation).

### Input and validation

| Field | Format | Notes |
| --- | --- | --- |
| `email` | email address | Required. |
| `fullName.firstName`, `fullName.lastName` | text | Required. Printable ASCII only. |
| `fullName.middleName` | text | Optional. Printable ASCII only. |
| `fullName.otherNames` | array of text | Optional. Printable ASCII only. Blank entries are dropped, and the field is left out when none remain. Validation errors and the React components use the paths `fullName.otherNames.0`, `fullName.otherNames.1`, …: whole numbers from 0, with no gaps. |
| `address.line1`, `address.city` | text | Required. Printable ASCII only. |
| `address.line2` | text | Optional. Printable ASCII only. |
| `address.state` | two-letter US state code or `DC` | Required. Any of the 50 states or DC. Case-insensitive; sent upper-case. |
| `address.postalCode` | `12345` or `12345-6789` | Required. |
| `address.country` | three-letter country code | Optional; defaults to `USA`. |
| `phoneNumber` | US number | Required. US numbers only. Formatting is ignored; sent as `{ countryCode: '1', number: '<10 digits>' }`. |
| `dateOfBirth` | `YYYY-MM-DD` | Required. The customer must be 18 or older. |

Values are trimmed before sending.

`validateCustomerOnboardingInput(input)` checks these rules, for example as the customer types. It returns `{ valid, fieldErrors }`, where `fieldErrors` maps a field path (for example `'address.postalCode'`) to one code:

| Code | Meaning |
| --- | --- |
| `required` | The field is empty. |
| `invalidEmail` | Not a well-formed email address: letters, digits and `._%+-` before the `@` (not starting or ending with a dot), a domain whose labels don't start or end with a hyphen, a letter-only top-level domain, and no consecutive dots. |
| `invalidDate` | Not a real date in `YYYY-MM-DD` form. `DateOfBirthField` converts the `MM/DD/YYYY` the customer types before validating. |
| `underMinimumAge` | The customer is younger than 18. |
| `overMaximumAge` | The date of birth is more than 120 years ago. |
| `invalidState` | Not a US state code. |
| `invalidPostalCode` | Not a 5-digit ZIP or ZIP+4. |
| `invalidPhone` | Not a 10-digit US number. |
| `invalidCountry` | Not a three-letter country code. |
| `nonAscii` | Contains characters outside printable ASCII (for example accents). |

Only the first failure per field is reported. They're codes rather than messages, so the copy is yours. Client-side validation is for the customer's benefit; Coinme's service makes the final decision.

## Error handling

Every failure is a `CoinmeOnboardingError` with a `kind` you can branch on and a `retryable` flag.

```typescript
try {
  const { customerId } = await submitCustomerOnboarding(vault, input, { headers });
} catch (error) {
  if (!(error instanceof CoinmeOnboardingError)) throw error;
  switch (error.kind) {
    case 'validation':
      // Nothing was sent. Plain fields: error.fieldErrors; SSN: error.secureFieldErrors.
      showFieldErrors(error.fieldErrors);
      break;
    case 'unauthorized':
      // Get a fresh token and try again.
      break;
    case 'configuration':
      // Refused before sending, or the package isn't configured. Fix the integration.
      reportIntegrationError(error.message);
      break;
    default:
      if (error.retryable) showTryAgain();
      else showCannotOnboard(error.kind); // duplicate, sanctions, jurisdiction, …
  }
}
```

| `kind` | Meaning | `retryable` |
| --- | --- | --- |
| `validation` | Input failed client-side checks; see `fieldErrors` and `secureFieldErrors` (SSN). Nothing was sent. | yes, after fixing |
| `duplicate` | The customer is already onboarded with your program. | no |
| `ageRequirement` | The customer doesn't meet the minimum age. | no |
| `jurisdiction` | The customer's state isn't supported. | no |
| `prohibited` | An identifier is on a prohibited list. | no |
| `sanctions` | The customer matched a sanctions list. | no |
| `identityVerificationFailed` | The identity couldn't be verified with the details given. | per the service (usually yes) |
| `invalidRequest` | The request was rejected as invalid: either by the service (CAAS codes `206-400-100-999`, and `270-400-203-668` for a name with characters other than letters, spaces, `'`, `-` and `.`) or as any HTTP 4xx other than 401, 403, 408 and 429 that carries no CAAS error code, such as a rejection by the secure-field proxy for a misconfigured vault. | per the service; no for a 4xx without a code |
| `server` | The service failed (5xx), or asked for the request to be tried later: timed out waiting for it (408) or rate-limited it (429). | yes |
| `network` | No response arrived: the customer is offline, the request was blocked, or it timed out. After a timeout the customer may already be onboarded; see below. | yes |
| `unauthorized` | The `Authorization` header was missing, expired or rejected (401/403). | no |
| `notReady` | `submit()` was called before the secure SSN field finished loading. Wait for `vaultStatus` to be `'ready'`, or enable your submit button only when `isValid` is `true`. | yes |
| `configuration` | Refused before sending: the `Authorization` header carries a partner access token instead of a Transient Auth Token (see [Authentication and headers](#authentication-and-headers)). Or the package has no onboarding configuration for the selected environment; published packages always include it, so contact Coinme if you see this. | no |
| `unknown` | Anything else, including an error thrown by your `getHeaders`, an error code the SDK doesn't know, and a phone verification response that reports success but has no `data`. | no |
| `codeIncorrect` | Phone verification: the code doesn't match, or it expired (Coinme currently reports an expired code this way). | yes |
| `codeExpired` | Phone verification: the code expired. | yes, with a new code |
| `tooManyAttempts` | Phone verification: too many failed checks, or the account's phone number has been changed too often. See `retryAfterSeconds` and `attemptsExhausted`. | per the service (usually yes, after `retryAfterSeconds`); never once `attemptsExhausted` |
| `smsNotSent` | Phone verification: Coinme's response didn't confirm the text was sent. | yes |
| `phoneNotSupported` | Phone verification: the number can't receive verification texts (not a mobile number, a carrier that isn't allowed, or recently used by another account). | no |
| `phoneAlreadyInUse` | Phone verification: the number belongs to another Coinme account. | no |
| `phoneNotVerified` | Not currently returned. It stays in the type so code that handles it still compiles. You don't need to handle it separately: treat it like any other failure. | no |

**A timeout doesn't mean nothing was sent.** When no response arrives within `timeoutMs` (60 seconds by default), the submit fails as `network`, but the request may still have reached Coinme and onboarded the customer. If the customer then retries with the same details and gets `duplicate`, the first attempt probably succeeded, even though you never received their `customerId`.

When the service's response includes a retry flag, `retryable` follows it. Otherwise it comes from the error-code table below. An `invalidRequest` without a CAAS error code is not retryable, and the drop-in form then shows its terminal message ("We're unable to complete your onboarding.") instead of "try again", unless you override it with `errorMessages`.

**CAAS error codes.** When Coinme returns an error code, it's on `error.errorCode`, and `ONBOARDING_ERROR_CODES` maps each known code to its `kind`:

| Code | `kind` |
| --- | --- |
| `206-400-100-001`, `270-400-203-603` | `duplicate` |
| `206-400-100-011` | `ageRequirement` |
| `206-400-100-012` | `jurisdiction` |
| `206-400-100-014` | `prohibited` |
| `206-400-100-020` | `identityVerificationFailed` |
| `206-400-100-031` to `206-400-100-036` | `sanctions` |
| `206-400-100-999`, `270-400-203-668` | `invalidRequest` |
| `206-500-100-999`, `270-500-203-604`, `270-500-203-999` | `server` |

`PHONE_VERIFICATION_ERROR_CODES` does the same for the phone verification calls:

| Code | Returned when | `kind` |
| --- | --- | --- |
| `203-400-115-001` | Sending or checking: too many failed checks | `tooManyAttempts` |
| `203-400-115-003` | Sending: the account's phone number has been changed too often | `tooManyAttempts` |
| `203-400-115-004` | Sending: another account used the number recently | `phoneNotSupported` |
| `203-400-115-006` | Sending: not a mobile number, or a phone type that isn't allowed | `phoneNotSupported` |
| `203-400-115-007` | Sending: the carrier isn't allowed | `phoneNotSupported` |
| `203-400-115-008` | Sending: the number belongs to another account | `phoneAlreadyInUse` |
| `203-400-115-009` | Checking: the code is wrong or expired | `codeIncorrect` |
| `203-400-115-010` | Checking: the code expired | `codeExpired` |

Earlier versions of this page listed `201-400-115-*`, `202-400-115-*` and `204-400-115-*` codes for phone verification. Coinme doesn't send those; the codes above are the ones it returns. If your error handling branches on the old codes, branch on `kind` instead, or on the codes above.

Coinme's phone verification endpoints can report a failure with HTTP 200. The SDK treats a 200 as success only when it carries no error (an `errorResponse`, or a top-level `errorData` or `errors` list) and has `data`; sending a code also needs Coinme to confirm the text went out, otherwise it fails as `smsNotSent`.

Other properties: `status` (the HTTP status, when the request completed), `cause` (the original error) and, for phone verification (mostly with `tooManyAttempts`), `retryAfterSeconds` (seconds until the customer can try again) and `attemptsExhausted` (`true` once every attempt is used, which also makes the error not retryable), when Coinme sends them.

- `error.message` never contains customer details, so it's safe to log.
- Don't show `error.cause` to customers. Branch on `kind` and show your own copy.

## Accessibility

The drop-in form and `OnboardingFormField` wire the basics:

- Each input and select has a `<label>`.
- Its inline error is linked with `aria-describedby`, and screen readers announce it when it appears (`aria-live="polite"`).
- `aria-invalid` is set once the field is touched and invalid.
- The submit-failure message has `role="alert"`.

The SSN input lives inside the vault's iframe, so its label can't be linked from the page. The SDK names it through the secure field's `ariaLabel`: the row's label when it's a string, otherwise `'Social Security Number'`. Its container is a `role="group"` named by the row's label. Pass your own name with the `ariaLabel` option:

```tsx
fieldProps={{ ssn: { ariaLabel: 'Número de Seguro Social' } }}
```

With the bare field components, labels and error wiring are yours.

## Server-side rendering

Importing the package on the server is safe: it has no browser side effects at load. The vault and the SSN field are created in the browser after mount, so:

- In the Next.js App Router, put the form in a client component (`'use client'`).
- On the server, the form renders without the SSN iframe, which appears after hydration.
- Add the [CSP](#content-security-policy) entries in your framework's header config.

With the core API, call `createOnboardingVault` from client-side code only (for example, inside `useEffect`). It rejects when there's no `window`.

## Verify your integration (sandbox)

1. Render the form with `environment="sandbox"` and a sandbox onboarding token.
2. Fill it in with a sandbox test identity from Coinme. Check that the submit button enables only once every field, including the SSN, is valid.
3. Submit, and check that `onSuccess` receives a `customerId`.
4. Reload the page, submit the same identity again, and check that `onError` receives a `duplicate` error.
5. In the browser's network tab, check that the submit goes to the sandbox host listed under [Content-Security-Policy](#content-security-policy).
6. With a fresh sandbox identity, onboard, then render `PhoneVerificationStep` with the `phoneNumber` from `onSuccess` and a token minted for the new `customerId`. Send a code, check that a wrong code shows `codeIncorrect`, then enter the right one and check that `onVerified` is called.

## Security

- **The raw SSN never touches your code.** It's typed into the vault's iframe and goes from there to the vault. Don't try to read it or ask for it in a plain input.
- **Keep Coinme credentials and your partner access token out of the browser.** The page only needs the Transient Auth Tokens, just in time for each request. Don't store them.
- **Don't log customer details.** `CoinmeOnboardingError` messages are safe to log. Form values (from `values` or your own inputs) are personal data.
- **No verified phone, no completed onboarding.** Coinme doesn't consider KYC complete until the customer confirms the code texted to the number they onboarded with. Never treat a customer without a verified phone as onboarded or KYC-complete, and send an unverified customer who signs back in to verification first.
- **One phone number throughout.** Verify the number the customer onboarded with: pass `phoneNumber` from the onboarding result, or the copy you stored, and never accept a different number at verification.
- **Coinme is the authority.** Client-side checks and a verified screen are UX only. Confirm the customer's status on your backend before granting access.
- **Limit your CSP** to the documented [vault provider and Coinme hosts](#content-security-policy).

## Commonly asked questions

### What is the onboarding token, and how do I get one?

The onboarding token is a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) with the `onboarding` scope: a short-lived credential that authorizes one onboarding submit. Your backend mints it in two calls, both described on that page: it exchanges your API client ID and client secret for a partner access token, then calls `POST /services/browserAuth` with `scope=onboarding`. The customer does not exist at Coinme yet, so pass your identifier for the customer's sign-up session as `customerId`. Your Coinme credentials and the partner access token never belong in the browser.

You own getting the token to the page. How you do it is up to you, but two common shapes are:

- **Fetch it inside `getHeaders`.** Write a `getHeaders` that calls your backend, which mints the token and returns it, and return `{ Authorization: 'Bearer <token>' }`. The SDK calls `getHeaders` just before each submit, so every submit gets a fresh token.
- **Render it into the page.** Mint the token when you render the onboarding view, hand it to the page (for example through the page's initial data), and have `getHeaders` return it.

The SDK does not fetch tokens, refresh them or store them; it sends whatever `getHeaders` returns. Don't keep the token in `localStorage`, `sessionStorage` or cookies.

Phone verification needs a second token, minted the same way with `scope=onboarding` but for the Coinme `customerId` that onboarding returned rather than your sign-up session. The sign-up session token does not work for the verification calls. See [Authentication and headers](#authentication-and-headers).

### How do I associate an onboarding with my own backend session?

The submit goes from the customer's browser to Coinme, so your backend does not see it; the new Coinme `customerId` reaches you through your frontend, from `onSuccess`. The customer has no account with you yet, because this one call onboards them and runs KYC, so there is no signed-in session at that moment. Your backend associates the two by keeping its own sign-up session across the two requests it does see: the one that mints the onboarding token, and the one that receives the `customerId`.

**What Coinme provides and what you build**

| Piece | Provided by |
| --- | --- |
| The onboarding form, the secure SSN field and the submit to Coinme | Coinme (this SDK) |
| The new Coinme `customerId`, passed to `onSuccess` | Coinme |
| The phone verification step, which texts the code and checks it | Coinme (this SDK) |
| Minting the onboarding token (`POST /services/browserAuth` with `scope=onboarding`) | Coinme API, called by your backend |
| Minting the phone verification token (the same call, for the new `customerId`) | Coinme API, called by your backend |
| CaaS API calls, such as fetching a customer's wallets | Coinme API, called by your backend |
| Your sign-up session and its ID | You |
| Carrying that session between your page and your backend, for example with a session cookie | You |
| A backend endpoint that mints the onboarding token and returns it to your page | You |
| The `getHeaders` function that calls that endpoint | You |
| A backend endpoint that receives the `customerId` and `phoneNumber` from `onSuccess` and links them to your user | You |
| A backend endpoint that mints the phone verification token for that `customerId`, and a record of whether the phone is verified | You |

Coinme does not create or manage your sessions or cookies. There is no Coinme call that returns which sign-up session a `customerId` was onboarded from.

**Two identifiers are involved, and they are different values.** When your backend mints the onboarding token, it passes its own sign-up session ID in the `customerId` parameter, because the customer does not exist at Coinme yet. When onboarding succeeds, `onSuccess` returns a new value: the Coinme `customerId`. Your backend stores the Coinme `customerId` against its sign-up session ID.

**How the pieces fit together**

1. The customer starts sign-up. Your backend creates a sign-up session and gives the browser a way to carry it, typically a session cookie.
2. Just before the submit, the SDK calls your `getHeaders`. It asks your backend for a token; your backend reads the sign-up session, mints the onboarding token with the sign-up session ID as `customerId`, and returns the token.
3. The SDK submits the onboarding to Coinme from the browser, with the token.
4. Coinme returns the new `customerId` to `onSuccess`.
5. Your `onSuccess` sends the `customerId` and `phoneNumber` to your backend on the same sign-up session. Your backend checks the `customerId` and links both to your user.
6. Your page moves on to [phone verification](#phone-verification). Its `getHeaders` asks your backend for a token, which your backend mints for the linked `customerId`.
7. Once the code checks out, your backend records that the customer's phone is verified. Only then is the customer onboarded.

**Checks we recommend before linking a `customerId`**

Because `onSuccess` runs in the browser, the `customerId` your backend receives is a value reported by the client. A CaaS API call your backend makes with it confirms that it is valid and belongs to your partner account, and rejects one that is not; it does not confirm which sign-up session it came from. We recommend your backend:

1. accepts the `customerId` only on the sign-up session that minted the onboarding token, identifying that session from what your backend issued, never from a value in the request body;
2. links one `customerId` per sign-up session, and each `customerId` to one sign-up session;
3. confirms the `customerId` with a CaaS API call made with your partner credentials.

If the request from `onSuccess` to your backend fails, retry it with the same `customerId` rather than resubmitting the form: the customer is already onboarded at Coinme, and a second submit returns `duplicate`.

> **We've provided an example implementation.**
>
> [Example: linking onboarding to your backend session](https://platformdocs.coinme.com/docs/onboarding-sdk-session-example.md) builds the onboarding pieces in the "You" rows above; the phone verification token is minted by the same function, for the linked `customerId`. It is one possible implementation, not a Coinme requirement.

### Why does onboarding happen from the browser at all?

So that the Social Security Number never reaches your code, your logs or your servers. The SSN is typed into the vault's secure field and travels from there to Coinme, which is only possible if the request starts in the browser. The trade-off is that your backend does not observe the onboarding call, so the `customerId` reaches it through your frontend.

### Can I onboard from my backend instead?

The onboarding endpoint itself is described in Coinme's [customer onboarding guide](https://docs.coinme.com/docs/customer-onboarding-overview), and nothing stops a server-to-server integration. It means collecting and handling the SSN yourself.

## Troubleshooting

**`401` on install.** The registry token is missing or expired. Re-export `COINME_REGISTRY_TOKEN` and reinstall. See [Install](#install).

**`vaultStatus` is `'error'` with `kind: 'network'`.** The secure field script didn't load. Check the network and your [CSP](#content-security-policy). Ad blockers can also block `js.verygoodvault.com`.

**Submits fail with `notReady`.** The submit ran before the secure SSN field finished loading, typically from a submit button that isn't disabled while `isValid` is `false`. Gate the button on `isValid` (it's `false` until the vault is ready), or wait for `vaultStatus` to be `'ready'`.

**`vaultStatus` is `'error'` with `kind: 'configuration'`.** The package has no onboarding configuration for the selected environment. Published packages always include it, so contact Coinme.

**The SSN field doesn't appear.** The vault is still loading or failed to load (check `vaultStatus`), or the vault's iframe is blocked by your CSP (`frame-src`) or an ad blocker.

**The submit button never enables.** It needs every required field valid **and** a valid SSN. With a custom layout, make sure every required field is placed. Read `fieldErrors` and `ssnState` from `useCustomerOnboarding` to see what's missing.

**Submits or phone verification fail with `configuration` and nothing is sent.** The `Authorization` header carries a partner access token. Your backend is returning the partner access token to the browser; mint a Transient Auth Token from `POST /services/browserAuth` (with `scope=onboarding`) instead and return only its `access_token`. See [Authentication and headers](#authentication-and-headers).

**Submits fail with `unauthorized`.** `getHeaders` returned no `Authorization` header, or the token was expired or rejected. Fetch a fresh token for each submit.

**Phone verification fails with `unauthorized`.** The token was minted for the sign-up session instead of the new `customerId`, or it expired. Mint a fresh one for the `customerId` from `onSuccess` inside the step's `getHeaders`.

**A correct code is rejected as `codeIncorrect`.** The code had probably expired: a code works for about a minute, and Coinme currently reports an expired code as `codeIncorrect`. Send a new one.

**Names with digits or symbols are rejected as `invalidRequest`.** The onboarding service accepts only letters, spaces, `'`, `-` and `.` in names, and returns error code `270-400-203-668` for anything else. Ask the customer to type their name without other characters.

**Submits fail with `unknown` right away.** Check that `getHeaders` resolves. An error thrown there is reported as the submit error, with the original on `error.cause`.

**Accented names are rejected.** The onboarding service accepts printable ASCII only, so the SDK reports `nonAscii` for those fields. Ask the customer to type the name without accents.

**Doubled SSN fields in development.** If you create the SSN field yourself with the core API in React, create it in an effect and delete it in the effect's cleanup, so StrictMode's double run doesn't mount two iframes. The SDK's components already do this.
