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

# Browser SDK

> Integrate the Foil browser SDK: import t.js, call start() with your publishable key, and get a sealed session handoff with getSession() at action time.

Foil's browser surface is intentionally small. Import `t.js`, call `start()`, and call `getSession()` when the user performs a sensitive action.

```js theme={"dark"}
const Foil = await import("https://cdn.usefoil.com/t.js");
const foil = await Foil.start({ publishableKey: "pk_live_..." });

// At action time (signup, login, checkout)
const { sessionId, sealedToken } = await foil.getSession();
```

## Load and initialize

Start Foil as early as possible on your page. The SDK begins collecting signals immediately.

```html theme={"dark"}
<script type="module">
  const foilPromise = import("https://cdn.usefoil.com/t.js")
    .then((Foil) =>
      Foil.start({ publishableKey: "pk_live_your_publishable_key" })
    );

  const foil = await foilPromise;

  // Optional: subscribe to errors
  foil.onError((error) => {
    console.error(error.code, error.message);
  });

  // Optional: surface fingerprinting errors before the action
  void foil.waitForFingerprint().catch(console.error);
</script>
```

### Preload the SDK

The browser runs an inline module script only after it finishes parsing the page, so the `import()` call above doesn't start downloading `t.js` until then. To start the download while the page is still parsing, add a `modulepreload` link to the page's `<head>`:

```html theme={"dark"}
<link rel="modulepreload" href="https://cdn.usefoil.com/t.js" crossorigin>
```

The browser downloads and compiles `t.js` but doesn't run it, so the link on its own doesn't start a Foil session. When your `import()` call runs, it uses the preloaded module instead of making a second request.

* Use the same URL in the link and in your `import()` call, including any query string. A different URL downloads `t.js` twice.
* Put the link in the document that imports `t.js`. If Foil runs inside an iframe, the link belongs in the iframe's document, not in the parent page.
* Use `rel="modulepreload"`, not `rel="preload"`. Only `modulepreload` prepares the module for `import()`.
* Add the link only to pages that start Foil. The browser downloads `t.js` on every page that has the link.

