knownprintDocs

SDKs

Web SDK

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.

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):

Shell
npm install @knownprint/web @knownprint/sdk-js
JavaScript
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). If your site sends a Content Security Policy, see Content Security Policy.

The agent

load(options)

TypeScript
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>;
OptionDefaultRules
pkrequiredYour 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.
endpointlocation.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.
consent{ mode: 'security_only' }The consent mode the page starts in; see consent(granted) and Privacy.
linkedIdnoneYour account id for the visitor, sent with every identification. At most 128 UTF-16 code units; an empty string counts as none.
tagsnoneYour 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) 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).

identify(options)

TypeScript
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 fieldExampleMeaning
requestIdevt_6cgdjsd3qhozl3xuff7lpftxr4The id your backend exchanges for the event with GET /v1/events/{request_id}. Send it with the form or request it belongs to.
expiresAt2026-06-01T14:03:37.412ZAn 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).

JavaScript
// 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 }),
  });
});

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

ModeMeaning
security_onlyThe default: collection for security purposes.
consentedThe visitor gave consent.
blockedNothing 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.

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), 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 and Privacy).
JavaScript
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

TypeScript
const version: string;

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

KnownprintError

TypeScript
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.

CodeWhenWhat to do
invalid_optionsAn option of load, identify or consent is wrong, or a second load names another key, endpoint or profile.Fix the call.
collection_blockedidentify was called while the consent mode is blocked.Expected: send the form without a request id.
load_failedThe 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_failedknownprint 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 for the slug.
identify_failedThe 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.
networkA 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).

@knownprint/sdk-js

createKnownprint(options)

TypeScript
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:

OptionDefaultMeaning
agent@knownprint/webThe 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).

MemberWhat 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.
fireOnThe fireOn in force.
versionThe version of @knownprint/sdk-js.

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

attach(form, options)

JavaScript
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>
OptionDefaultMeaning
field'kp_request_id' (DEFAULT_FIELD)The name of the hidden input that carries the request id.
timeoutMs3000 (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.

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

Constants

ExportValueMeaning
DEFAULT_FIELD'kp_request_id'The default hidden field name.
DEFAULT_TIMEOUT_MS3000The default wait before a submit goes ahead without a request id.
VERSIONthe package versionAlso KnownprintBrowser.version.

Exports

PackageValuesTypes
@knownprint/webload, version, KnownprintErrorAgent, ConsentMode, IdentifyOptions, IdentifyResult, Knownprint, KnownprintErrorCode, LoadOptions, Tags
@knownprint/sdk-jscreateKnownprint, VERSION, DEFAULT_FIELD, DEFAULT_TIMEOUT_MSAgent, 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.