> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.runpayments.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.runpayments.io/_mcp/server.

# Run Tokenization (Runner.js v2)

## Overview

Runner.js v2 is Run's browser SDK for Agnostic Gateway Tokenization. It mounts a secure card entry form (card number, expiry and CVV) on your checkout page. Clients type their card details into an iframe hosted by the Runner.js tokenization service, so the data never touches your page or your servers. In return you get an `account_token` that you can charge or vault through the Run API.

> **Info**
>
> You don't choose a gateway in your front-end code. When you call `init()`, Runner looks up the merchant's configuration and mounts the right integration automatically. This guide covers the flexible, fully themeable card tokenizer used by accounts enabled for Run Tokenization.
>
> Run turns on Run Tokenization for each MID. Send a Run Request asking for Run Tokens to be activated for a particular merchant. On a MID without Run Tokenization, v2 renders the gateway's hosted fields and returns the v1 result shape.
>
> If you're moving an existing Runner.js v1 integration, follow the [Run Tokenization Migration Guide](/docs/guides/tokenization/run-tokenization-migration-guide).

### How It Works

* **Card data stays in the iframe.** You only ever see the `account_token` and PCI-permitted metadata: `bin` (first 6 digits), `last4` and `brand`.
* **The integration is selected for you.** There is no gateway parameter to pass.
* **One iframe, three fields.** Card number, expiry and CVV are all rendered in a single iframe. You control how they're arranged inside it (see [Field layout](#field-layout)).

### Quick Start

#### Add a Mount Point

Add an empty element where the card form should appear, plus your own submit button.

```html
<div id="card-form"></div>
<button id="pay">Pay</button>
```

#### Load the SDK

```html
<script src="https://javelin.runpayments.io/javascripts/latest/runner-v2.js"></script>
```

#### Create an Instance and Mount the Form

```javascript
var runner = new Runner({ env: 'production' });

runner.init({
  element:   '#card-form',      // where to render
  publicKey: 'pk_live_xxx',     // your publishable key
  mid:       'YOUR_MERCHANT_ID' // merchant the card is collected for
});
```

#### Tokenize When the Client Submits

```javascript
document.getElementById('pay').addEventListener('click', function () {
  runner.tokenize(function (result) {
    if (result.account_token) {
      // Send result.account_token to your server to charge or vault it.
      console.log('Token:', result.account_token, result.brand, result.last4);
    } else {
      console.error('Tokenization failed:', result.tokenizererror);
    }
  });
});
```

That's the whole happy path. Everything else is optional configuration.

### Loading the SDK

Load `runner-v2.js` from the host that matches your environment:

| Environment | `env` value            | Script host                              |
| ----------- | ---------------------- | ---------------------------------------- |
| Production  | `production` (default) | `https://javelin.runpayments.io`         |
| Staging     | `staging`              | `https://javelin-staging.runpayments.io` |

The script exposes a global `Runner` class. Create one instance per card form:

```javascript
var runner = new Runner({
  env:     'production', // must match the host you loaded the script from
  version: '2.0.4'       // optional; defaults to the bundle's own version
});
```

> **Tip**
>
> `/javascripts/latest/runner-v2.js` always serves the newest release. To stay on a specific version, pin it in the path: `/javascripts/2.0.4/runner-v2.js`.

> **Warning**
>
> `env` must be one of the supported values. If it isn't, the SDK refuses to send tokenization requests rather than risk routing card data to an unknown origin.

#### Constructor Options

| Option    | Type                          | Default        | Description                                     |
| --------- | ----------------------------- | -------------- | ----------------------------------------------- |
| `env`     | `'production'` or `'staging'` | `'production'` | Target environment. Must match the script host. |
| `version` | string                        | bundle version | Pins the version of the hosted iframe.          |

## Configuration

Pass all options to `runner.init()`. Only `element`, `publicKey` and `mid` are required.

### Required

