---
name: coinme-vault-js
description: "Add card capture to a web app with the Coinme Vault SDK: install from the private registry, mount secure fields, style and validate them, and submit the payment method to Coinme with the transient auth token. Use when asked to collect card details, add a payment method or integrate Coinme's vault in a website or web app, in plain JavaScript, React, Vue or an SSR framework."
metadata:
  surface: "caas"
  package: "@coinme-security/vault-sdk-js"
  version: "1.3.0"
---

# Coinme Vault SDK in JavaScript

## When to use this skill

The human wants a web app to collect a customer's card details and add them as a payment method at Coinme without the card data touching the app's code or servers. It is not for the Coinme Widget, which handles payment inside its own frame.

## Which integration this is

This skill is for the **Coinme-as-a-Service (CaaS) integration**: the partner keeps its own users and its own screens, and Coinme performs regulated services for them (onboarding and KYC, card vaulting, risk signals, transactions). The users are the partner's customers, not Coinme users. There is no Coinme Widget here, so no `rampId`, `partnerKey`, widget URL or embed allowlist. If the human wants to embed the Coinme Widget instead, this is the wrong skill: read [Two ways to build on Coinme](https://platformdocs.coinme.com/agents/surfaces.md) and pick a Widget skill.

## What you will produce

A web app with the vault's secure fields in the payment form, validation wired to the submit control, and a submit that sends the payment method to Coinme with a fresh transient auth token in the Authorization header, a Risk SDK session id fetched right before the submit, and the device fingerprint the Coinme SDKs share, which the SDK adds.

## Before you start: ask the human for these

The documentation does not contain them and you cannot derive them. Stop and ask, then continue. Never write a real value into a tracked file; keep each where the row says.

| Value | What it is | Where it goes |
| --- | --- | --- |
| `registry token` | Read-only token for the private registry that serves the Coinme SDKs. The install steps below read it from an environment variable they name; set that variable. | An environment variable or a gitignored registry config read at install time; CI reads it from a secret. Never in a committed file. |
| `API client ID and client secret` | The credentials the human's backend exchanges at `POST /services/authorize` for a partner access token, which mints the Transient Auth Token. The client ID is not the partner ID, and not the Risk SDK's `clientId`. | The backend's secret store or environment variables; never in client code or a committed file. |
| `production base URL` | The base URL for `/services/authorize` and `/services/browserAuth` in production; sandbox is `https://caas-staging.coinme.com`. Coinme provides it at onboarding. | Backend configuration, one value per environment. |
| `customerId, paymentProviderId and the Risk SDK webSessionId` | The customer the payment method belongs to, the payment provider, and the Risk SDK session the submit is tied to. | Values from the human's app state at submit time; the Risk SDK must already be integrated to supply the session id, fetched right before the submit. On the web and React Native the Coinme SDKs share the device fingerprint; on iOS and Android the app passes the same value it gives the Risk SDK. |

## Rules for this skill

- Follow the steps in order and keep the code as written; change only identifiers the human gives you and the places marked as yours.
- Do not invent configuration fields, event names or API methods. What exists is what this skill shows plus what the installed package declares in its type definitions; check those before adding anything.
- Samples show the environment (such as `'sandbox'`, `'test'` or a staging base URL) as a literal so each stays self-contained. In the project, read it from the runtime configuration the human's build uses (for Vite, `VITE_*` variables in a gitignored `.env.local` with a committed `.env.example`), with a value per environment.
- This integration has no `rampId`, `partnerKey`, widget URL or embed allowlist. Do not ask for them or add them; they belong to the Widget skills.
- The Transient Auth Token is minted only in the human's backend, never in the browser or the app: write that backend route as the backend step below shows, reading the API client ID, client secret and base URL from the server's configuration. Never send the partner access token, the client ID or the client secret to the client.
- Never pass the partner access token to the SDK, not in sandbox, not in a prototype and not as a fallback when minting fails; the `Authorization` header carries only the Transient Auth Token from `POST /services/browserAuth`.
- When a step needs a value you do not have, ask; do not substitute a placeholder that could ship.
- Read the linked pages when a step is unclear; they are the source this skill was generated from.

## Read first

Every payment-method submit carries a Transient Auth Token as `Authorization: Bearer <token>`, minted by the human's backend for the customer (the backend step below). The client fetches one when the add-card screen opens, keeps it in memory, and on a `server` error with status 401 or 403 fetches a fresh one and retries once. Never store it on the device or in the browser, and never put the backend's credentials in the client. Never pass the partner access token to the SDK; the `Authorization` header carries only the Transient Auth Token from `POST /services/browserAuth`.

From 1.2.3 a submit whose `Authorization` header carries a partner access token is refused before sending with a `configuration` `CoinmeVaultError`: fix the backend route that returned it, never retry. From 1.2.2, a `network` error with `timedOut: true` means the outcome is unknown, since the request may still have completed: re-list the customer's payment methods before offering a retry, or the same card can be added twice.

The submit also needs a Risk SDK session id, fetched right before the submit because a session tag lives 30 minutes. From Vault SDK 1.3.0, with Risk SDK for Web 1.2.0 or React Native 1.1.0 or later, the SDK adds the device fingerprint the Coinme SDKs share; otherwise pass `X-Device-Fingerprint` with the same value the Risk SDK gets. If the Risk SDK is not integrated yet, say so and offer the Risk skill first.

