Install
Send the request id with a form
Put a fresh knownprint request id into each form submit with the browser SDK or by hand, with a time limit so no form waits on the agent.
Your backend needs the request id of the action it is deciding on. For a form, that means a hidden field holding a fresh request id on every submit. This page shows two ways to get there:
- The browser SDK,
@knownprint/sdk-js, whoseattach()does it for a form in one call. - By hand, with a few lines over the script tag agent: for forms that post the usual way, and for single page apps that send their own
fetch.
Both follow the same rules: a fresh request id per submit, the account id from the form, and a time limit after which the form goes ahead without a request id. Your backend treats a submit without one as unknown, not as a pass (Add the browser agent).
Set up the browser agent first; this page builds on it.
The browser SDK
@knownprint/sdk-js wraps the agent's load() and adds attach(), which writes a fresh request id into a form before each submit.
<script src="/kp/agent.js" defer></script>
<script src="/js/forms.bundle.js" defer></script>
<form id="signup" method="post" action="/signup" data-kp-linked-id="">
<input name="email" type="email" required>
<input name="password" type="password" required>
<button type="submit">Create account</button>
</form>import { createKnownprint } from '@knownprint/sdk-js';
const kp = createKnownprint({
pk: 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
agent: window.knownprint,
});
for (const form of document.querySelectorAll('form[data-kp-linked-id]')) {
kp.attach(form);
}Deferred scripts run in document order, so window.knownprint is in place by the time your bundle runs. Without the agent option the SDK uses the ES module agent @knownprint/web that it bundles, and you need no script tag. The SDK always bundles @knownprint/web, so where window.knownprint is missing (the script tag was blocked or failed), agent: window.knownprint is undefined and the client falls back to that bundled agent, with the same options.
createKnownprint
createKnownprint(options) returns a client. Creating it loads nothing and sends nothing: the agent is loaded once, on the first identify(), consent() or attached submit. A load that fails is not tried again: every later call rejects the same way until the page reloads, and attached forms go ahead without a request id.
| Option | Type | Default | Meaning |
|---|---|---|---|
pk | string | required | Your environment's public key. |
endpoint | string | location.origin + '/kp' | As in LoadOptions. |
profile | 'full' or 'security' | 'full' | As in LoadOptions. |
consent | { mode: ConsentMode } | { mode: 'security_only' } | As in LoadOptions. |
linkedId | string | none | As in LoadOptions.attach() passes the form's own value on each submit. |
tags | Tags | none | As in LoadOptions. |
fireOn | 'account_events' | 'account_events' | When the page identifies: at account events, which your code triggers. Any other value throws a TypeError. |
agent | { load(options): Promise<Agent> } | @knownprint/web | The agent to use. Pass window.knownprint on a page that loads /kp/agent.js. |
The agent receives only pk, endpoint, profile, consent, linkedId and tags.
The client
| Member | Type | Meaning |
|---|---|---|
identify(options?) | Promise<{ requestId, expiresAt }> | The agent's identify. |
consent(granted) | Promise<void> | The agent's consent, unchanged. |
attach(form, options?) | () => void | Intercepts the form's submits; returns a function that detaches it. |
fireOn | 'account_events' | The value it was created with. |
version | string | The SDK version. |
The SDK also exports DEFAULT_FIELD ('kp_request_id'), DEFAULT_TIMEOUT_MS (3000) and VERSION, and the types CreateOptions, KnownprintBrowser, AgentModule, FireOn, Agent, LoadOptions, IdentifyOptions and IdentifyResult.
The client has no forget(). To forget a browser, call it on the agent itself, window.knownprint.load(sameOptions) and then agent.forget(), when window.knownprint is defined, and expire knownprint's cookie from your server in the same flow (Forget this browser).
How attach works
attach(form, { field, timeoutMs }) listens for the form's submit event. On each submit:
- It stops the submit and calls
identify({ linkedId: form.dataset.kpLinkedId }). - When
identify()resolves, it writes the request id into the hidden input namedfield, creating it when the form has none. - It submits the form again with
form.requestSubmit(submitter), so the button the person pressed, with itsnameandvalue, is sent as before. That one submit goes through untouched.
If identify() rejects, or has not resolved after timeoutMs, the form is submitted without the field: an existing field of that name is removed, so a stale request id is never sent. The person is never kept waiting longer than timeoutMs.
| Option | Type | Default | Meaning |
|---|---|---|---|
field | string | 'kp_request_id' | The name of the hidden input that carries the request id. |
timeoutMs | number | 3000 | How long a submit waits for identify() before it goes ahead without a request id, in milliseconds. |
More behaviour you can rely on:
- A fresh request id on every submit. A second submit (after a validation error on your server, for example) is intercepted again and gets its own request id.
- No double submits from the SDK. A submit while the previous one is still being identified is stopped and starts nothing.
- Detach. The function
attach()returns removes the listener. A submit already intercepted still goes ahead.
The hidden field
With the defaults, your backend receives the request id as the form field kp_request_id:
email=ana%40example.com&password=...&kp_request_id=evt_3mzq7k2xw4hb6nfd5rtp2c7yjaTo use another name, pass field:
kp.attach(form, { field: 'fraud_check_id' });You can also put the input in your markup yourself; attach() fills an existing input with that name:
<input type="hidden" name="kp_request_id">data-kp-linked-id
The form's data-kp-linked-id attribute is the linkedId of each submit. Render your own account id into it where you know the account, for example on a checkout or a change of email:
<form method="post" action="/account/email" data-kp-linked-id="acct_81723">The attribute is read on every submit, so your code can set it just before the person submits:
form.dataset.kpLinkedId = currentAccountId;An empty attribute counts as not set, and the client's linkedId option is used. A value longer than 128 UTF-16 code units makes identify() reject, and the form goes ahead without a request id. Use an opaque account id, not an email address (Linked ids and tags).
The time limit
The first submit of a page also downloads the agent, unless the page loaded it earlier. To make the first submit faster, load the agent when the page opens with the same options; load() with the same options resolves the same agent, so the SDK reuses it:
window.knownprint?.load({ pk: 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }).catch(() => {});Lower timeoutMs where every second counts, raise it where a missing request id costs you more than a short wait. Whatever you choose, your backend must accept a submit without a request id as unknown.
What attach does not cover
attach() works with forms that the browser submits: a press of a submit button, Enter in a field, or your code calling form.requestSubmit(). It does not see:
form.submit()called from script, which fires nosubmitevent. Useform.requestSubmit()instead.- Forms whose submit your own JavaScript handles with
fetch, as most single page apps and frameworks do. Your handler runs on the first, stopped submit, sending without a request id, and again on the resubmit. Callidentify()in your handler instead, as in Single page apps and fetch, and do notattach()that form.
attach() resubmits with form.requestSubmit(), which every current browser has.
By hand, for a form that posts
The same flow over the script tag agent, with no package:
<script src="/kp/agent.js" defer></script>
<script src="/js/forms.js" defer></script>const PUBLIC_KEY = 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const FIELD = 'kp_request_id';
const TIMEOUT_MS = 3000;
// Resolves the value, or null on a rejection or after `ms`.
function withTimeout(promise, ms) {
return new Promise((resolve) => {
const timer = setTimeout(() => resolve(null), ms);
promise.then(
(value) => {
clearTimeout(timer);
resolve(value);
},
() => {
clearTimeout(timer);
resolve(null);
},
);
});
}
function requestIdFor(linkedId) {
if (!window.knownprint) return Promise.resolve(null);
const attempt = window.knownprint
.load({ pk: PUBLIC_KEY })
.then((agent) => agent.identify({ linkedId }))
.then((result) => result.requestId);
return withTimeout(attempt, TIMEOUT_MS);
}
function attach(form) {
let passing = false;
let inFlight = false;
form.addEventListener('submit', async (event) => {
if (passing) return;
event.preventDefault();
if (inFlight) return;
inFlight = true;
const submitter = event.submitter;
const requestId = await requestIdFor(form.dataset.kpLinkedId || undefined);
let input = form.querySelector(`input[name="${FIELD}"]`);
if (requestId === null) {
if (input) input.remove();
} else {
if (!input) {
input = document.createElement('input');
input.type = 'hidden';
input.name = FIELD;
form.appendChild(input);
}
input.value = requestId;
}
inFlight = false;
passing = true;
try {
form.requestSubmit(submitter);
} finally {
passing = false;
}
});
}
document.querySelectorAll('form[data-kp-linked-id]').forEach(attach);
// Load the agent early so the first submit is quick.
window.knownprint?.load({ pk: PUBLIC_KEY }).catch(() => {});requestSubmit() fires the submit event at once, inside the call, so the passing flag lets exactly that submit through.
Single page apps and fetch
When your own code sends the form with fetch, call identify() in your submit handler and put the request id into the body you send. The same time limit applies:
async function onSignup(event) {
event.preventDefault();
const form = event.currentTarget;
const requestId = await requestIdFor(); // the helper above: null when there is none
const response = await fetch('/api/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: form.elements.email.value,
password: form.elements.password.value,
kp_request_id: requestId,
}),
});
// Handle the response as usual.
}
document.querySelector('#signup').addEventListener('submit', onSignup);The name kp_request_id is only a convention: send the request id in whatever field or header your backend reads. Keeping one name for forms and fetch makes the backend simpler.
In React, Vue or similar, call the same helper in the submit handler of your component. Get a new request id for each submit; never reuse one from an earlier action or keep one in app state.
Read it in your backend
Your backend reads the field, checks its shape, and fetches the event with your secret key. A sketch in Node with Express:
const REQUEST_ID = /^evt_[a-z2-7]{26}$/;
app.post('/signup', express.urlencoded({ extended: false }), async (req, res) => {
const requestId = req.body.kp_request_id;
let event = null;
if (typeof requestId === 'string' && REQUEST_ID.test(requestId)) {
const response = await fetch(`${process.env.KNOWNPRINT_API}/v1/events/${requestId}`, {
headers: { Authorization: `Bearer ${process.env.KNOWNPRINT_SECRET_KEY}` },
});
if (response.ok) event = await response.json();
else if (response.status !== 404 && response.status !== 409) {
// Not a missing event: a key, scope or rate problem, or knownprint failing. Log it.
console.warn('knownprint read failed:', response.status);
}
}
if (event === null) {
// Unknown: no request id, a malformed one, one knownprint does not know, or a failed read.
// Decide what unknown means for signups, for example email verification first.
}
// Otherwise decide on the event's visitor and signals.
});The address of the API comes with your account. Verify in your backend covers what to check on the event and how to decide.