Install
Add the browser agent
Load the knownprint agent with one script tag, call identify at each account event, and send the request id to your backend.
The browser agent is a small script your page loads from your own origin. At each account event (a signup, a login, a checkout, a password reset) your code calls identify(), which resolves a request id. Your page sends the request id to your backend with the action, and your backend reads the full result with its secret key.
The page never sees the visitor id, the confidence or any signal. There is nothing in the page for a visitor to tamper with: the answer lives only on your server.
Before you start
You need three things in place:
- The proxy rule. Your web server or CDN forwards the path
/kp/on your site to knownprint. The agent's script and its identification requests go through that path. Set it up first with the proxy rule for nginx, Caddy or Cloudflare. - Your public key. Each environment has a public key of the form
pk_live_orpk_test_followed by 32 characters. It is safe to put in page source. Keys come with your account; knownprint is in early access (Get early access at https://knownprint.com). - Your origins on the key. knownprint accepts identifications only from the origins listed on the key, compared exactly: scheme, host and port. List every origin that loads the agent, for example both
https://example.comandhttps://www.example.com. See API keys.
Add the script tag
Load the agent from your knownprint path, then run your own code after it:
<script src="/kp/agent.js" defer></script>
<script src="/js/account.js" defer></script>Deferred scripts run in document order, so window.knownprint exists by the time account.js runs, unless the agent's script failed to load (a content blocker, a network error). Your code must handle that case: see No request id means unknown.
/kp/agent.js is a small loader. It defines window.knownprint with two members:
| Member | Type | Meaning |
|---|---|---|
version | string | The agent version. |
load(options) | (options: LoadOptions) => Promise<Agent> | Validates the options, downloads the agent itself and resolves the page's Agent. |
On the first load() the loader downloads the agent from a file under {endpoint}/a/, with a subresource integrity check. A copy that was changed on the way (by a proxy or CDN that minifies, rewrites or injects into scripts) is refused and load() rejects with load_failed. Make sure nothing between your visitors and knownprint rewrites responses under /kp/.
The loader is cached by browsers for up to an hour; the agent files carry their build in their name and are cached for a year. Do not give /kp/agent.js a longer cache lifetime in your CDN.
If your application bundles its own JavaScript, the same agent will also come as an ES module, @knownprint/web, with the SDK release; see the web SDK. Until then, use the script tag.
Load the agent
Call load() once per page, as early as you like. It resolves the Agent you call identify() on.
const PUBLIC_KEY = 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
let agentPromise = null;
function getAgent() {
if (!window.knownprint) {
return Promise.reject(new Error('knownprint agent script not loaded'));
}
if (agentPromise === null) {
// A failed load stays failed until the page reloads: identify() calls then
// reject, and each action goes ahead without a request id.
agentPromise = window.knownprint.load({ pk: PUBLIC_KEY });
}
return agentPromise;
}LoadOptions
| Member | Type | Default | Meaning |
|---|---|---|---|
pk | string | required | Your environment's public key: pk_live_ or pk_test_ followed by 32 characters from a to z and 2 to 7. |
endpoint | string | location.origin + '/kp' | Where your proxy rule forwards to knownprint. See The endpoint. |
profile | 'full' or 'security' | 'full' | Which agent the page runs. See Profiles. |
consent | { mode: ConsentMode } | { mode: 'security_only' } | The consent mode: 'security_only', 'consented' or 'blocked'. See Consent modes. |
linkedId | string | none | Your own id for the account, sent with every identification from this page unless identify() passes its own. At most 128 UTF-16 code units; an empty string counts as not set. |
tags | Tags | none | Your own labels, sent with every identification from this page unless identify() passes its own. See Linked ids and tags. |
Tags is Record<string, string | number | boolean>.
Every option is checked before anything is sent to knownprint. A value that breaks a rule rejects with invalid_options. Under the script tag, pk, endpoint, profile and consent are checked before the agent is downloaded, and a load() refused for one of them can be called again with corrected options. linkedId and tags are checked once the agent has arrived; a first load() refused for them, or one that failed with load_failed, leaves the page's agent failed until the page reloads. Test your options in development, where these rejections show at once.
One agent per page
A page has one agent. The first load() fixes its public key, endpoint and profile:
- A later
load()with the samepk,endpointandprofileresolves the sameAgent. You can callload()from several places in your code without loading twice. - A later
load()with a differentpk,endpointorprofilerejects withinvalid_options. To switch, the page must reload. - A later
load()never changes thelinkedIdortagsof the first. Pass them toidentify()instead. - A later
load()whose consent mode is'blocked'moves the agent toblocked. A laterload()with'security_only'or'consented'leaves the mode as it is; useagent.consent()to change it.
The endpoint
Leave endpoint unset when your proxy rule forwards /kp/ on the page's own origin, which is the usual setup. Set it when your rule uses another path:
// In getAgent() above:
agentPromise = window.knownprint.load({ pk: PUBLIC_KEY, endpoint: '/fraud-check' });The script tag then loads /fraud-check/agent.js, and every request of the agent goes under /fraud-check/.
The endpoint must be a path that starts with /, or an https: URL. An http: URL is accepted only on the page's own origin and only on localhost, 127.0.0.1 or [::1], for local development. It may not hold a user name or password, a query (?), a fragment (#), a backslash, .. or //. Keep it on the page's own origin: an https: URL on another origin passes the check but does not work, because knownprint's answers carry no cross-origin (CORS) headers. A page served from file: or a sandboxed frame has no origin to default to, so load() without an endpoint rejects there with invalid_options.
Identify an account event
Call identify() at the moment of the action you want to check, and send the request id with that action:
async function getRequestId(linkedId = undefined) {
try {
const agent = await getAgent();
const { requestId } = await agent.identify({ linkedId });
return requestId;
} catch (err) {
// Blocked, offline or refused: the action goes ahead without a request id,
// and your backend treats it as unknown.
return null;
}
}
document.querySelector('#login-form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = event.currentTarget;
const email = form.elements.email.value;
const requestId = await getRequestId();
await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email,
password: form.elements.password.value,
kp_request_id: requestId,
}),
});
});For a form that posts the usual way, without your own fetch, Forms shows how to write the request id into a hidden field, with a time limit so the form never waits too long.
IdentifyOptions
| Member | Type | Default | Meaning |
|---|---|---|---|
linkedId | string | the load() value | Your id for the account this action is about. Replaces the load() value for this identification. Same rules as in LoadOptions. |
tags | Tags | the load() value | Your labels for this identification. Replaces the load() tags whole; the two are never merged. |
IdentifyResult
identify() resolves { requestId, expiresAt }:
{
"requestId": "evt_3mzq7k2xw4hb6nfd5rtp2c7yja",
"expiresAt": "2026-01-15T09:30:12.418Z"
}| Field | Type | Meaning |
|---|---|---|
requestId | string | The id of this identification: evt_ followed by 26 characters. Your backend reads the result with it from GET /v1/events/{request_id} (Verify in your backend). |
expiresAt | string | An RFC 3339 timestamp in UTC, 10 seconds after knownprint received the identification. A request id is meant to travel to your backend with the action it was made for, straight away. |
The event stays readable from your backend after expiresAt, for as long as knownprint keeps events (Limits and retention). Use each request id for one action only: call identify() again for the next action, even on the same page.
How identify behaves
- Calls are queued. Two
identify()calls at once run one after the other, and each resolves its own request id. - The agent caps its own work at a few seconds, so
identify()does not hang on a slow device. Network time comes on top. Put your own time limit around it where a person is waiting, as Forms does. - In a page that the browser is prerendering,
identify()waits until the page is shown. - The agent sends nothing of your page's query string, fragment or title, or of data your site stores in the browser. knownprint records the page's origin and its path. Your proxy rule passes only knownprint's own cookie on to knownprint.
- After
identify()resolves, the agent may send a few small follow-up requests under your endpoint that belong to the same identification. Your proxy rule forwards them like the rest.
When to call identify
Call identify() at account events: the moments where a fraud decision is made on your server. Typical ones:
| Event | Why |
|---|---|
| Signup | Spot the same browser opening many accounts. See Fake signups. |
| Login | Spot a new browser on a known account, or one browser trying many accounts. See Account takeover. |
| Checkout and payment | Spot card testing and repeat chargebacks from one browser. See Payment fraud. |
| Password reset and email change | Spot takeover attempts that go through recovery. |
| Promo code or free trial redemption | Spot the same browser coming back for the same offer. See Promo abuse. |
| Posting, messaging, withdrawals | Any action you would want to stop or review. |
Call it when the person acts (on submit or on click), not when the page loads. Each call is one identification; calling on every page view only adds identifications your backend never reads.
Linked ids and tags
linkedId ties an identification to an account of yours. Pass your own stable, opaque account id (a database id), not an email address or a name. knownprint records it on the event as linked_id and uses it to show you which browsers each account used and which accounts each browser touched: see Accounts. Before login you may not know the account; pass the account the person is trying to use (for example the one a login form names, after your backend looks it up) or leave it out. Your backend can also write the account onto the event afterwards, once it knows which account acted: see Attach your account id.
Rules: a string of at most 128 UTF-16 code units, with no lone surrogate. An empty string counts as not set.
tags are your own labels, recorded on the event as tags: the kind of action, a plan, an order value, an experiment. They help you search and filter events later.
await agent.identify({
linkedId: 'acct_81723',
tags: { action: 'checkout', cart_value: 129.5, first_order: true },
});Rules for tags:
- A plain object (not an array, not a class instance).
- Keys are non-empty strings;
__proto__,constructorandprototypeare refused. - Keys and string values hold no lone surrogate.
- Values are strings, finite numbers or booleans. Nested objects, arrays,
nullandundefinedare refused. - The whole object, serialised as JSON, stays under 4,096 bytes of UTF-8.
Do not put personal data in tags. A tags object that breaks a rule rejects with invalid_options.
Single page apps
In a single page app the page loads once and the routes change in place. The agent fits that:
- Call
load()once, when your app starts, and keep the resolvedAgent(thegetAgent()helper above does this). Callingload()again with the same options is harmless. - Call
identify()at each account event, not on each route change. - Pass the account in each
identify()call rather than inload(): the account changes when a person logs in, logs out or switches accounts, while the options of the firstload()stay fixed for the life of the page. - Get a fresh request id for each action. A request id from the login does not cover the checkout five minutes later.
- If your app server-renders pages and hydrates them, call
load()only in the browser.
import { useCallback } from 'react';
const PUBLIC_KEY = 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
export function useRequestId() {
return useCallback(async (linkedId) => {
if (!window.knownprint) return null;
try {
const agent = await window.knownprint.load({ pk: PUBLIC_KEY });
const { requestId } = await agent.identify({ linkedId });
return requestId;
} catch {
return null;
}
}, []);
}Forms shows the same pattern with a time limit around identify().
Profiles
The profile option picks which agent the page runs. Choose it once per page.
| Profile | What you get |
|---|---|
full (default) | The complete agent. It recognises returning browsers most reliably and gives every signal its full detail. Use it unless you have a reason not to. |
security | A smaller agent that does less work in the browser. Results are less complete: returning browsers are recognised less reliably than with full. |
Every event records the profile it was made with, as profile. Both profiles honour every consent mode.
Consent modes
The consent mode tells the agent what the visitor allowed. Set it in load() and change it later with agent.consent().
| Mode | Behaviour |
|---|---|
security_only (default) | The agent identifies for fraud prevention and security. |
consented | The same, recorded as consented. Set it when the visitor agreed through your consent banner. |
blocked | The agent collects nothing and sends nothing. Under the script tag it does not even download the agent. identify() rejects with collection_blocked. |
Changing the mode
agent.consent(granted) takes a boolean and resolves when the mode has changed:
| Call | From | To |
|---|---|---|
consent(true) | any mode, blocked included | consented |
consent(false) | consented | security_only |
consent(false) | security_only or blocked | unchanged |
A value other than true or false rejects with invalid_options.
To stop the agent after it started, for example when a visitor objects in the middle of a visit, call load() again with the same pk, endpoint and profile and consent: { mode: 'blocked' }. From then on nothing is collected or sent until consent(true).
async function setConsent(granted) {
try {
const agent = await getAgent();
await agent.consent(granted);
} catch {
// The agent did not load: nothing is collected, so there is nothing to change.
}
}
// The visitor accepted in your consent banner.
acceptButton.addEventListener('click', () => setConsent(true));
// The visitor withdrew consent for anything beyond security.
withdrawButton.addEventListener('click', () => setConsent(false));
// The visitor objected to processing altogether.
objectButton.addEventListener('click', () => {
if (window.knownprint) {
window.knownprint.load({ pk: PUBLIC_KEY, consent: { mode: 'blocked' } }).catch(() => {});
}
});What knownprint records
Each event's consent block records:
| Field | Meaning |
|---|---|
consent.mode | The mode the page set. |
consent.gpc | True when the browser sends Global Privacy Control. |
consent.tcf_purpose1 | Purpose 1 consent from an IAB TCF v2 consent platform on the page: true or false, or null where there is no such platform, GDPR does not apply, or the platform did not answer in time. |
consent.effective_mode | The mode knownprint processed the event under. Today every event is processed as security_only. |
Global Privacy Control and TCF are recorded only; they never change the mode or what the agent does. Your page decides the mode. For what each mode means for your privacy notice, see Privacy.
Forget this browser
agent.forget() removes knownprint's storage token from the browser's storage. Use it when a visitor asks you to forget their browser, for example from a privacy settings page, and expire knownprint's cookie from your server in the same flow.
forgetButton.addEventListener('click', async () => {
try {
const agent = await getAgent();
await agent.forget(); // never rejects
} catch {
// The agent did not load: there is nothing of it to remove in this page.
}
// Then expire the cookie from your server, as below.
await fetch('/account/forget-browser', { method: 'POST' });
});- It works in every consent mode,
blockedincluded. - It resolves when it is done. It never rejects.
- An
identify()called beforeforget()keeps nothing it receives. One called after waits untilforget()is done.
What it does not reach:
- The cookie. knownprint also stores the token in a first-party HttpOnly cookie, set on your site's host through your knownprint path and named
kp_tunless your account names another. No script can remove an HttpOnly cookie, so expire it from your server in the same flow:Set-Cookie: kp_t=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax, with your account's cookie name in place ofkp_tif it names another. - Other open tabs of your site, until they reload.
- Data on knownprint's servers. To erase what knownprint holds about a visitor, delete the visitor through the API: see Visitors API.
Errors
Every rejection from load(), identify() and consent() is a KnownprintError, whose message is knownprint: <code>:
| Property | Type | Meaning |
|---|---|---|
name | string | Always 'KnownprintError'. |
code | KnownprintErrorCode | One of the six codes below. |
status | number or null | The HTTP status, for challenge_failed and identify_failed. |
problem | string or null | The knownprint problem type (for example origin_not_allowed) when the server sent one. |
window.knownprint does not expose the class, so check err.name:
try {
const { requestId } = await agent.identify();
} catch (err) {
if (err && err.name === 'KnownprintError') {
console.warn('knownprint', err.code, err.status, err.problem);
}
}Error codes
| Code | When | What to do |
|---|---|---|
invalid_options | An option breaks a rule; a second load() names another pk, endpoint or profile; consent() got a non-boolean. | A bug in your page. Fix the call; do not retry. |
collection_blocked | identify() while the consent mode is blocked. | Expected. Send the action without a request id. |
load_failed | The agent could not be downloaded: blocked by a content blocker or your Content Security Policy, a network error, a failed integrity check, or no answer within 10 seconds. Only the script tag loader raises it, from load(), or from the first identify() or consent(true) after a load() in blocked mode. | Send the action without a request id. If it happens for everyone, check your proxy rule and Content Security Policy. |
challenge_failed | knownprint refused to start the identification, or answered something the agent could not read. status and problem say why. | See the problem table below. |
identify_failed | knownprint refused the identification or its answer could not be read. status and problem say why. | See the problem table below. |
network | A request did not reach knownprint: offline, blocked, or refused by the page's policy. | Send the action without a request id. You may retry once. |
Problem types
When knownprint refuses a request, problem names the reason. The common ones:
problem | status | Meaning | What to do |
|---|---|---|---|
unauthorized | 401 | knownprint does not recognise the public key. | Check pk against your account. |
origin_not_allowed | 403 | The page's origin is not on the key's allowed origins. | Add the exact origin to the key (API keys). |
ip_not_allowed | 403 | The key's allowed IP ranges exclude the address knownprint saw, often your server's own when the proxy rule sends no valid proxy secret. | Check the proxy rule and the key's IP ranges. |
rate_limited | 429 | Too many requests from this address or for this key, or your daily limit is reached. | Send the action without a request id; do not retry in a loop. See Limits. |
build_inactive | 400 | The page runs an agent build knownprint no longer accepts, usually a page left open across an agent update. | A reload fixes it. |
token_expired, invalid_token, nonce_reused | 401, 409 | The short-lived permission to identify had expired or was already used, often after a laptop slept. | Call identify() once more. |
schema_mismatch, field_map_mismatch, validation_failed, payload_too_large | 400, 422, 413 | The request did not arrive as the agent sent it. | Check that nothing rewrites request bodies under /kp/. |
The full list is in Errors.
Retrying
A person is waiting, so keep retries short: at most one retry for network, token_expired, invalid_token and nonce_reused, then go ahead without a request id. Never retry invalid_options, collection_blocked, load_failed, origin_not_allowed or unauthorized: the same call fails the same way until the page or your configuration changes.
No request id means unknown
Some browsers never give you a request id: a content blocker stops the script, the network fails, the visitor refused consent, or a script sends your form directly. A fraudster can also remove the agent on purpose.
Your backend must treat a missing, malformed or unknown request id as unknown, not as a pass. Decide in your backend what unknown means for each action: let a login through with a second factor, hold a payout for review, ask for email verification on signup. Never let the browser decide; it can say anything. Verify in your backend shows the server side.
Browser support
The agent runs in current versions of Chrome, Edge, Firefox, Safari and other Chromium browsers, on desktop and on mobile. It is built to the ES2017 language level. In a browser that cannot run it, window.knownprint is missing or load() rejects, and you get no request id: treat that as unknown, as above.
The agent also runs in private windows and in browsers that block storage.
TypeScript
The script tag gives you no type declarations. Declare the parts you use:
type ConsentMode = 'security_only' | 'consented' | 'blocked';
type Tags = Record<string, string | number | boolean>;
interface KnownprintAgent {
identify(options?: { linkedId?: string; tags?: Tags }): Promise<{
requestId: string;
expiresAt: string;
}>;
consent(granted: boolean): Promise<void>;
forget(): Promise<void>;
}
interface Window {
knownprint?: {
version: string;
load(options: {
pk: string;
endpoint?: string;
profile?: 'full' | 'security';
consent?: { mode: ConsentMode };
linkedId?: string;
tags?: Tags;
}): Promise<KnownprintAgent>;
};
}Next steps
- Forms: put the request id into a form, with a time limit.
- Content Security Policy: the directives the agent needs.
- Verify in your backend: read the event and decide.
- Go live: the checklist before production traffic.