## Backend: mint the Transient Auth Token

Before the client can submit a card, the human's backend needs a route that returns `mintTransientAuthToken(customerId)` for the signed-in customer: a Transient Auth Token with the default `payment-methods` scope, bound to the customer the card will belong to. The client calls it when the add-card screen opens.

#### Get a partner access token

Call this from your backend only. It authenticates with HTTP Basic: your API client ID and client secret, joined by a colon and base64-encoded.

```bash
curl -X POST "https://caas-staging.coinme.com/services/authorize" \
  -H "Authorization: Basic $(printf '%s:%s' "$CLIENT_ID" "$CLIENT_SECRET" | base64)"
```

```json
{
  "access_token": "eyJ…",
  "token_type": "Bearer",
  "expires_in": "1800"
}
```

The lifetime differs by environment: 30 minutes (`1800`) in sandbox and 60 minutes (`3600`) in production. Read `expires_in` (seconds, sent as a string) rather than hard-coding it, keep the token in your backend and reuse it until shortly before it expires.

> **Never send the partner access token to a browser or an app.**
>
> It authorizes every CaaS endpoint on your behalf. Only the Transient Auth Token from the next step goes to the client.

#### Mint the Transient Auth Token

Also from your backend only, authenticated with the partner access token from step 1.

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

| Parameter | In | Required | Notes |
| --- | --- | --- | --- |
| `Authorization` | header | yes | `Bearer <partner access token>`. |
| `customerId` | query | yes | For card capture, the Coinme customer the card will belong to. For onboarding, your identifier for the customer's sign-up session. For phone verification, the Coinme `customerId` onboarding returned, read from your backend's own record, never from the client. For attestations, the Coinme `customerId` of the onboarded customer. The token is bound to this value. |
| `scope` | query | no | `payment-methods` (the default) for the Vault SDK's payment-method submit, `onboarding` for the Onboarding SDK's onboarding submit and phone verification calls (sandbox only for now: Coinme's production environment does not issue tokens with this scope yet), or `attestations` for the Compliance SDK's attestation store, which is not available in the beta at this time. |

For onboarding, pass `scope=onboarding` and the sign-up session's identifier:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${SIGNUP_SESSION_ID}&scope=onboarding" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

For phone verification, pass `scope=onboarding` and the `customerId` onboarding returned. Mint a fresh one for each verification call (sending the code, checking it), since a customer waiting for the text can easily pass the 10 minutes:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}&scope=onboarding" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

For the Compliance SDK's attestations, pass `scope=attestations` and the onboarded customer's `customerId`. Attestations are not available in the Compliance SDK beta at this time, and Coinme does not issue tokens with this scope:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}&scope=attestations" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

```json
{
  "access_token": "eyJ…",
  "token_type": "Bearer",
  "expires_in": "600"
}
```

Mint a fresh token each time the customer reaches the add-card, onboarding or consent screen. Tokens last 10 minutes and are cheap to mint; never cache one or reuse it across sessions or customers.

> **Check the body, not just the status.**
>
> A mint that reaches the service but fails validation returns HTTP `200` with an error envelope in the body (for example `{"status":400}`) and no `access_token`. Treat any response without an `access_token` as a failure.

#### In your backend

The two calls as a Node.js module. The route that hands the token to your page or app calls `mintTransientAuthToken`: for card capture, for a signed-in customer only; for onboarding, for the customer's sign-up session, because the customer is not signed in yet; for phone verification, for the `customerId` your backend saved against that customer's record when onboarding succeeded, read from your own record and never from the request; for attestations, for the signed-in customer only.

```typescript
const BASE_URL = process.env.COINME_BASE_URL!; // https://caas-staging.coinme.com in sandbox

let partnerToken: { value: string; expiresAt: number } | undefined;

const getPartnerAccessToken = async (): Promise<string> => {
  if (partnerToken && partnerToken.expiresAt > Date.now() + 60_000) {
    return partnerToken.value;
  }
  const credentials = Buffer.from(
    `${process.env.COINME_CLIENT_ID}:${process.env.COINME_CLIENT_SECRET}`
  ).toString('base64');
  const response = await fetch(`${BASE_URL}/services/authorize`, {
    method: 'POST',
    headers: { Authorization: `Basic ${credentials}` },
  });
  const body = await response.json();
  if (!response.ok || !body.access_token) {
    throw new Error(`Coinme authorize failed (${response.status})`);
  }
  partnerToken = {
    value: body.access_token,
    expiresAt: Date.now() + Number(body.expires_in) * 1000,
  };
  return partnerToken.value;
};

export const mintTransientAuthToken = async (
  customerId: string, // or, for onboarding, the sign-up session's identifier
  scope: 'payment-methods' | 'onboarding' | 'attestations' = 'payment-methods'
): Promise<{ token: string; expiresIn: number }> => {
  const url = new URL(`${BASE_URL}/services/browserAuth`);
  url.searchParams.set('customerId', customerId);
  url.searchParams.set('scope', scope);
  const response = await fetch(url, {
    method: 'POST',
    headers: { Authorization: `Bearer ${await getPartnerAccessToken()}` },
  });
  const body = await response.json();
  // A failed mint can arrive as HTTP 200 with an error envelope and no token.
  if (!response.ok || !body.access_token) {
    throw new Error(`Coinme browserAuth failed (${body.status ?? response.status})`);
  }
  return { token: body.access_token, expiresIn: Number(body.expires_in) };
};
```

