---

title: Web SDK
description: Reference for the browser agent (window.knownprint and @knownprint/web) and for @knownprint/sdk-js, which attaches a fresh request id to your forms.
---

This page is the reference for the browser side of knownprint:

- **The agent**: `load`, the `Agent` it returns (`identify`, `consent`, `forget`), `version` and `KnownprintError`. The script tag `/kp/agent.js` exposes it as `window.knownprint`, and `@knownprint/web` exports the same thing as an ES module.
- **`@knownprint/sdk-js`**: `createKnownprint`, a small layer over the agent whose `attach(form)` writes a fresh request id into a form before each submit.

:::note Coming
`@knownprint/web` and `@knownprint/sdk-js` are not published to npm yet: they come with the SDK release. The agent itself is available today through the script tag `/kp/agent.js`, which takes the same options and returns the same `Agent` described below. Setup is on [Add the browser agent](/install/browser), and a script-tag version of the form helper is on [Protect your forms](/install/forms).
:::

## Install

With the script tag (available now), the agent is `window.knownprint`:

```html
<script src="/kp/agent.js" defer></script>
```

With the packages (coming with the SDK release):

```bash
npm install @knownprint/web @knownprint/sdk-js
```

```js
import { load, KnownprintError } from '@knownprint/web';
import { createKnownprint } from '@knownprint/sdk-js';
```

Both packages are ES modules with TypeScript declarations. `@knownprint/web` has no dependencies and imports nothing at run time. `@knownprint/sdk-js` builds on `@knownprint/web`, which it installs with it.

Either way, the agent talks to `/kp/` on your own origin, which your proxy forwards to knownprint ([Run knownprint from your domain](/install/proxy)). If your site sends a Content Security Policy, see [Content Security Policy](/install/csp).

## The agent

### load(options)

```ts
function load(options: LoadOptions): Promise<Agent>;

interface LoadOptions {
  pk: string;
  endpoint?: string;
  profile?: 'full' | 'security';
  consent?: { mode: ConsentMode };
  linkedId?: string;
  tags?: Tags;
}

type ConsentMode = 'security_only' | 'consented' | 'blocked';
type Tags = Record<string, string | number | boolean>;
```