Browsers without `modulepreload` support, such as Safari 15 and 16, ignore the link and download `t.js` when the import runs. If you load Foil through a first-party integration, preload `t.js` from the integration URL. See [Load the SDK from your domain](https://usefoil.com/docs/first-party/overview.md#load-the-sdk-from-your-domain).

## API reference

### Module exports

| Export | Type | Description |
| - | - | - |
| `start(options)` | `(options: FoilStartOptions) => Promise<FoilClient>` | Bootstrap the runtime and start signal collection. Resolves to a `FoilClient`. |
| `version` | `string` | SDK bundle version. Useful for support tickets and telemetry. |
| `FoilError` | `class` | Error class thrown by all async methods. See [Error handling](#error-handling). |

### `Foil.start(options)`

```ts theme={"dark"}
interface FoilStartOptions {
  publishableKey: string;   // pk_live_* or pk_test_*
  endpoint?: string;        // base URL for collection requests
}

function start(options: FoilStartOptions): Promise<FoilClient>;
```

Bootstraps the runtime and begins signal collection. Safe to call on page load.

* **`publishableKey`** is required. Pass a `pk_live_*` or `pk_test_*` key. Secret keys (`sk_*`) are rejected.
* **`endpoint`** is optional. It's the base URL the SDK sends collection requests to. When you import `t.js` through a [first-party integration](https://usefoil.com/docs/first-party/overview.md), it defaults to the directory of the imported `t.js`, which is the integration URL. Otherwise it defaults to Foil's API. The value must be an HTTPS URL without credentials, a query string, or a fragment. An invalid value rejects with `config.validation_failed`. The client exposes the resolved value as `endpoint`.
* `start()` is **idempotent for the same key** - calling it again with the same `publishableKey` and `endpoint` resolves to the same client without re-bootstrapping. Calling it with a *different* key or endpoint rejects with `config.already_initialized`.
* On success, signal collection has started. You don't need to await anything else before calling `getSession()` at action time - the SDK will flush whatever it has collected.
* Rejections are `FoilError`s (see [Error codes](#error-codes)): `config.validation_failed`, `config.already_initialized`, `runtime.bootstrap_failed`, `runtime.integrity_failed`, `runtime.start_failed`, `runtime.start_timeout`, or a `transport.*` code when Foil can't create a session.
* `start()` waits up to 10 seconds for the runtime to be ready. These limits, and the ones on `waitForFingerprint()` and `getSession()`, count only time the page is visible: a page in the background can't run Foil's work, so time spent hidden doesn't count. A wait still ends after 5 minutes if the page never comes back.
* A rejection with `retryable: true` applies to that attempt only. It usually means the network failed or Foil was unreachable while the session was being created. Call `start()` again, for example when the user submits, and `getSession()` retries the session.

### `FoilClient`

```ts theme={"dark"}
interface FoilClient {
  readonly endpoint: string;   // resolved base URL for collection requests
  getSession(): Promise<SessionHandoff>;
  waitForFingerprint(): Promise<void>;
  onError(handler: (error: FoilErrorPayload) => void): () => void;
  destroy(): void;
}

interface SessionHandoff {
  sessionId: string;     // sid_* - stable across getSession() calls on the same client
  sealedToken: string;   // base64 - opaque, verify server-side
}
```

#### `getSession()`

Flushes pending observations and returns a sealed handoff for your backend.

* Resolves with `{ sessionId, sealedToken }`. **Every call produces a fresh `sealedToken`**; the `sessionId` stays the same for the lifetime of the client.
* Safe to call multiple times. Calling it twice - e.g. on submit retry - is fine; just send the most recent handoff.
* Concurrent calls are coalesced: if you issue two `getSession()` calls before the first resolves, both receive the same handoff.
* **Tokens aren't single use.** Verification is stateless: the server SDKs decrypt a token, but they don't record it or check its age, so the same token verifies every time you submit it. To reject repeated submissions, record the `decision.event_id` of each token you accept (it's unique to each token) or the `session_id` if you want one action per session. See [What verification doesn't check](https://usefoil.com/docs/server-verification.md#what-verification-doesnt-check).
* You do **not** need to `await waitForFingerprint()` first. `getSession()` waits for fingerprinting to finish before it returns, and every handoff carries a `visitor_fingerprint`. If fingerprinting can't finish, `getSession()` rejects instead of returning a handoff without one.
* To get a session as early as possible, call `getSession()` right after `start()`, or alongside `waitForFingerprint()`, rather than after it. A `getSession()` that's already waiting can be answered with the fingerprint, one network round trip sooner.
* Rejects with a `FoilError`: `runtime.unavailable` when called before `start()` resolved or after `destroy()`, `runtime.session_failed` (`retryable: true`) when the handoff request fails or takes longer than 15 seconds of visible time, or a `transport.*` or API error code when the Foil API rejects the request. See [Error codes](#error-codes).

#### `waitForFingerprint()`

Resolves when fingerprinting has completed.

* Optional. `getSession()` waits for fingerprinting on its own, so you never need this call to get a visitor ID in the handoff. Its only use is to surface a fingerprinting error earlier than `getSession()` would.
* No identity data is returned to the browser; the fingerprint ID is only visible server-side in the verified sealed token.
* Typical fingerprint resolution completes within a few hundred milliseconds. Don't block your form submission on it - kick it off after `start()` and use `getSession()` at action time regardless.
* Safe to call in parallel with `getSession()`. Don't `await` it before `getSession()`: that waits out the round trip a waiting `getSession()` can skip.
* Rejects with `runtime.fingerprint_failed` (`retryable: true`, `fatal: false`), including when fingerprinting doesn't finish within 10 seconds of visible time. Foil doesn't score a session without a fingerprint, so `getSession()` can't succeed until fingerprinting does. Retrying after a transient failure can succeed.

#### `onError(handler)`

Subscribes to `FoilError` events emitted by the runtime.

* Returns an unsubscribe function: `const off = foil.onError(fn); /* later */ off();`.
* If a fatal error has *already* occurred before you attach the handler, it is replayed on the next microtask so you don't miss it.
* The `handler` receives the error as a `FoilErrorPayload` (the `toJSON()` shape of `FoilError`), which doesn't include `cause`. Exceptions thrown from your handler are swallowed to preserve event-emitter behavior - don't rely on them propagating.
* `onError` reports the errors that stop the runtime, which are failures during load and `start()`. Failures from `getSession()` and `waitForFingerprint()` reject those promises and aren't sent to `onError`.
* Use this for logging and observability. For control flow, `await` the promise from `start()` / `getSession()` / `waitForFingerprint()` and catch rejections.

#### `destroy()`

Stops timers and releases resources.

* **Terminal.** After `destroy()` the client cannot be restarted - discard the reference. Any subsequent `getSession()` / `waitForFingerprint()` calls reject with `runtime.unavailable`.
* Useful for SPAs that navigate away from a Foil-protected surface, or for tests that need to tear down between cases.
* Synchronous and best-effort - in-flight network requests may still complete in the background.

## Getting a session handoff

Call `getSession()` right before the protected action - not on page load.

```js theme={"dark"}
async function submitSignup(formData) {
  const { sessionId, sealedToken } = await foil.getSession();

  await fetch("/api/signup", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      ...formData,
      foil: { sessionId, sealedToken },
    }),
  });
}
```

The handoff contains:

```json theme={"dark"}
{
  "sessionId": "sid_7m2k9x4v8q1n5t3w6r0p2c4y8h",
  "sealedToken": "AQAA..."
}
```

Every call produces a fresh handoff. The browser never receives verdicts, scores, or visitor IDs.

## Error handling

All async methods reject with a structured `FoilError`. `onError` handlers receive the same shape, without `cause`, for errors that stop the runtime.

```json theme={"dark"}
{
  "code": "config.validation_failed",
  "message": "Foil start options are invalid.",
  "retryable": false,
  "fatal": true,
  "operation": "start",
  "details": {
    "fieldErrors": [{ "field": "publishableKey", "issue": "required" }]
  }
}
```

| Field | Type | Description |
| - | - | - |
| `code` | string | Stable, machine-readable identifier. Branch on this - see the [code reference](#error-codes) below. |
| `message` | string | Human-readable explanation. Safe to log; do not pattern-match. |
| `retryable` | boolean | Whether retrying the failing operation may succeed. |
| `fatal` | boolean | Whether the runtime is in a terminal state - further calls will reject with the same error. |
| `operation` | `'start' \| 'wait_for_fingerprint' \| 'get_session'` | Which method rejected. |
| `status` | number, optional | HTTP status from the Foil API when the cause was a server response. |
| `requestId` | string, optional | Foil request ID. Include verbatim in support tickets. |
| `details` | object, optional | Code-specific context, e.g. `details.fieldErrors` on validation failures. |

### Error codes

| Code | Operation | Retryable | Fatal | When it happens |
| - | - | - | - | - |
| `config.validation_failed` | `start` | no | yes | `publishableKey` is missing, uses the `sk_*` secret prefix, or doesn't match `pk_live_*` / `pk_test_*`, or `endpoint` isn't a valid HTTPS URL. `details.fieldErrors` lists the offending fields. |
| `config.already_initialized` | `start` | no | yes | `start()` was called a second time with a different publishable key or endpoint in the same page. |
| `runtime.bootstrap_failed` | any | no | yes | The WASM bundle failed to load, failed its integrity check at load time, or threw during bootstrap. Usually a network or CSP issue - see [Content Security Policy](https://usefoil.com/docs/content-security-policy.md). |
| `runtime.integrity_failed` | `start` | no | yes | The WASM integrity check failed. The bundle is tampered with or corrupted. |
| `runtime.unavailable` | any | no | yes | A client method was called before `start()` resolved, or after `destroy()`. |
| `runtime.start_failed` | `start` | yes | no | The runtime rejected during startup without a more specific code. The thrown `FoilError` carries the underlying error in its standard `cause` property. `cause` isn't included in `toJSON()` or in `onError` payloads. |
| `runtime.start_timeout` | `start` | yes | no | The runtime didn't signal ready within 10 seconds of visible time. Typically a stalled network request to the Foil API. |
| `runtime.fingerprint_failed` | `wait_for_fingerprint` | yes | no | Fingerprint resolution failed or didn't finish within 10 seconds of visible time. Foil doesn't score a session without a fingerprint, so `getSession()` can't succeed until a retry resolves it. |
| `runtime.session_failed` | `get_session` | yes | no | The session handoff call failed or didn't complete within 15 seconds of visible time. Retry once; if it fails again, fall back to your default policy. |
| `transport.upgrade_required` | any | no | yes from `start`, otherwise no | The Foil API rejected the request with HTTP 426 - the bundle on the page is too old. The user must reload to pick up a fresh `t.js`. |
| `transport.session_create_failed` | `start` | yes | no | The runtime couldn't create a session, usually because the network failed or Foil was unreachable. Call `start()` again to retry. |
| `transport.session_reset_required` | any | no | yes from `start`, otherwise no | The session can no longer continue, for example because it uses an outdated schema. Reload the page to start a new session. |
| `transport.fetch_failed` | `get_session`, `wait_for_fingerprint` | yes | no | The request to the Foil API failed after the runtime's own retries. |

The `code` values above are stable, and the SDK can add new codes within a category. Branch on `retryable` and `fatal` for control flow, and use the category prefix for logging. A rejection can also carry an error code from the Foil API itself, such as `auth.origin_not_allowed`; see [API errors](https://usefoil.com/docs/api-reference/errors.md) for those codes.

### Fallback policy

If Foil fails, your app should degrade gracefully. The pattern below treats any error that a retry can't fix as a skip - you get no signal, but the user can still complete the action.

```js theme={"dark"}
async function getFoilHandoff() {
  try {
    return await foil.getSession();
  } catch (err) {
    if (err.code === 'transport.upgrade_required') {
      // Bundle is stale; reload the page so a fresh t.js loads.
      window.location.reload();
      return null;
    }
    if (err.retryable) {
      try {
        return await foil.getSession();
      } catch {
        // fall through to skip
      }
    }
    // Report to your error tracker and continue without a handoff.
    reportError(err);
    return null;
  }
}

// On the server, a missing handoff means you have no Foil signal for
// this request - fall open or fall closed based on the sensitivity of
// the action. See Going to production for guidance.
```

For server-side error handling and the rest of the `FoilError` envelope as returned by the Foil API itself, see [API errors](https://usefoil.com/docs/api-reference/errors.md).

## Best practices

* **Start early** - initialize on page load, not at action time
* **Preload `t.js`** - add a `modulepreload` link to the page's `<head>` so the download starts while the page parses
* **Call `getSession()` late** - right before the sensitive action for the freshest signal data
* **Handle errors gracefully** - if the SDK fails, your app should still work (degrade to a fallback policy)
* **Don't expose verdicts client-side** - the browser API intentionally doesn't return them

## What's next

* [Server verification](https://usefoil.com/docs/server-verification.md) - verify the handoff on your backend
* [Pin a release](https://usefoil.com/docs/pin-a-release.md) - load one exact SDK release with its integrity hash and choose when to upgrade
* [Browser compatibility](https://usefoil.com/docs/browser-compatibility.md) - supported browsers and known differences
* [Quickstart](https://usefoil.com/docs/quickstart.md) - end-to-end integration in 5 minutes


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.