---
title: "Example: linking onboarding to your backend session"
url: "https://platformdocs.coinme.com/#/docs/onboarding-sdk-session-example"
markdown: "https://platformdocs.coinme.com/docs/onboarding-sdk-session-example.md"
summary: "A complete example of the pieces you build to link an onboarded customer to your backend's sign-up session: the token endpoint, the completion endpoint with the recommended checks, the frontend that calls them, and the database table."
surface: "caas"
platform: "web"
package: "@coinme-security/onboarding-sdk-react"
version: "1.7.1"
peerDependencies: {"react":">=18","react-dom":">=18"}
updated: "2026-11-02"
---

# Example: linking onboarding to your backend session

A complete example of the pieces you build to link an onboarded customer to your backend's sign-up session: the token endpoint, the completion endpoint with the recommended checks, the frontend that calls them, and the database table.

> **This is one way to do it, not the only way.**
>
> It shows one way you can build your integration. Coinme does not require this stack, these endpoint names, this cookie configuration or this database schema. Everything not marked **Coinme** is code you write and own, and you can build it differently.

For the concepts behind this example, see [How do I associate an onboarding with my own backend session?](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md#how-do-i-associate-an-onboarding-with-my-own-backend-session) in the Onboarding SDK guide.

## What this example assumes

- A React frontend and a Node.js backend served from the **same origin**. For separate origins, see [Different origins](#different-origins).
- Express 5 with `express-session`, and a production session store such as Redis.
- PostgreSQL.

Any language, framework, session library or database works the same way.

## Who provides what

| Piece | Provided by | In this example |
| --- | --- | --- |
| `CustomerOnboardingForm`, the secure SSN field, the submit to Coinme | **Coinme** (Onboarding SDK) | Used as documented |
| The new Coinme `customerId`, passed to `onSuccess` | **Coinme** | Read in `onSuccess` |
| `POST /services/authorize` and `POST /services/browserAuth` with `scope=onboarding`, which mint the onboarding token and, after linking, the phone verification token | **Coinme** API | Called inside `mintTransientAuthToken` |
| CaaS API calls, such as fetching a customer's wallets | **Coinme** API | Called inside `customerIdIsValid` |
| The sign-up session and its ID | You | `express-session`, cookie `signup_sid` |
| `POST /your-api/onboarding/token`: returns an onboarding token to the page | You | [Backend](#backend) |
| `POST /your-api/onboarding/complete`: receives the `customerId` and links it | You | [Backend](#backend) |
| `POST /your-api/phone-verification/token`: mints the phone verification token for the `customerId` linked to this session; never takes a `customerId` from the page | You | [The phone verification token](#the-phone-verification-token) |
| The table that links each `customerId` to a sign-up session | You | [Database](#database) |
| `getHeaders` and `onSuccess` | You | [Frontend](#frontend) |

## The flow

1. The page calls `getHeaders` (through the SDK, just before the submit), which calls `POST /your-api/onboarding/token`. The browser sends the `signup_sid` cookie.
2. The backend reads the sign-up session ID from the session, creating one if needed, and mints an onboarding token with it as `customerId` by calling `mintTransientAuthToken`. **(Coinme API)**
3. The SDK submits the onboarding to Coinme with the token. **(Coinme)** Your backend does not see this request.
4. Coinme returns the new `customerId` to `onSuccess`. **(Coinme)**
5. `onSuccess` calls `POST /your-api/onboarding/complete` with the `customerId`. The browser sends the same `signup_sid` cookie.
6. The backend checks the `customerId`, confirms it with a CaaS API call **(Coinme API)**, links it to the sign-up session, and responds.

Phone verification follows. It uses a second token, minted for the linked `customerId`: see [The phone verification token](#the-phone-verification-token).

## What comes from Coinme's documentation, and what this example adds

From the [Onboarding SDK guide](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md) and [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md):

- Mint the onboarding token on your backend. Your Coinme credentials and the partner access token never go to the browser.
- When minting the onboarding token, pass your identifier for the customer's sign-up session as `customerId`. The onboarding token does not work for phone verification.
- Phone verification needs a second token, minted for the `customerId` that onboarding returned, and that token is the only thing that ties the verification calls to the customer. Your backend reads the `customerId` from its own linked record, never from the request.
- Fetch the token just in time. Don't keep it in `localStorage`, `sessionStorage` or cookies.
- `onSuccess` is not awaited by the SDK; handle its promise yourself.
- A CaaS API call with a `customerId` rejects one that is not valid for your partner account.
- After a submit that times out or succeeds, a second submit with the same details returns `duplicate`.
- Don't log customer details.

Coinme's recommended checks before linking a `customerId`: accept it only on the sign-up session that minted the token; link one `customerId` per sign-up session and each `customerId` to one session; confirm it with a CaaS API call.

Design choices of **this example** (not Coinme requirements):

- The sign-up session is carried in an `HttpOnly`, `Secure`, `SameSite=Lax` cookie.
- Both endpoints require `Content-Type: application/json`, so a plain cross-site form post can't call them.
- The one-to-one links are enforced with unique constraints in the database.
- The completion endpoint is safe to retry with the same `customerId`.
- The session ID is regenerated after linking.
- An attempt to link a `customerId` already linked to another session is recorded for review.

## Database

```
-- You own this table.
CREATE TABLE coinme_customer_links (
  signup_id   TEXT PRIMARY KEY,         -- your sign-up session ID
  customer_id TEXT NOT NULL UNIQUE,     -- the Coinme customerId from onSuccess
  linked_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
```

## Backend

```typescript
import crypto from 'node:crypto';
import express from 'express';
import session from 'express-session';

declare module 'express-session' {
  interface SessionData {
    signupId?: string;
    linkedCustomerId?: string;
  }
}

const app = express();
app.set('trust proxy', 1); // When TLS terminates at a proxy or load balancer; otherwise Secure cookies are not set.
app.use(express.json());
app.use(
  session({
    name: 'signup_sid',
    secret: process.env.SESSION_SECRET!, // A long random value from your secret store.
    store: sessionStore, // A production session store, for example connect-redis.
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60 * 60 * 1000 },
  })
);

const requireJson: express.RequestHandler = (req, res, next) =>
  req.is('application/json') ? next() : res.sendStatus(415);

// Called from getHeaders, just before each submit.
app.post('/your-api/onboarding/token', requireJson, async (req, res) => {
  if (!req.session.signupId) req.session.signupId = crypto.randomUUID();
  // mintTransientAuthToken is the backend module in step 3 of the Onboarding SDK skill.
  const { token } = await mintTransientAuthToken(req.session.signupId, 'onboarding');
  res.set('Cache-Control', 'no-store').json({ token });
});

// Called from onSuccess with the Coinme customerId.
app.post('/your-api/onboarding/complete', requireJson, async (req, res, next) => {
  const signupId = req.session.signupId;
  const customerId = req.body?.customerId;

  if (!signupId) return res.sendStatus(401);
  if (typeof customerId !== 'string' || customerId.length === 0) return res.sendStatus(400);

  // Retry of a link that already succeeded on this session.
  if (req.session.linkedCustomerId) {
    return res.sendStatus(req.session.linkedCustomerId === customerId ? 204 : 409);
  }

  if (!(await customerIdIsValid(customerId))) return res.sendStatus(400);

  try {
    await db.query(
      'INSERT INTO coinme_customer_links (signup_id, customer_id) VALUES ($1, $2)',
      [signupId, customerId]
    );
  } catch (error) {
    if (isUniqueViolation(error)) {
      await flagForReview({ signupId, customerId });
      return res.sendStatus(409);
    }
    throw error;
  }

  req.session.regenerate((error) => {
    if (error) return next(error);
    req.session.signupId = signupId;
    req.session.linkedCustomerId = customerId;
    res.sendStatus(204);
  });
});
```

The functions this example leaves to you:

| Function | What it does | Coinme reference |
| --- | --- | --- |
| `mintTransientAuthToken(signupId, 'onboarding')` | Gets a partner access token from `POST /services/authorize`, then calls `POST /services/browserAuth` with `customerId` set to `signupId` and `scope=onboarding`, and returns the token. Use the module as written in the skill. | [Onboarding SDK skill, step 3](https://platformdocs.coinme.com/skills/coinme-onboarding-react/SKILL.md); [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) |
| `customerIdIsValid(customerId)` | Makes a CaaS API call with your partner credentials, such as fetching the customer's wallets, and returns `false` if Coinme rejects the `customerId`. | [Custody API client](https://platformdocs.coinme.com/docs/caas-custody-api-client.md) |
| `isUniqueViolation(error)` | Returns `true` for your database's unique-constraint error (PostgreSQL code `23505`). | None |
| `flagForReview(details)` | Records the attempt for your team. It does not link the `customerId`. | None |

## The phone verification token

Phone verification (`PhoneVerificationStep` or `usePhoneVerification`) needs its own token, minted for the `customerId` this example just linked. The route takes no ID from the request: the `customerId` comes from the server-side session and the link above. For a returning customer on a new session, look it up in `coinme_customer_links` (or your own user record) through your own sign-in instead.

```typescript
// Called from the verification step's getHeaders, before every send and every check.
app.post('/your-api/phone-verification/token', requireJson, async (req, res) => {
  const customerId = req.session.linkedCustomerId; // never req.body or the query string
  if (!customerId) return res.sendStatus(409); // onboarding hasn't been linked on this session
  const { token } = await mintTransientAuthToken(customerId, 'onboarding');
  res.set('Cache-Control', 'no-store').json({ token });
});
```

The page's verification `getHeaders` (`getVerificationHeaders` in [Frontend](#frontend)) calls this route the way `getHeaders` calls the onboarding one. See [Example: both tokens, end to end](https://platformdocs.coinme.com/docs/transient-auth-token.md#example-both-tokens-end-to-end) for the whole sequence.

## Frontend

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

// You build this. The SDK calls it just before each submit.
const getHeaders = async () => {
  const res = await fetch('/your-api/onboarding/token', {
    method: 'POST',
    credentials: 'same-origin', // Sends the signup_sid cookie.
    headers: { 'Content-Type': 'application/json' },
    body: '{}',
  });
  if (!res.ok) throw new Error(`Token request failed: ${res.status}`);
  const { token } = await res.json();
  return { Authorization: `Bearer ${token}` };
};

// You build this. PhoneVerificationStep's getHeaders, called before every send and every
// check. It sends no customerId: the route mints for the one linked to this session.
const getVerificationHeaders = async () => {
  const res = await fetch('/your-api/phone-verification/token', {
    method: 'POST',
    credentials: 'same-origin', // Sends the signup_sid cookie.
    headers: { 'Content-Type': 'application/json' },
    body: '{}',
  });
  if (!res.ok) throw new Error(`Token request failed: ${res.status}`);
  const { token } = await res.json();
  return { Authorization: `Bearer ${token}` };
};

// You build this. Sends the Coinme customerId to your backend on the same session.
const linkCustomer = async (customerId: string) => {
  const res = await fetch('/your-api/onboarding/complete', {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ customerId }),
  });
  // fetch rejects only on network failure, so check the status.
  if (!res.ok) throw new Error(`Link request failed: ${res.status}`);
};

export const Onboarding = () => (
  <CustomerOnboardingForm
    environment="sandbox"
    getHeaders={getHeaders}
    onSuccess={({ customerId }) => {
      // The SDK does not await onSuccess, so handle the promise here.
      linkCustomer(customerId)
        .then(startPhoneVerification)
        .catch(() => showRetryLink(() => linkCustomer(customerId)));
    }}
    onError={(error) => reportOnboardingFailure(error.kind)}
  />
);
```

`startPhoneVerification`, `reportOnboardingFailure` and `showRetryLink` are your own UI code. `startPhoneVerification` shows `PhoneVerificationStep` with `getHeaders={getVerificationHeaders}` and the `phoneNumber` from the onboarding result. `showRetryLink` retries `linkCustomer` with the same `customerId`; it does not resubmit the form.

## Different origins

If your frontend and backend are on different origins, this example would change as follows:

- `credentials: 'include'` in both `fetch` calls.
- The session cookie set with `sameSite: 'none'` and `secure: true`.
- CORS on the backend allowing credentials from the frontend's exact origin, never `*`.
- Both endpoints rejecting requests whose `Origin` header is not the frontend's origin.

## Checking the example works

| Check | Expected |
| --- | --- |
| Repeated calls to `/your-api/onboarding/token` in one session | Each token is minted with the same sign-up session ID |
| `/your-api/onboarding/complete` without the cookie | `401` |
| A `customerId` the CaaS call rejects | `400`, nothing linked |
| The same `customerId` twice on one session | `204` both times, one row |
| A different `customerId` on an already-linked session | `409` |
| A `customerId` already linked to another session | `409`, attempt recorded for review |
| `/your-api/phone-verification/token` on a session with no linked customer | `409` |
| `/your-api/phone-verification/token` with a `customerId` in the body or query string | The `customerId` is ignored; the token is minted for the linked one |
| A request without `Content-Type: application/json` | `415` |
| The session cookie after a successful link | A new session ID |
| Application logs | No onboarding tokens or customer details |