| Option                 | Type   | Description                                                                                                                        |
| ---------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| `element` (required)   | string | CSS selector of the element to mount the card form into, for example `'#card-form'`. The element's existing contents are replaced. |
| `publicKey` (required) | string | Your publishable API key.                                                                                                          |
| `mid` (required)       | string | Merchant ID the card is being collected for.                                                                                       |
| `accountId` (optional) | string | Accepted for gateway integrations that use it. The Run Tokenization card flow resolves on `publicKey` and `mid` alone.             |

### Labels & Placeholders

| Option             | Type   | Default                 | Description                        |
| ------------------ | ------ | ----------------------- | ---------------------------------- |
| `cardLabel`        | string | `"Card Number"`         | Label above the card number field. |
| `expiryLabel`      | string | `"Expiry"`              | Label above the expiry field.      |
| `cvvLabel`         | string | `"CVV"`                 | Label above the CVV field.         |
| `cardPlaceholder`  | string | `"1234 5678 1234 5678"` | Card number placeholder.           |
| `monthPlaceholder` | string | `"MM/YY"`               | Expiry placeholder.                |
| `cvvPlaceholder`   | string | `"•••"`                 | CVV placeholder.                   |

### Field Behavior

| Option                  | Type    | Default | Description                                                                                                                                                              |
| ----------------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `useCvv`                | boolean | `true`  | Set to `false` to skip collecting CVV. The field is removed and its grid slot is reclaimed.                                                                              |
| `useExpiry`             | boolean | `true`  | Set to `false` to skip collecting expiry.                                                                                                                                |
| `updateMode`            | boolean | `false` | For card-on-file updates where the expiry is already known. Expiry is not rendered or required. Use this instead of `useExpiry: false` when re-tokenizing a stored card. |
| `tokenizeAutomatically` | boolean | `false` | Tokenize automatically when the card field loses focus, instead of waiting for `tokenize()`.                                                                             |
| `inactivityto`          | number  | `0`     | Tokenize automatically after this many milliseconds of typing inactivity. `0` disables it.                                                                               |
| `autoAdvance`           | boolean | `true`  | Moves focus from card number to expiry to CVV as each field is completed (at the brand's maximum length). Set to `false` to manage focus yourself.                       |

### Layout & Styling Options

| Option         | Type                                                   | Default     | Description                                                                                                         |
| -------------- | ------------------------------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------- |
| `layout`       | `'default'`, `'single-row'`, `'stacked'` or `'custom'` | `'default'` | Field arrangement preset. See [Field layout](#field-layout).                                                        |
| `errorDisplay` | `'inline'` or `'summary'`                              | `'inline'`  | Where validation errors appear. See [Error display](#error-display).                                                |
| `css`          | string or object                                       | none        | Custom styling, filtered through a security allowlist. See [Styling](#styling) and [CSS allowlist](#css-allowlist). |

### Built-In Capabilities

These work automatically. No configuration is needed.

#### Card Brand Recognition

The brand is detected from the BIN on every keystroke, and a live brand icon appears in the field. Supported brands: Visa, Mastercard, American Express, Discover, JCB and Diners Club. Unrecognized ranges fall back to a generic 16-digit (4-4-4-4) rule set and never block the form.

#### Auto-Formatting

Digits are grouped by brand as the client types, for example 4-4-4-4 for most cards and 4-6-5 for American Express.

#### Luhn and Length Validation

Real-time and brand-aware. An error appears only once the field reaches a valid length for the brand without passing the check. A failing check blocks tokenization.

#### BIN Lookup

A debounced lookup runs on the first 6 digits and surfaces brand metadata through `Runner.onBinInfo`. A failed lookup never blocks tokenization.

#### Masked Metadata

The token response includes the PCI-permitted `bin` (first 6) and `last4`. The full card number is never exposed.

#### CVV Length by Brand

4 digits for American Express, 3 for all other brands.

#### Browser Autofill

Standard `autocomplete` attributes (`cc-number`, `cc-exp`, `cc-csc`) are set so browser card autofill works.

#### Auto-Resize

The iframe reports its height to your page and adjusts as the layout or error messages change.

#### PCI Idle-Clear

If card fields contain typed but unsubmitted data for 5 minutes with no activity, they are cleared automatically so an abandoned card number or CVV never lingers on the page. This fires `Runner.onIdleTimeout`. It's a security control and can't be configured or disabled. It never affects a card that has already been tokenized.

## Layout & Styling

The card form is fully themeable. Because your CSS is applied inside the secure card iframe, it's filtered through a security allowlist. You get full control over colors, fonts, borders, spacing and grid or flex layout. Properties that could be used to hide or overlay fields are removed.

### Field Layout

The form container (`.rn-form`) is a CSS grid. Every field and every error message is its own grid item, so you aren't limited to a fixed row.

#### Presets

Choose a preset with the `layout` option:

| `layout`     | Arrangement                                                    |
| ------------ | -------------------------------------------------------------- |
| `default`    | Card number on its own row; expiry and CVV share the next row. |
| `single-row` | Card number, expiry and CVV all on one line.                   |
| `stacked`    | Every field on its own full-width row.                         |
| `custom`     | No built-in grid. You define it entirely with `css`.           |

```javascript
runner.init({
  element: '#card-form',
  publicKey: 'pk_live_xxx',
  mid: 'YOUR_MERCHANT_ID',
  layout: 'single-row'
});
```

#### Custom Layouts

For full control, set `layout: 'custom'` and target the styling hooks with `css`. All grid properties are on the allowlist.

```javascript
runner.init({
  element: '#card-form',
  publicKey: 'pk_live_xxx',
  mid: 'YOUR_MERCHANT_ID',
  layout: 'custom',
  css: `
    .rn-form {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-template-areas:
        "card card card"
        "expiry cvv .";
      gap: 12px;
    }
    [data-field="card"]   { grid-area: card; }
    [data-field="expiry"] { grid-area: expiry; }
    [data-field="cvv"]    { grid-area: cvv; }
  `
});
```

> **Info**
>
> All three fields live in one iframe. You can arrange them freely inside it, but you can't place your own page inputs (such as a cardholder name field) between them. This is a deliberate PCI boundary.

### Styling

Pass CSS with the `css` option, either as a CSS string or as an object of selectors mapped to property/value pairs:

```javascript
// String form
css: '.rn-input { border-radius: 10px; border-color: #6b7280; } .rn-label { color: #374151; }'

// Object form
css: {
  '.rn-input': { 'border-radius': '10px', 'border-color': '#6b7280' },
  '.rn-label': { color: '#374151' }
}
```

#### Styling Hooks

| Selector                                                                          | Element                                          |
| --------------------------------------------------------------------------------- | ------------------------------------------------ |
| `.rn-form`                                                                        | The grid container.                              |
| `.rn-field`, `[data-field="card"]`, `[data-field="expiry"]`, `[data-field="cvv"]` | A field wrapper (label and input).               |
| `.rn-label`                                                                       | Field labels.                                    |
| `.rn-input`                                                                       | The input boxes.                                 |
| `.rn-input:focus`, `.rn-input.is-valid`, `.rn-input.is-invalid`                   | Focus and validation states.                     |
| `.rn-brand-icon`                                                                  | The live card brand icon.                        |
| `.rn-error`, `[data-error="card"]`, `[data-error="expiry"]`, `[data-error="cvv"]` | A per-field error message.                       |
| `.rn-error-summary`                                                               | The combined error region (`summary` mode only). |

### Error Display

Choose where validation messages appear with `errorDisplay`:

| `errorDisplay`     | Behavior                                                                                                                                               |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `inline` (default) | Each error sits in its own grid cell below its field. Move any of them with `[data-error="..."]` in `css`.                                             |
| `summary`          | Per-field messages are hidden. All errors are combined into a single `#rn-error-summary` region that you can place and style like any other grid item. |

```javascript
runner.init({
  element: '#card-form',
  publicKey: 'pk_live_xxx',
  mid: 'YOUR_MERCHANT_ID',
  layout: 'stacked',
  errorDisplay: 'summary'
});
```

> **Tip**
>
> To control your own submit button in real time, listen to [`Runner.onFieldChange`](#runneronfieldchange) rather than relying on the visible errors.

### CSS Allowlist

Unrestricted CSS inside a card iframe is a clickjacking risk: a malicious rule could move or hide the CVV field and overlay it on the host page. To prevent this, Runner only accepts a sanitized allowlist of layout and theming properties. Anything not listed below is removed.

#### How Your CSS Is Sanitized

1. Comments (`/* ... */`) are removed first so they can't hide anything.
2. Only flat `selector { property: value; }` blocks are read. At-rules such as `@import`, `@charset` and `@media` are dropped, and nested blocks aren't supported.
3. Selectors containing `<`, `>`, `\` or `@` are rejected.
4. Each declaration is kept only if its property is on the allowlist.
5. A declaration is dropped if its value contains `url(`, `expression(`, `image-set(`, `javascript:`, `<`, `>`, `\`, `@` or a comment delimiter.
6. `!important` is removed, so you can't override critical layout rules.

#### Allowed Properties

#### Color & Typography

`color`, `background`, `background-color`, `font`, `font-family`, `font-size`, `font-weight`, `font-style`, `line-height`, `letter-spacing`, `text-align`, `text-transform`, `text-decoration`

#### Box Model & Sizing

`padding`, `padding-top`, `padding-right`, `padding-bottom`, `padding-left`, `margin`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, `width`, `min-width`, `max-width`, `height`, `min-height`, `max-height`, `box-sizing`

#### Borders & Focus Rings

`border`, `border-top`, `border-right`, `border-bottom`, `border-left`, `border-color`, `border-width`, `border-style`, `border-radius`, `outline`, `outline-color`, `outline-width`, `outline-style`, `outline-offset`, `box-shadow`

#### Flexbox Layout

`display`, `gap`, `row-gap`, `column-gap`, `flex`, `flex-direction`, `flex-wrap`, `flex-grow`, `flex-shrink`, `flex-basis`, `align-items`, `align-content`, `align-self`, `justify-content`, `justify-items`, `justify-self`

#### Grid Layout & Ordering

`grid`, `grid-template`, `grid-template-columns`, `grid-template-rows`, `grid-template-areas`, `grid-column`, `grid-row`, `grid-area`, `grid-auto-flow`, `grid-auto-columns`, `grid-auto-rows`, `place-items`, `place-content`, `place-self`, `order`, `white-space`, `vertical-align`

These only rearrange items inside the iframe. They can't position anything relative to your page.

#### Transitions

`transition`, `transition-property`, `transition-duration`, `transition-timing-function`

#### Not Allowed

| Property or feature                                     | Why it's blocked                                                 |
| ------------------------------------------------------- | ---------------------------------------------------------------- |
| `position`, `top`, `right`, `bottom`, `left`, `z-index` | Repositioning and stacking are the core clickjacking techniques. |
| `transform`                                             | Can move a field off-screen or overlay it.                       |
| `opacity`, `visibility`                                 | Can make an input invisible while it still captures typing.      |
| `content`                                               | Allows injecting content through pseudo-elements.                |
| `cursor`                                                | `cursor: url(...)` loads a remote resource.                      |
| `animation`, `@keyframes`                               | Can be used to reveal or hide elements over time.                |
| `background-image` and any `url(...)` value             | Remote resource loading, tracking and mixed content.             |
| All at-rules, including `@import`                       | Remote stylesheet loading.                                       |

> **Tip**
>
> If a property you set has no effect, check it against the allowlist above. Positioning and remote-resource properties are removed on purpose.

## Methods, Events & Tokens

### Methods

Call these on your `Runner` instance.

| Method              | Signature                             | Description                                                                                                                                                                                                                                |
| ------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `init`              | `init(params)`                        | Mounts the card form. See [Configuration](#configuration).                                                                                                                                                                                 |
| `tokenize`          | `tokenize(done, expMonth?, expYear?)` | Validates the fields and tokenizes the card. `done(result)` receives the token result. When expiry is hidden (for example in `updateMode`), you can pass `expMonth` and `expYear`. Use a 4-digit year (`'2028'`); CyberSource requires it. |
| `onTokenize`        | `onTokenize(cb)`                      | Fires whenever a token becomes available (for example with `tokenizeAutomatically`) or is cleared. See below.                                                                                                                              |
| `onLoaded`          | `onLoaded(cb)`                        | Fires when the card iframe has loaded and is ready.                                                                                                                                                                                        |
| `getTokenizerError` | `getTokenizerError()`                 | Returns the current tokenizer error message as a string, if there is one.                                                                                                                                                                  |
| `destroy`           | `destroy()`                           | Removes the form and its iframe. Call it before mounting again, for example on single-page app navigation.                                                                                                                                 |

#### onTokenize Payload

```javascript
runner.onTokenize(function (e) {
  // e = {
  //   hasToken:      boolean,  // false when the token is cleared
  //   token:         string,
  //   account_token: string,   // same value as token
  //   expiration?:   string,   // legacy; use expiry
  //   bin?:          string,   // first 6
  //   last4?:        string,
  //   brand?:        string,
  //   expiry?:       string
  // }
});
```

`expiration` is a legacy field kept for v1 compatibility. Use `expiry` instead.

`bin`, `last4`, `brand` and `expiry` match the token result when the integration supplies them, which it does for Run Tokenization accounts.

### Events

Three real-time hooks let you drive your own UI, such as enabling your submit button only when the card is valid, without waiting for `tokenize()`.

> **Warning**
>
> Set these hooks as functions on the global `Runner` class, **not** on your instance.

#### Runner.onFieldChange

Fires on every change to the card number, expiry or CVV field.

```javascript
Runner.onFieldChange = function (e) {
  // e = { field: 'cardNumber' | 'expiry' | 'cvv',
  //       state: 'valid' | 'invalid' | 'incomplete',
  //       valid: boolean }
  if (e.field === 'cardNumber' && e.state === 'invalid') {
    // show your own hint, disable submit, etc.
  }
};
```

| `field`      | Emitted for       |
| ------------ | ----------------- |
| `cardNumber` | Card number field |
| `expiry`     | Expiry field      |
| `cvv`        | CVV field         |

| `state`      | Meaning                                                                                |
| ------------ | -------------------------------------------------------------------------------------- |
| `incomplete` | Not enough input to judge yet. Don't show an error.                                    |
| `invalid`    | Failed validation, such as a bad Luhn check or length, an expired date or a short CVV. |
| `valid`      | Passed validation.                                                                     |

> **Info**
>
> The field's value is never included. Only the field name and its validity cross the iframe boundary, so the card number and CVV never reach your page.

#### Runner.onBinInfo

Fires once 6 digits have been entered, and again when server-side enrichment arrives.

```javascript
Runner.onBinInfo = function (e) {
  // e = { action: 'BIN_INFO', brand: 'visa', first6: '411111',
  //       info?: { card_brand, country, issuer, debit, prepaid,
  //                corporate, l2enabled, l3enabled, ... } }
  console.log('Detected', e.brand, 'BIN', e.first6);
};
```

> **Info**
>
> In this release BIN data from `onBinInfo` is for display only: `card_brand` and the first six digits are derived from the card number prefix. For issuer, country and commercial-card data (for example, for L2/L3 or routing decisions), call the server-side `POST /api/v1/bin-info` endpoint with the returned token after tokenization.

#### Runner.onIdleTimeout

Fires when card fields with typed but unsubmitted data are cleared after 5 minutes of inactivity. Use it to reset your own UI, for example to re-enable a card entry state or hide a stale summary.

```javascript
Runner.onIdleTimeout = function () {
  // The card form was cleared for inactivity. Reset your submit UI.
};
```

This only fires for unsubmitted data. A card that has already been tokenized is masked and read-only, so it's left as is.

### Token Result

This is the object passed to your `tokenize(done)` callback. The same data is available through `onTokenize`.

**Success**

```javascript
{
  account_token: "3f2b…",  // the token. Send this to your server.
  bin:           "411111", // first 6 digits (PCI-permitted, safe to display and store)
  last4:         "1111",
  brand:         "visa",
  expiry:        "12/28"   // "" when expiry isn't collected
}
```

**Failure**

```javascript
{
  account_token:  null,
  tokenizererror: "Invalid card number" // reason
}
```

> **Warning**
>
> Always check that `account_token` is present before continuing. The token expires 5 minutes after tokenization, so charge or vault it promptly. Never send raw card data to your server.

## Examples

### Card-On-File Update

Re-tokenize a stored card without collecting expiry or CVV again.

```javascript
var runner = new Runner({ env: 'production' });

runner.init({
  element: '#card-form',
  publicKey: 'pk_live_xxx',
  mid: 'YOUR_MERCHANT_ID',
  updateMode: true,   // expiry not rendered or required
  useCvv: false,      // no CVV on an update
  layout: 'single-row'
});

// If you need to send a known expiry, pass it to tokenize().
// Use a 4-digit year ('2028'); CyberSource requires it.
runner.tokenize(function (r) { /* ... */ }, '12', '2028');
```

> **Warning**
>
> In `updateMode`, an empty expiry is sent to the tokenizer unless you pass one to `tokenize(done, expMonth, expYear)`. Make sure your flow supplies the expiry wherever the processor requires it.

### Enable Your Submit Button Only When the Card Is Valid

```html
<div id="card-form"></div>
<button id="pay" disabled>Pay</button>

<script src="https://javelin.runpayments.io/javascripts/latest/runner-v2.js"></script>
<script>
  var validity = { cardNumber: false, expiry: false, cvv: false };

  Runner.onFieldChange = function (e) {
    validity[e.field] = e.valid;
    document.getElementById('pay').disabled =
      !(validity.cardNumber && validity.expiry && validity.cvv);
  };

  var runner = new Runner({ env: 'production' });
  runner.init({ element: '#card-form', publicKey: 'pk_live_xxx', mid: 'YOUR_MERCHANT_ID' });

  document.getElementById('pay').addEventListener('click', function () {
    runner.tokenize(function (r) {
      if (r.account_token) submitToServer(r.account_token);
    });
  });
</script>
```

### Themed Single-Row Form with Summary Errors

```javascript
var runner = new Runner({ env: 'production' });

runner.init({
  element: '#card-form',
  publicKey: 'pk_live_xxx',
  mid: 'YOUR_MERCHANT_ID',
  layout: 'single-row',
  errorDisplay: 'summary',
  cardLabel: 'Card',
  css: {
    '.rn-input':         { 'border-radius': '10px', 'border-color': '#cbd5e1', 'font-size': '15px' },
    '.rn-input:focus':   { 'border-color': '#4f46e5' },
    '.rn-label':         { color: '#334155', 'font-weight': '600' },
    '.rn-error-summary': { background: '#fef2f2', padding: '8px', 'border-radius': '6px' }
  }
});
```

### Single-Page Apps

Destroy the form before navigating away or mounting it again.

```javascript
var runner = new Runner({ env: 'staging' });
runner.init({ element: '#card-form', publicKey: 'pk_test_xxx', mid: 'YOUR_MERCHANT_ID' });

// Later, when navigating away:
runner.destroy();
```

## Notes & Limitations

* **Send the token, never card data.** `account_token` is what goes to your server. It expires 5 minutes after tokenization, so charge or vault it promptly.
* **Fields share one iframe.** You can arrange card number, expiry and CVV freely inside the form, but you can't place your own inputs between them. This is a deliberate PCI boundary.
* **Supported brands.** Visa, Mastercard, American Express, Discover, JCB and Diners Club. Unrecognized BINs use a generic 16-digit rule set and still tokenize.
* **BIN data is display-only in this release.** For issuer, country and commercial-card data used for L2/L3 or routing, call `POST /api/v1/bin-info` from your server after tokenization.
* **updateMode and expiry.** Pass `expMonth` and `expYear` to `tokenize()` if your processor requires an expiry. Use a 4-digit year (`'2028'`); CyberSource requires it.
* **CSS is allowlisted.** If a property has no effect, check the [CSS allowlist](#css-allowlist).