| Option     | Default                     | Rules                                                                                                                                                                                                                                                 |
| ---------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pk`       | required                    | Your public key: `pk_live_` or `pk_test_` followed by 32 characters from `a` to `z` and `2` to `7`. The page's origin must be in the key's allowed origins.                                                                                           |
| `endpoint` | `location.origin + '/kp'`   | Where your proxy serves knownprint. A path on your origin (`'/kp'`) or an `https://` URL. Plain `http://` is accepted only for `localhost`, `127.0.0.1` or `[::1]` on the page's own origin. No query, fragment, user name, `..` or `//` in the path. |
| `profile`  | `'full'`                    | `'full'` or `'security'`, a smaller collection for security use. See [Add the browser agent](/install/browser).                                                                                                                                       |
| `consent`  | `{ mode: 'security_only' }` | The consent mode the page starts in; see [consent(granted)](#consent-granted) and [Privacy](/privacy).                                                                                                                                                |
| `linkedId` | none                        | Your account id for the visitor, sent with every identification. At most 128 UTF-16 code units; an empty string counts as none.                                                                                                                       |
| `tags`     | none                        | Your own labels for the identifications: a plain object whose keys are non-empty (and not `__proto__`, `constructor` or `prototype`) and whose values are strings, finite numbers or booleans, under 4,096 bytes as compact JSON.                     |

`load` checks the options before any identification and before it touches any storage, and rejects with `KnownprintError` code `invalid_options` when one is wrong.

One page holds one agent. The first `load` fixes `pk`, `endpoint` and `profile`:

- A later `load` with the same three values resolves the same `Agent`.
- A later `load` with any of them different rejects with `invalid_options`.
- A later `load` with the same values and `consent: { mode: 'blocked' }` moves the agent to `blocked`, from any mode.
- A later `load` with `consent` `security_only` or `consented` does not change the mode; use [consent(granted)](#consent-granted) for that.

`linkedId` passed to `load` is sent by the page, so treat it as a hint. The account id you can rely on is the one your backend writes after verification ([Attach your account id](/install/server#attach-your-account-id)).

### identify(options)

```ts
interface Agent {
  identify(options?: IdentifyOptions): Promise<IdentifyResult>;
  consent(granted: boolean): Promise<void>;
  forget(): Promise<void>;
}

interface IdentifyOptions {
  linkedId?: string;
  tags?: Tags;
}

interface IdentifyResult {
  requestId: string;
  expiresAt: string;
}
```

Runs one identification and resolves with its request id. Call it at the moment the user acts (on submit, on a button press), not on page load: your backend accepts a request id for 10 seconds.

| Result field | Example                          | Meaning                                                                                                                         |
| ------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `requestId`  | `evt_6cgdjsd3qhozl3xuff7lpftxr4` | The id your backend exchanges for the event with `GET /v1/events/{request_id}`. Send it with the form or request it belongs to. |
| `expiresAt`  | `2026-06-01T14:03:37.412Z`       | An RFC 3339 time in UTC, 10 seconds after knownprint received the identification. Your backend should refuse the id after it.   |

`linkedId` and `tags` follow the rules of `load`. Given here, each replaces the value given to `load` for this identification (tags are replaced whole, not merged). Left out, the value given to `load` applies.

The page never receives the visitor id, the confidence or the signals: only your backend reads them ([Verify a request in your backend](/install/server)).

```js
// Once per page. Resolves null when the script is blocked or fails to load.
const agentReady = window.knownprint
  ? window.knownprint.load({ pk: 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }).catch(() => null)
  : Promise.resolve(null);

document.querySelector('#checkout').addEventListener('click', async () => {
  let requestId = null;
  try {
    const agent = await agentReady;
    if (agent !== null) ({ requestId } = await agent.identify({ tags: { step: 'checkout' } }));
  } catch (error) {
    // Go ahead without it: your backend treats a missing id as an unknown visit.
  }
  await fetch('/api/checkout', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ cart: cartId, kp_request_id: requestId }),
  });
});
```

### consent(granted)

Changes the agent's consent mode and resolves when done.

| Mode            | Meaning                                                                     |
| --------------- | --------------------------------------------------------------------------- |
| `security_only` | The default: collection for security purposes.                              |
| `consented`     | The visitor gave consent.                                                   |
| `blocked`       | Nothing is collected or sent. `identify` rejects with `collection_blocked`. |
- `consent(true)` sets `consented`, from any mode, `blocked` included.
- `consent(false)` moves `consented` back to `security_only`. It does not move any mode to `blocked`; to block, call `load` again with the same values and `consent: { mode: 'blocked' }`.
- A value other than `true` or `false` rejects with `invalid_options`.

An agent loaded `blocked` collects and sends nothing until `consent(true)`; `forget()` still works in that mode. Which mode to start in depends on your consent policy; see [Privacy](/privacy).

### forget()

Removes the token the agent stored in the browser's storage for your site. Resolves when it is done and never rejects. An identification asked for after `forget()` starts once the forgetting is done. Call it and expire knownprint's cookie from your server in the same flow.

Two things it does not do:

- It does not reach knownprint's first-party HttpOnly cookie, which identifications set through your proxy and which no script can read or remove. The cookie is named `kp_t` unless your account names another. A response of your own server expires it: `Set-Cookie: kp_t=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax` (with your account's cookie name if it names another) expires that cookie alone ([Forget this browser](/install/browser#forget-this-browser)), and `Clear-Site-Data: "cookies"` clears every cookie of your site, your session included, which suits a "sign out and forget this device" action.
- It does not delete anything knownprint holds. For that, delete the visitor from your backend ([Visitors](/visitors) and [Privacy](/privacy)).

```js
document.querySelector('#forget-device').addEventListener('click', async () => {
  const agent = await agentReady; // as in the identify example
  if (agent !== null) await agent.forget(); // never rejects
  // Then ask your server to expire the cookie, for example on a sign-out route.
  await fetch('/sign-out-and-forget', { method: 'POST' });
});
```

### version

```ts
const version: string;
```

The agent's version, as `window.knownprint.version` or the `version` export of `@knownprint/web`.

### KnownprintError

```ts
class KnownprintError extends Error {
  readonly code: KnownprintErrorCode;
  readonly status: number | null;
  readonly problem: string | null;
}

type KnownprintErrorCode =
  | 'invalid_options'
  | 'collection_blocked'
  | 'load_failed'
  | 'challenge_failed'
  | 'identify_failed'
  | 'network';
```

Every rejection of `load`, `identify` and `consent` is a `KnownprintError`, whose `name` is `'KnownprintError'`. Its message is `knownprint: <code>` and never holds a value from the page or the answer.

| Code                 | When                                                                                                                                                 | What to do                                                                      |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `invalid_options`    | An option of `load`, `identify` or `consent` is wrong, or a second `load` names another key, endpoint or profile.                                    | Fix the call.                                                                   |
| `collection_blocked` | `identify` was called while the consent mode is `blocked`.                                                                                           | Expected: send the form without a request id.                                   |
| `load_failed`        | The script tag's agent could not load its code (blocked by a content blocker or a policy, or not loaded within 10 seconds).                          | Send the form without a request id. Check your CSP and proxy if it is frequent. |
| `challenge_failed`   | knownprint refused to start the identification. `status` holds the HTTP status and `problem` the error slug, such as `origin_not_allowed`.           | Send the form without a request id. See [Errors](/api/errors) for the slug.     |
| `identify_failed`    | The identification was refused or could not complete. `status` and `problem` are set when knownprint answered with an error, such as `rate_limited`. | Send the form without a request id.                                             |
| `network`            | A request to your `/kp/` path failed without an answer.                                                                                              | Send the form without a request id.                                             |

A failed identification must never stop the user: send the form without the id and let your backend take its missing-id path ([Handle a missing request id](/install/server#handle-a-missing-request-id)).

## @knownprint/sdk-js

### createKnownprint(options)

```ts
function createKnownprint(options: CreateOptions): KnownprintBrowser;

interface CreateOptions extends LoadOptions {
  fireOn?: FireOn;
  agent?: AgentModule;
}

type FireOn = 'account_events' | 'page_views';

interface AgentModule {
  load(options: LoadOptions): Promise<Agent>;
}

interface KnownprintBrowser {
  identify(options?: IdentifyOptions): Promise<IdentifyResult>;
  consent(granted: boolean): Promise<void>;
  attach(form: HTMLFormElement, options?: { field?: string; timeoutMs?: number }): () => void;
  readonly fireOn: FireOn;
  readonly version: string;
}
```

`CreateOptions` is `LoadOptions` plus two members:

| Option   | Default            | Meaning                                                                                                                                                                                                  |
| -------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `agent`  | `@knownprint/web`  | The agent module to load. A page that uses the script tag passes `window.knownprint`.                                                                                                                    |
| `fireOn` | `'account_events'` | When the page identifies: on account events (signup, login, checkout and the like). `'account_events'` is the only value accepted for now; `'page_views'` or anything else throws a `TypeError` at once. |

Creating the client collects and sends nothing. It calls the agent's `load` once, lazily, on the first `identify`, `consent` or attached submit, with the `LoadOptions` members only. A `load` that rejects is not tried again: that call and every later one on the client reject with the same error (an attached form still submits, without a request id).

| Member                   | What it does                                                                                              |
| ------------------------ | --------------------------------------------------------------------------------------------------------- |
| `identify(options?)`     | The agent's `identify`: resolves `{ requestId, expiresAt }`.                                              |
| `consent(granted)`       | The agent's `consent`, unchanged.                                                                         |
| `attach(form, options?)` | Writes a fresh request id into `form` before each submit. Returns a function that detaches it. See below. |
| `fireOn`                 | The `fireOn` in force.                                                                                    |
| `version`                | The version of `@knownprint/sdk-js`.                                                                      |

The client does not expose `forget`; call it on the agent itself.

### attach(form, options)

```js
import { createKnownprint } from '@knownprint/sdk-js';

const kp = createKnownprint({
  pk: document.querySelector('[data-kp-pk]').dataset.kpPk,
  agent: window.knownprint, // when the page uses the script tag
});

for (const form of document.querySelectorAll('form[data-kp]')) kp.attach(form);
```

```html
<form method="post" action="/signup" data-kp>
  <input name="email" type="email" required>
  <button type="submit" name="plan" value="pro">Sign up</button>
</form>
```

| Option      | Default                             | Meaning                                                                          |
| ----------- | ----------------------------------- | -------------------------------------------------------------------------------- |
| `field`     | `'kp_request_id'` (`DEFAULT_FIELD`) | The name of the hidden input that carries the request id.                        |
| `timeoutMs` | `3000` (`DEFAULT_TIMEOUT_MS`)       | How long a submit waits for the identification before it goes ahead without one. |

On each submit, `attach`:

1. Stops the submit and runs `identify`, passing the form's `data-kp-linked-id` attribute as `linkedId` when it has one.
2. Writes the request id into the hidden input named `field`, creating it when the form has none.
3. Submits the form again with the same submit button, so the button's `name` and `value` are sent as usual. Only that one resubmission is let through.

If the identification fails, or does not finish within `timeoutMs`, the form is submitted without the field. An input left over from an earlier submit is removed, so a stale request id is never sent. A second submit while one is being identified is ignored. Every later submit is stopped again and gets its own fresh request id, which your backend accepts once.

`attach` handles native form submission. A form whose submit handler sends the data itself (with `fetch`, or a framework's own submit) should call `kp.identify()` in that handler instead and send `requestId` with its request, as in the [identify example](#identify-options).

The function `attach` returns removes the listener; a submit already being handled still goes ahead.

### Constants

| Export               | Value               | Meaning                                                           |
| -------------------- | ------------------- | ----------------------------------------------------------------- |
| `DEFAULT_FIELD`      | `'kp_request_id'`   | The default hidden field name.                                    |
| `DEFAULT_TIMEOUT_MS` | `3000`              | The default wait before a submit goes ahead without a request id. |
| `VERSION`            | the package version | Also `KnownprintBrowser.version`.                                 |

## Exports

| Package              | Values                                                               | Types                                                                                                                      |
| -------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `@knownprint/web`    | `load`, `version`, `KnownprintError`                                 | `Agent`, `ConsentMode`, `IdentifyOptions`, `IdentifyResult`, `Knownprint`, `KnownprintErrorCode`, `LoadOptions`, `Tags`    |
| `@knownprint/sdk-js` | `createKnownprint`, `VERSION`, `DEFAULT_FIELD`, `DEFAULT_TIMEOUT_MS` | `Agent`, `AgentModule`, `CreateOptions`, `FireOn`, `IdentifyOptions`, `IdentifyResult`, `KnownprintBrowser`, `LoadOptions` |

`Knownprint` is the type of the module itself (`{ version: string; load(options: LoadOptions): Promise<Agent> }`), which is also the shape of `window.knownprint`. The types `@knownprint/sdk-js` re-exports are those of `@knownprint/web`.