The token lasts 10 minutes. When a submit fails because it expired, fetch a fresh one from the backend and retry once; [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) has the error tables.

## Procedure

Follow the guide below in order. It is the integration guide for this platform as published, so the section names are the guide's own.

# Coinme Vault SDK for Javascript

`@coinme-security/vault-sdk-js` is a typed, framework-agnostic JavaScript wrapper that lets

any web app capture debit card data - card number, expiry, CVC, billing address, and other

sensitive values - without those values ever touching your JavaScript, your DOM, your logs, or

your backend. You render containers for the secure fields; the SDK mounts VGS-hosted inputs

into them; your code receives only a confirmation response.

The SDK works with any web stack - vanilla JS, React, Vue, Angular, Svelte, or any

SSR framework - because the secure fields are cross-origin iframes, not framework components.

You wire them up in a handful of calls.

## How it works

The SDK wraps [VGS Collect.js](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/index),

a browser library from Very Good Security that handles the mechanics of secure card capture.

VGS acts as a secure proxy: each field the SDK creates is a cross-origin iframe served by VGS,

not an input element in your page. Values typed by the user are captured inside those iframes

and submitted directly to Coinme's vault - they never enter your JavaScript, your DOM tree, or

any network request your code can inspect.

The SDK pre-binds Coinme's VGS vault configuration. You never supply a vault ID, ingress

route, or submit path - just pick an `environment` (`sandbox` or `live`) and the SDK resolves everything else.

### The iframe model - what it means for your integration

Because each secure field is an iframe served from VGS's domain, a few things work differently from a regular `<input>`:

- **Your page CSS cannot reach inside the fields.** Styling is applied through a `css` option

you pass at field creation time - see [Styling](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#styling).
- **You can't read the field values back.** The fields are intentionally opaque. You get state

metadata - `isValid`, `isDirty`, `last4`, `cardBrand` - but never the raw value.
- **Field containers must exist in the DOM before you create fields.** The factory calls (`vault.createCardNumberField`, etc.) mount iframes into the container elements you pass. If a container doesn't exist yet, the field won't render.
- **Vault creation is browser-only.** `createCoinmeVault` loads VGS Collect.js from the VGS CDN and needs a `window`. Calling it during server-side rendering will reject - see

[SSR frameworks](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#ssr-frameworks-next-js-nuxt-sveltekit).

### What VGS Collect.js version is used?

VGS Collect.js is loaded at runtime from the VGS CDN (for PCI script attestation). The SDK pins to version **4.0.1** - exposed as the `VGS_COLLECT_VERSION` export if you need to reference it. The SDK also ships full TypeScript typings for the VGS Collect surface, which VGS itself does not provide.

## Prerequisites

Before you install the SDK:

| Requirement | Details |
| --- | --- |
| Browser target | Evergreen Chrome, Firefox, Edge; Safari 10+. Vault creation is browser-only. |
| Node (build-time) | Any version that supports your build tool. Importing the package in Node is side-effect safe; creating a vault there is not. |
| `CLOUDSMITH_TEAM_TOKEN` | Coinme Cloudsmith entitlement token - see below. |
| Content-Security-Policy | If your site sets a CSP, you must add VGS domains before the SDK will work - see [CSP](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#content-security-policy). |

### Obtaining the `CLOUDSMITH_TEAM_TOKEN`

The SDK is published to Coinme's private npm registry. Access is authenticated by a Cloudsmith entitlement token. This token is used only at npm install time. To obtain one, ask your Coinme integration contact.

### Content-Security-Policy

If your site sets a `Content-Security-Policy`, the secure fields (iframes) and the VGS Collect.js script load from VGS's domains. Add these entries before you begin:

```
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
```

Also add your Coinme ingress host under `connect-src`. (`js3.verygoodvault.com` is VGS's fallback CDN; `vgs-collect-keeper` receives VGS product-interaction analytics.) If either domain is missing, the fields will fail to render or `createCoinmeVault` will reject with a network error.

## Installation

### Step 1 - Configure the private registry

`.npmrc` (npm or Yarn Classic):

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

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

```yaml
nodeLinker: node-modules

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

Commit the config file. Keep the token itself out of source control - supply it as an

environment variable.

### Step 2 - Install

```bash
export CLOUDSMITH_TEAM_TOKEN=<your-token>
yarn add @coinme-security/vault-sdk-js
```

There is no peer dependency to install separately. The `@vgs/collect-js` loader ships as a regular dependency of the SDK.

## Quickstart

Here is the minimum integration for vanilla JS - container elements, vault creation, field

mounting, gated submit, and error handling. If you're using React, Vue, or an SSR framework,

see [Framework setup](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#framework-setup) below.

```markup
<div id="pan"></div>
<div id="expiry"></div>
<div id="cvc"></div>
<button id="submit" disabled>Submit</button>
```

```typescript
import {
  CoinmeVaultError,
  createCoinmeVault,
} from '@coinme-security/vault-sdk-js';

// createCoinmeVault is async - it loads VGS Collect.js from the VGS CDN.
const vault = await createCoinmeVault({ environment: 'sandbox' });

// Mount secure fields into the container elements.
// These calls return raw VGS field instances.
vault.createCardNumberField('#pan', { placeholder: 'Card number' });
vault.createExpiryField('#expiry', { placeholder: 'MM / YYYY' });
vault.createCvcField('#cvc', { placeholder: 'CVC' });

// Subscribe to form state changes to gate the submit button.
const button = document.querySelector<HTMLButtonElement>('#submit')!;
vault.subscribe(() => {
  button.disabled = !vault.getFormState().isValid;
});

button.addEventListener('click', async () => {
  try {
    const result = await vault.submit();
    // result.status is the HTTP status; result.data is the parsed response body.
    // Raw field values are never available here.
    console.log('OK', result.status);
  } catch (error) {
    if (error instanceof CoinmeVaultError) {
      console.log(`${error.kind}: ${error.message}`);
    }
  }
});

// Call when the hosting view is removed.
// vault.dispose();
```

Three things to notice:

- `createCoinmeVault`**is async.** It loads VGS Collect.js from the CDN before resolving. Wait for it before calling any field factories.
- **Field containers must exist first.** The factory calls (`createCardNumberField`, etc.) mount iframes into DOM elements. Create the vault and call the factories only after your containers are in the DOM.
- `vault.subscribe` notifies on every field-state change and returns an unsubscribe function. Poll `vault.getFormState().isValid` inside it to keep your submit button in sync.

> **It's Easy!**
>
> For the vast majority of deployments, all you need to pass to `createCoinmeVault` is `environment`; you would pass `live` as the environment for production and `sandbox` for stage (testing). **The SDK does the rest**; you don't need to provide any other configuration.

## Framework setup

The SDK is framework-agnostic, but a few integration patterns are worth following per framework to get lifecycle and cleanup right.

### React

Vault creation is async and browser-only, so it belongs in a `useEffect`. Secure fields must be created after their container `<div>`s mount, and deleted in cleanup to prevent React 18 StrictMode's double-invocation from stacking duplicate iframes:

```tsx
import {
  createCoinmeVault,
  type CoinmeVault,
} from '@coinme-security/vault-sdk-js';
import { useEffect, useState, useSyncExternalStore } from 'react';

/** Creates the vault on mount (browser-only), disposes on unmount. */
const useCoinmeVault = () => {
  const [vault, setVault] = useState<CoinmeVault>();
  useEffect(() => {
    let disposed = false;
    let created: CoinmeVault | undefined;
    createCoinmeVault({ environment: 'sandbox' }).then((v) => {
      if (disposed) return v.dispose();
      created = v;
      setVault(v);
    });
    return () => {
      disposed = true;
      created?.dispose();
    };
  }, []);
  return vault;
};

/** Reactive form state - snapshot is referentially stable, no memo needed. */
const useVaultFormState = (vault: CoinmeVault) =>
  useSyncExternalStore(vault.subscribe, vault.getFormState);
```

Create fields in a separate effect, with cleanup:

```tsx
useEffect(() => {
  if (!vault) return;
  const fields = [
    vault.createCardNumberField('#pan'),
    vault.createExpiryField('#expiry'),
    vault.createCvcField('#cvc'),
  ];
  // Delete fields in cleanup so React StrictMode's double-run doesn't stack iframes.
  return () => fields.forEach((field) => field.delete());
}, [vault]);
```

A full working example is in `examples/react` in the SDK repository.

### Vue 3

Same lifecycle, Vue idioms - create the vault in `onMounted`, dispose in `onUnmounted`, mirror form state into a `ref`:

```markup
<script setup lang="ts">
import {
  createCoinmeVault,
  type CoinmeVault,
  type VaultFormState,
} from '@coinme-security/vault-sdk-js';
import { onMounted, onUnmounted, ref } from 'vue';

const vault = ref<CoinmeVault>();
const formState = ref<VaultFormState>({ isValid: false, fields: {} });
let unsubscribe: (() => void) | undefined;

onMounted(async () => {
  const v = await createCoinmeVault({ environment: 'sandbox' });
  vault.value = v;
  v.createCardNumberField('#pan', { placeholder: 'Card number' });
  v.createExpiryField('#expiry', { placeholder: 'MM / YYYY' });
  v.createCvcField('#cvc', { placeholder: 'CVC' });
  unsubscribe = v.subscribe(() => {
    formState.value = v.getFormState();
  });
});

onUnmounted(() => {
  unsubscribe?.();
  vault.value?.dispose();
});
</script>

<template>
  <div id="pan" />
  <div id="expiry" />
  <div id="cvc" />
  <button :disabled="!formState.isValid" @click="handleSubmit">Submit</button>
</template>
```

### SSR frameworks (Next.js, Nuxt, SvelteKit, …)

Importing the package on the server is safe - the module has no load-time browser side

effects. **Creating a vault is browser-only** - `createCoinmeVault` rejects if there is no `window`. Keep these points in mind:

- Create the vault inside client-side lifecycle code: `useEffect` (Next.js), `onMounted` (Nuxt), `onMount` (SvelteKit). The React and Vue examples above already do this.
- In Next.js App Router, add the `'use client'` directive to your form component.
- Don't render secure-field containers on the server expecting them to be filled - fields

mount only after the client-side vault exists.
- Add CSP headers in your framework's config (e.g. `next.config.js` headers) - see

[CSP](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#content-security-policy).

## Secure fields

Five factory methods are available on the vault instance. Each one mounts a cross-origin

iframe into the container matched by the CSS selector you pass, and returns the raw VGS field

instance. All VGS field methods - `mask()`, `replacePattern()`, `update()`, `reset()`, `delete()`, `focus()`, `on()`/`off()`, and the `promise` readiness signal - work exactly as

[VGS documents them](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/reference-documentation).

| Factory | Purpose |
| --- | --- |
| `createCardNumberField` | Card number with Luhn validation, brand detection, and masking. Defaults to name `pan`. Add `showCardIcon: true` for a brand icon inside the field. |
| `createExpiryField` | Expiry date in `MM / YYYY` format, with a built-in not-in-the-past check. On submit, a serializer splits it into `exp_month` and a 4-digit `exp_year`. Defaults to name `expiry`. |
| `createCvcField` | Security code; adapts to the detected card brand (3 or 4 digits). Defaults to name `cvc`. |
| `createCardHolderField` | Cardholder name - for flows that need it collected securely. (The payment-method helper accepts name literals instead.) Defaults to name `cardholder`. |
| `createTextField` | Generic secure field for other sensitive values: billing address lines, city, ZIP, SSN, etc. `name` is required. Choose field behaviour with `type` (`'text'`, `'ssn'`, `'zip-code'`, `'password'`, `'textarea'`, and others). |

Every factory passes all options through to VGS unfiltered, so new VGS options work without an SDK update.

> **Expiry year width.**
>
> The payment-method endpoint requires a 4-digit year. The expiry factory defaults to `MM / YYYY` accordingly. Override `yearLength: 2` only if your endpoint accepts 2-digit years.

### Field names

`VAULT_FIELD_NAMES` provides the conventional field-name constants - `pan`, `cvc`, `expiry`, `address1`, `address2`, `city`, `zipcode`. The card factories default to them. Pass them explicitly on `createTextField` so collected values line up with the payment-method request template:

```typescript
import { VAULT_FIELD_NAMES } from '@coinme-security/vault-sdk-js';

vault.createTextField('#address1', {
  name: VAULT_FIELD_NAMES.address1,
  validations: ['required'],
});
```

## Styling

Because secure fields render inside VGS iframes, ordinary page CSS cannot reach inside them. There are two complementary approaches.

### Inside the field: the `css` option

Style the field's text input with the `css` option. It supports regular CSS properties, pseudo-classes and pseudo-elements, nested `&` selectors, the VGS field state classes, web fonts via `@font-face`, and media queries:

```typescript
vault.createCardNumberField('#pan', {
  css: {
    'font-family': '"Inter", system-ui, sans-serif',
    'font-size': '16px',
    color: '#1b1d1f',
    '&::placeholder': { color: '#9aa0a6' },
    '&:focus': { color: '#000' },
    // VGS state classes: valid, invalid, empty, dirty, touched
    '&.invalid.touched': { color: '#c5221f' },
    '@font-face': {
      'font-family': 'Inter',
      src: 'url("https://example.com/inter.woff2")',
    },
  },
});
```

> Media queries inside `css` are computed against the **iframe's** width, not the page's.

### Around the field: the `classes` option

Your host container `<div>` receives state classes from VGS that you can target with regular page CSS. Map them to your own class names with the `classes` option:

```typescript
vault.createCvcField('#cvc', {
  classes: { invalid: 'field-invalid', focused: 'field-focused' },
});
```

```css
.field-focused { border-color: #1a73e8; }
.field-invalid  { border-color: #c5221f; }
```

VGS's default class names (if you don't override them) are `vgs-collect-container__invalid`, `__focused`, `__empty`, `__dirty`, and `__touched`.

### Masks and input shaping

Text-like fields expose VGS's chainable formatting API on the returned instance:

```typescript
const ssn = vault.createTextField('#ssn', { name: 'ssn', type: 'ssn' });
ssn.mask('999-99-9999', '*');       // 9: digit, a: letter, *: alphanumeric
ssn.replacePattern('/[^0-9-]+/g'); // strip anything else as the user types
```

For the full option-by-option reference, see the VGS [customization](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/customization) and [formatting](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/formatting)

pages - everything there is reachable through the factories' options and returned instances.

## Form state and validity

`vault.getFormState()` returns `{ isValid, fields }`. `vault.subscribe(listener)` fires on every field-state change and returns an unsubscribe function.

```typescript
const unsubscribe = vault.subscribe(() => {
  const { isValid, fields } = vault.getFormState();
  submitButton.disabled = !isValid;
  panHint.hidden = !(fields.pan?.isDirty && !fields.pan?.isValid);
});
```

`isValid` is `true` only when at least one field exists and every field reports valid. A validation-free `createTextField` (e.g. an optional apartment line) counts as valid while empty and won't block submission; fields with `validations` stay invalid until they pass.

Each entry in `fields` carries non-sensitive state and metadata: `isValid`, `isDirty`, `isEmpty`, `isFocused`, `isTouched`, `errorMessages`, and for card fields `last4`, `bin`, and `cardType`. Raw field values are never included.

The form state snapshot is referentially stable between changes, so it plugs directly into React's `useSyncExternalStore`:

```typescript
useSyncExternalStore(vault.subscribe, () => vault.getFormState())
```

> Plain (non-PCI) inputs collected with a regular `<input>` - such as a billing `state`
>
> dropdown - are not part of the vault. Gate your submit on `isValid` **and** your own checks for any plain inputs.

## Submitting a payment method

> **Never use your partner access token with the Vault SDK.**
>
> The `Authorization` header must be `Bearer <transient-auth-token>` with a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend mints from `POST /services/browserAuth`. Never pass your partner access token (from `POST /services/authorize`) to the SDK.

From 1.2.3 the SDK refuses a submit whose `Authorization` header carries a partner access token and throws a `configuration` `CoinmeVaultError` 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` and return only its `access_token`. The partner access token is a long-lived credential that must stay on your backend.

For Coinme's payment-method endpoint specifically, the SDK ships a `submitPaymentMethod` helper that assembles the nested request body for you. The card number, expiry, CVC, and billing address fields are wired in by their `VAULT_FIELD_NAMES`; the remaining values (`customerId`, billing first/last name, etc.) are plain literals you supply.

```typescript
import {
  submitPaymentMethod,
  VAULT_FIELD_NAMES,
} from '@coinme-security/vault-sdk-js';

// Mount secure fields using VAULT_FIELD_NAMES so values line up with the request template.
vault.createCardNumberField('#pan');
vault.createExpiryField('#expiry');
vault.createCvcField('#cvc');
vault.createTextField('#address1', { name: VAULT_FIELD_NAMES.address1, validations: ['required'] });
vault.createTextField('#address2', { name: VAULT_FIELD_NAMES.address2 });
vault.createTextField('#city',     { name: VAULT_FIELD_NAMES.city,     validations: ['required'] });
vault.createTextField('#zipcode',  { name: VAULT_FIELD_NAMES.zipcode,  validations: ['required', 'postal_code/us'] });

const result = await submitPaymentMethod(vault, {
  customerId: 'customer_123',
  paymentProcessAssociation: 'BUY',   // 'BUY' | 'SELL'
  paymentProviderId: 'provider_123',
  webSessionId: 'session_123',        // Risk SDK session tag, fetched right before this call
  billingAddress: {
    firstName: 'Jane',
    lastName: 'Doe',
    state: 'WA',                      // plain literal, e.g. from a regular <select>
    country: 'US',                    // optional; defaults to 'US'
  },
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Bearer <transient-auth-token>',
    // From 1.3.0, with Risk SDK for Web 1.2.0 or later, X-Device-Fingerprint is
    // added for you. Otherwise pass the same value you gave the Risk SDK.
  },
});
```

### `submitPaymentMethod` input fields

| Field | Type | Notes |
| --- | --- | --- |
| `customerId` | `string` | The signed-in Coinme customer the payment method belongs to. |
| `paymentProcessAssociation` | `'BUY' \| 'SELL'` | Whether the card is being added for a buy or sell ramp. |
| `paymentProviderId` | `string` | Payment provider identifier; sent as `providerId` in the request body. |
| `webSessionId` | `string` | Risk SDK web session identifier (from the Coinme Risk SDK). Required - always sent in the body. Fetch it from the Risk SDK right before each submit: a session tag lives 30 minutes. |
| `billingAddress` | object | `{ firstName, lastName, state, country? }` - plain literals. `country` defaults to `'US'`. |
| `headers` | `Record<string, string>?` | Optional request headers, e.g. `Authorization`. From 1.3.0, with Risk SDK for Web 1.2.0 or later, `X-Device-Fingerprint` is optional; see [Device fingerprint](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#device-fingerprint). |
| `timeoutMs` | `number?` | Per-call submit timeout. Defaults to 60,000 ms. A submit that times out fails as a `network` error (from 1.2.2 with `timedOut: true`), but the request may still have completed, so the outcome is unknown: check the user's payment methods before retrying, or you may add the same one twice. |

Every submit auto-attaches Coinme distributed-tracing headers (`X-B3-TraceId`, `X-B3-SpanId`); pass your own values in `headers` to override them. Headers are per-call only - they do not

persist to later submits.

## Error handling

Every failure during submit - VGS field validation, network error, HTTP error, or a Coinme

application-level error - is normalized to a `CoinmeVaultError`. Catch it and branch on `error.kind`:

```typescript
try {
  await vault.submit();
} catch (error) {
  if (error instanceof CoinmeVaultError) {
    switch (error.kind) {
      case 'validation':
        // One or more fields failed VGS validation before the request was sent.
        showFieldErrors(error.fields); // Record<string, string[]>
        break;
      case 'server':
        // The request completed with a non-2xx HTTP status. From 1.2.3,
        // error.errorResponse carries the Coinme error envelope when the body had one.
        reportStatus(error.status);
        break;
      case 'caas':
        // 2xx response, but Coinme's backend returned an application error envelope.
        reportCaas(error.errorResponse);
        break;
      case 'network':
        if (error.timedOut) {
          // From 1.2.2: the submit hit timeoutMs. The request may still have
          // completed, so check the user's payment methods before a retry.
          await refreshPaymentMethods();
        } else {
          // Not sent - offline, DNS/TLS failure, a blocked iframe, or a VGS
          // CDN load failure.
          showRetry();
        }
        break;
      case 'configuration':
        // From 1.2.3: refused before sending, because Authorization carries a
        // partner access token. Fix the integration; a retry won't help.
        reportIntegrationError(error.message);
        break;
      default:
        // 'unknown' - any other unexpected failure.
        showRetry();
    }
  }
}
```

| `kind` | Meaning | Extra fields |
| --- | --- | --- |
| `validation` | A field failed VGS validation before the request was sent. | `fields` - `Record<string, string[]>` of VGS messages |
| `server` | The request completed with a non-2xx status. | `status`; from 1.2.3 also `errorResponse` when the body carried a Coinme error envelope |
| `caas` | 2xx response carrying a Coinme application-level error envelope. | `status`, `errorResponse` |
| `network` | No response was received. Either the request was not sent (offline, DNS/TLS failure), a secure field iframe failed to load, or the VGS CDN script failed to load during `createCoinmeVault`; or the submit hit `timeoutMs`, in which case the request may still have completed and the outcome is unknown. | `timedOut: true` on a timeout, from 1.2.2 |
| `configuration` | From 1.2.3. Refused before sending: the `Authorization` header carries a partner access token instead of a Transient Auth Token. Retrying will not help. | - |
| `unknown` | Any other unexpected failure. | - |

`CoinmeVaultError` never contains raw card data. Where a failure wraps an underlying error, the original is on `error.cause`; a request that times out has no `cause`.

To tell what went wrong, read the Coinme error envelope on `error.errorResponse` (`caas`, and from 1.2.3 `server` when the body carried one): its `errorData` entries each carry an `errorCode` and a `message` saying what went wrong (for example `Card already in use`), and it carries the `retry` flag. Branch on `errorCode`. From 1.2.3, a `caas` error's `message` is the envelope's first message, or a generic summary when it has none, and a `server` error's `cause` is `{ status, data }`, where `data` is the response body.

A timeout is not proof that nothing happened: the request may still be delivered after the SDK stops waiting. Never retry a timed-out submit blindly, or you may add the same payment method twice. Check the current state first (for example, re-list the user's payment methods) and retry only if the item is missing.

## Verifying your integration in sandbox

1. Create the vault with `environment: 'sandbox'`.
2. Use VGS test card values: card number `4111 1111 1111 1111`, any future expiry, any 3-digit CVC.
3. Watch `vault.getFormState().isValid` flip to `true` as all fields fill with valid data.
4. Submit and confirm you receive either a 2xx result or a `CoinmeVaultError` whose `kind` matches what you intentionally broke (going offline → `network`, a bad token → `server` or `caas`).

## Advanced topics

These sections cover less common integration scenarios. Most integrations won't need them.

### Vault configuration options

`createCoinmeVault(options)` resolves once at creation. To change configuration, create a new vault (call `dispose()` on the old one first).

| Option | Type | Notes |
| --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | Required. Selects the vault, ingress host, and submit path. |
| `config` | `RuntimeVaultConfig?` | Optional ingress and submit-path overrides. Both sandbox and live entries must be provided; `environment` decides which is active. |
| `onError` | `(error: unknown) => void` | Optional observe-only callback for initialization failures - use for logging. Handle the returned promise rejection to recover. |

### Custom ingress or submit path

To override the default ingress host or submit path, pass a `config` object. Both `sandbox` and `live` entries are required; `environment` decides which is active. The vault ID itself is not configurable at runtime.

> **You should never pass in a custom ingress unless you have been explicitly directed to do so by your Coinme integration contact.**Doing so can break your integration and can result in PCI compliance issues that would cripple your card processing efforts.
>
> **When in doubt:** pass only environment; let the SDK do the work for you.

```typescript
const vault = await createCoinmeVault({
  environment: 'sandbox',
  config: {
    sandbox: { ingress: 'https://secure.sandbox.example.com', path: '/your/submit/path' },
    live:    { ingress: 'https://secure.example.com',         path: '/your/submit/path' },
  },
});
```

> **Ingress caveat.**
>
> A VGS ingress hostname is a custom CNAME that must be registered and activated in VGS. VGS does not validate it client-side: an unregistered hostname silently falls back to the default vault URL rather than failing. Always verify a new ingress value in sandbox before using it in production.

### Custom request body

When your ingress expects a body shape other than the built-in payment-method one, call `vault.submit()` directly. Pass a `data` callback - VGS invokes it at submit time with

`formValues`, a map of each field's name to an opaque placeholder token (never the raw value). VGS resolves the real values inside its iframes before the request leaves the browser.

```typescript
const result = await vault.submit({
  data: (formValues) => ({
    sensitiveData: {
      cardNumber: formValues[VAULT_FIELD_NAMES.pan],
    },
    nonSensitiveData: 'some-literal',
  }),
  headers: { Authorization: `Bearer ${transientAuthToken}` },
});
```

`buildPaymentMethodRequest(input)` returns the `{ data }` callback the payment-method helper

uses internally - start from there if you need the standard body shape plus additional keys.

### Raw VGS access

The field factories return raw VGS field instances, and the underlying Collect form is exposed as `vault.form`. This gives you access to the full [Collect.js API](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/reference-documentation), fully typed by this SDK (VGS ships no types of its own):

```typescript
import type { CollectForm, CollectFieldState } from '@coinme-security/vault-sdk-js';

vault.form.on?.('enterPress', () => submitButton.click());
const raw = vault.form.field('#custom', { type: 'zip-code', name: 'zip' });
```

Fields created directly via `vault.form.field()` are not tracked by the SDK's form state or

readiness checks - prefer the factory methods unless you need something they can't express.

## Security rules

These rules apply to your integration. They are enforced by the iframe model and carry through from VGS:

- **Never log or persist raw card values.** Use only the state metadata surfaced by `vault.getFormState()` - `isValid`, `isDirty`, `last4`, `cardType`, `bin` - and the parsed

response body. The iframe model keeps values out of your JavaScript; keep it that way.
- **Always gate submit on validity.** Disable your submit button until `vault.getFormState().isValid` is `true`. This prevents malformed card data from ever being sent.
- **Import only from the package root.** Never import from internal subpaths (`@coinme-security/vault-sdk-js/core/...`) - use only the public exports.

## Example apps

Runnable reference implementations are included in the SDK repository:

- `examples/vanilla` - Vite + vanilla TypeScript with the full payment-method form.
- `examples/react` - Vite + React 18 using `useSyncExternalStore`.

Both examples render a complete card + billing address form, gate submit on validity, branch `CoinmeVaultError` by kind, and demonstrate the styling options. Copy-paste recipes for individual tasks are in `examples/HOWTOS.md`.

## Troubleshooting

`401`**during install** - `CLOUDSMITH_TEAM_TOKEN` is missing or expired. Re-export it and reinstall:

```bash
export CLOUDSMITH_TEAM_TOKEN=<your-token>
yarn install
```

`createCoinmeVault`**rejects with "can only load in a browser"** - you called it during

server-side rendering. Move vault creation into client-side lifecycle code (`useEffect`, `onMounted`, `onMount`). Importing the package in Node is safe; creating a vault there is not.

`createCoinmeVault`**rejects with "Failed to load VGS Collect.js"** - the CDN request was

blocked. Check your [CSP configuration](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#content-security-policy) and confirm `js.verygoodvault.com` is not blocked by a browser extension or firewall.

**Fields never render /**`submit`**throws**`unknown` - the secure field iframes were blocked,

or the container elements didn't exist when the factory was called. Check for ad blockers or

firewall rules blocking `js.verygoodvault.com`, and confirm containers are in the DOM before calling the factory methods.

**Submit button never enables** - `isValid` requires every registered field to be valid. Check that required fields carry `validations: ['required']`, and that any plain `<input>`

values are validated separately - they don't register with the vault and don't count toward

`isValid`.

**Submits succeed but hit the wrong host** - an unregistered ingress CNAME silently falls

back to the default vault URL rather than failing. Verify the ingress value in sandbox before

using it in production - see the [ingress caveat](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#custom-ingress-or-submit-path).

**React StrictMode shows doubled fields in development** - create fields in a `useEffect` and delete them in its cleanup function. See the [React setup](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#react) section and `examples/react` in the SDK repository.

## Device fingerprint

Coinme ties risk checks to a device ID sent as the `X-Device-Fingerprint` header. On the web and React Native you don't have to supply one.

- If you pass a fingerprint, 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`.
- Leaving the header out needs these releases or later: Risk SDK for Web 1.2.0, Risk SDK for React Native 1.1.0, Vault SDK for JavaScript 1.3.0, Vault SDK for React Native 1.3.0, Onboarding SDK for JavaScript & React 1.7.0, Onboarding SDK for React Native 1.2.0. With an older release, pass every Coinme SDK the same `X-Device-Fingerprint` you give the Risk SDK.
- Calls your server makes to Coinme for this user (for example orders) must send the same value. Read it in your web page or app with the SDK's `getDeviceFingerprint()` (on React Native it returns a Promise) and send it to your server with the request. Never call `getDeviceFingerprint()` on your server.
- On the web the value belongs to the browser and the site's origin, not the device: a page on another origin gets a different one.
- A `:` in the value is replaced with `-`.
- A risk session tag lives 30 minutes from when it was first issued. Fetch it right before adding a payment method or placing an order, and send the tag it returns as `webSessionId`.

## Verify

Build and run the app. Confirm the secure fields render and validate, that the submit control stays disabled until the form is valid, that the client gets a Transient Auth Token from the human's backend route and sends it as `Authorization: Bearer <token>` together with a Risk SDK session id fetched right before the submit and the device fingerprint the Risk SDK uses, that the `Authorization` header never carries the partner access token, and that no token or backend credential is in the client or a committed file.

### Reading the result

**Done when:** Invalid input keeps the form invalid, the submit resolves without an error, and listing the customer's payment methods from your backend shows the card `CREATED`.

**Stop and ask the human when** the card is refused as in use and you cannot find the earlier test that holds it, or the session tag keeps failing to match after you minted it on the same device.

Judge every Coinme call by its body, not its HTTP status: a refused request usually comes back as HTTP 200 with the error in the body. [Reading results](https://platformdocs.coinme.com/agents/results.md) has the rule, what each common error code asks you to do, and what to send your Coinme integration contact when something fails.

## Reference
- [Coinme Vault SDK](https://platformdocs.coinme.com/docs/coinme-vault-sdk.md)
- [Coinme Vault SDK for Javascript](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md)
- [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md)
