---

title: Stop bots and scrapers
description: Block automated browsers on logins, searches, signups and one-time codes, rate-limit per browser instead of per address, and treat a missing request id as unknown.
---

## The threat

Scripts try leaked passwords by the thousand, open accounts in bulk, buy up limited stock, ask for text-message codes to numbers that earn their owner money, and scrape your prices and listings through your own search. Some call your endpoints directly; others drive a real browser so that they look like a person.

knownprint answers both. A script that skips your page sends no request id, so your backend knows it has nothing to trust. A script that drives a browser through your page gets a request id, and the event tells your backend that automation drove it, which tool when it is known, whether the browser is among the busiest on your site today, and whether the request came from a hosting network. Your code blocks, slows or challenges it, and rate-limits per browser instead of per address.

This guide covers where to identify, which fields to read, a decision table, a complete backend example with a short-lived pass for search, how to use webhooks and search for review, and the mistakes that let bots through.

## Where to identify

Identify on the actions bots are after, at the moment they happen:

| Moment                                               | What the bot wants                                                                           |
| ---------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| Login                                                | Credential stuffing: testing leaked passwords ([Account takeover](/guides/account-takeover)) |
| Signup                                               | Accounts in bulk ([Fake signups](/guides/fake-signups))                                      |
| Requesting a one-time code by SMS or voice           | Messages you pay for, sent to numbers the attacker profits from                              |
| Adding to cart, checkout, booking, reserving         | Limited stock, tickets and appointments                                                      |
| Search, listing pages behind a search, price lookups | Your catalogue and prices                                                                    |
| Posting, messaging, reviewing, voting                | Spam and fake engagement                                                                     |

For a one-off action (a login, a code, a checkout), identify right before it and send the request id with it. For a stream of requests (a search box, infinite scroll, a price API your page calls), identify once and exchange the request id for a short-lived pass of your own, then rate-limit each pass by its `visitor_id`. Your backend accepts a request id only within 10 seconds of the identification and only once, and one address may make 30 identifications a minute ([Limits](/limits)), so identifying on every search request is neither needed nor wise.

```js title="search.js"
// A blocked or failed script leaves the page working: the agent is then null.
const agentReady = window.knownprint
  ? window.knownprint.load({ pk: 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }).catch(() => null)
  : Promise.resolve(null);

async function requestId(action) {
  try {
    const agent = await agentReady;
    if (agent === null) return null;
    const timeout = new Promise((resolve) => setTimeout(() => resolve(null), 3000));
    const result = await Promise.race([agent.identify({ tags: { action } }), timeout]);
    return result === null ? null : result.requestId;
  } catch {
    return null; // blocked or failed: the backend decides what no request id means
  }
}

/** Searches with the current pass; on 401 gets a new pass and tries once more. */
async function search(query) {
  const url = `/search?q=${encodeURIComponent(query)}`;
  let res = await fetch(url);
  if (res.status === 401) {
    const pass = await fetch('/browser-pass', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ kp_request_id: await requestId('search') }),
    });
    if (!pass.ok) return { results: [], blocked: true };
    res = await fetch(url);
  }
  if (res.status === 401 || res.status === 403) return { results: [], blocked: true };
  if (res.status === 429) return { results: [], slowDown: true };
  if (!res.ok) throw new Error(`search answered ${res.status}`);
  return res.json();
}
```

[Add the browser agent](/install/browser) shows how to load the agent.

## Which fields to read

| Field                          | What it tells you                                                                                                                                                                                          | How to use it                                                                               |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `signals.bot.value`            | `bad` when automation drove the browser, `not_detected` when none was found                                                                                                                                | Block on `bad` ([Bots](/signals/bots))                                                      |
| `signals.bot.confidence`       | How sure the verdict is, from 0 to 1                                                                                                                                                                       | Logs and review; decide on `value`                                                          |
| `signals.bot.capped`           | True when the confidence is lowered for this kind of install; it is then at most 0.7 and the `value` is unchanged. Normal under the standard proxy rule                                                    | Nothing: decide on `value`                                                                  |
| `signals.bot.detail.bot_type`  | For a `bad` verdict, the kind of automation: `selenium`, `playwright`, `puppeteer`, `phantomjs`, `nightmare`, `stealth`, `crawler`, `headless_chromium`, `webdriver` or `automation` when no tool is named | Logs and review; `crawler` is a client that declared itself a bot                           |
| `signals.high_activity.value`  | The browser is among the busiest on your site today                                                                                                                                                        | With other signals, a scraper or a farm ([Activity](/signals/activity))                     |
| `signals.datacenter.value`     | The request came from a hosting or cloud network                                                                                                                                                           | Scripts run on servers; people rarely browse from one ([Network signals](/signals/network)) |
| `signals.ip_blocklist.value`   | The address is on a list of addresses known for abuse                                                                                                                                                      | Context, weighed in the suspect score                                                       |
| `signals.proxy`, `signals.tor` | The request came through a proxy or Tor                                                                                                                                                                    | Bots rotate through proxies to dodge address limits                                         |
| `signals.suspect_score.value`  | 0 to 100: how much of the visit's signals your site should worry about                                                                                                                                     | A threshold for a challenge ([Suspect score](/signals/suspect-score))                       |
| `integrity.replayed`           | This identification was sent before                                                                                                                                                                        | A bot replaying a captured request: block ([Integrity](/signals/integrity))                 |
| `visitor_id`                   | The browser                                                                                                                                                                                                | The key for your rate limits, in place of the address                                       |

`signals.bot` can be `null` when nothing could be read; treat it as unknown. A `not_detected` verdict means no automation was found, not that a person was proven: keep your rate limits on every browser.

knownprint can still update an event's `bot` signal and its suspect score for up to 30 minutes after the identification: the verdict can turn to `bad`, and a `bad` verdict never turns back. A later `GET /v1/events/{request_id}` shows the signals as they are then.

## Decision table

The thresholds are starting points to tune on your own traffic, not knownprint defaults. Rows are checked from the top; the first that applies decides.

| What you see                                                                             | Decision                                                                                |
| ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| The request id was used before, the event was replayed, or it was made on another origin | Block                                                                                   |
| `signals.bot.value` is `bad`                                                             | Block                                                                                   |
| No request id, the event is not found or stale, or knownprint did not answer             | Challenge, or refuse an action that costs you money (a text message, a reserved ticket) |
| This browser passed your per-browser rate limit for the action                           | Slow down: answer `429` for a while                                                     |
| `signals.datacenter.value` is true                                                       | Challenge                                                                               |
| `signals.high_activity.value` is true and the suspect score is 40 or more                | Challenge                                                                               |
| `signals.suspect_score.value` at or above 70                                             | Challenge                                                                               |
| None of the above                                                                        | Allow, and count the action against the browser                                         |

A challenge for a bot is a step that is cheap for a person and costly for a script: a puzzle you run, an email confirmation, a short wait. A blocked bot gets the same answer as any other refusal.

## Backend example

A complete Express server in Node 22 with Postgres, using the `knownprint.js` module from [Read and verify the event](/guides#read-and-verify-the-event). `POST /browser-pass` turns a request id into a pass valid for 10 minutes; `GET /search` requires a pass and limits each browser to 30 searches a minute; `POST /otp` identifies per code and sends nothing to a bot. The secret key needs `events:read`.

```js title="bots.js"
import express from 'express';
import session from 'express-session';
import { db, fired, readEvent, suspectScore } from './knownprint.js';
import { isBlockedBrowser } from './sweep.js';

const app = express();
app.use(express.json());
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));

// create table browser_actions (
//   visitor_id text not null,
//   action text not null,
//   created_at timestamptz not null default now()
// );
// create index on browser_actions (visitor_id, action, created_at);

const PASS_MS = 10 * 60_000;

/** The decision table above. The thresholds are examples to tune. */
function decide(result) {
  if (result.outcome === 'invalid') return { decision: 'block', why: result.reason };
  if (result.outcome === 'unknown') return { decision: 'challenge', why: result.reason };

  const { event } = result;
  const bot = event.signals?.bot;
  if (bot?.value === 'bad') {
    return { decision: 'block', why: `bot ${bot.detail?.bot_type ?? ''}`.trim() };
  }
  const score = suspectScore(event);
  if (score === null) return { decision: 'challenge', why: 'no_score' };
  if (fired(event, 'datacenter')) return { decision: 'challenge', why: 'datacenter' };
  if (fired(event, 'high_activity') && score >= 40) {
    return { decision: 'challenge', why: 'high_activity' };
  }
  if (score >= 70) return { decision: 'challenge', why: `suspect_score ${score}` };
  return { decision: 'allow', why: 'clean' };
}

/** Records the action and answers whether the browser is within `max` per minute. */
async function withinRate(visitorId, action, max) {
  const { rows } = await db.query(
    `select count(*) as n from browser_actions
      where visitor_id = $1 and action = $2 and created_at > now() - interval '1 minute'`,
    [visitorId, action],
  );
  if (Number(rows[0].n) >= max) return false;
  await db.query('insert into browser_actions (visitor_id, action) values ($1, $2)', [
    visitorId,
    action,
  ]);
  return true;
}

// Exchange a request id for a pass. A challenge here is your own puzzle or confirmation.
app.post('/browser-pass', async (req, res) => {
  const result = await readEvent(req.body.kp_request_id);
  const { decision, why } = decide(result);
  if (decision === 'block') return res.status(403).json({ ok: false });
  if (decision === 'challenge') return res.status(403).json({ ok: false, next: 'challenge', why });
  req.session.pass = { visitorId: result.event.visitor_id, until: Date.now() + PASS_MS };
  return res.json({ ok: true });
});

async function requirePass(req, res, next) {
  const pass = req.session.pass;
  if (!pass || pass.until < Date.now()) return res.status(401).json({ error: 'pass_required' });
  if (await isBlockedBrowser(pass.visitorId)) return res.status(403).end(); // sweep.js, below
  if (!(await withinRate(pass.visitorId, 'search', 30))) {
    return res.status(429).set('Retry-After', '60').end();
  }
  return next();
}

app.get('/search', requirePass, async (req, res) => {
  res.json(await runSearch(String(req.query.q ?? ''))); // your own search
});

// One request id per code: a bot or an unknown browser gets no text message.
app.post('/otp', async (req, res) => {
  const result = await readEvent(req.body.kp_request_id);
  const { decision } = decide(result);
  if (decision !== 'allow') return res.status(403).json({ ok: false, next: 'challenge' });
  if (!(await withinRate(result.event.visitor_id, 'otp', 3))) return res.status(429).end();
  await sendCode(req.body.phone); // your own
  return res.json({ ok: true });
});
```

`runSearch` and `sendCode` stand for your own code; `isBlockedBrowser` comes from `sweep.js` in the next section, which fills the list it reads. [Verify a request in your backend](/install/server) explains the checks in `readEvent`.

:::note Coming
The Node SDK wraps reading and verifying an event. It is coming with the SDK release; until then, call the routes directly as above. See [Node SDK](/sdks/node).
:::

## Catch late verdicts with search and webhooks

A pass is granted on the verdict at the time of the identification, and that verdict can turn to `bad` in the following 30 minutes. Sweep for it, and revoke the passes of the browsers it names:

```js title="sweep.js"
import { db, kp } from './knownprint.js';

// create table blocked_browsers (visitor_id text primary key, blocked_at timestamptz default now());

/** Every few minutes: the automated visits of the last hour, page by page. */
export async function sweepBots() {
  const start = new Date(Date.now() - 60 * 60_000).toISOString();
  let cursor = null;
  do {
    const params = new URLSearchParams({ bot: 'bad', start, limit: '500' });
    if (cursor !== null) params.set('cursor', cursor);
    const page = await kp(`/v1/events?${params}`);
    for (const event of page.data) {
      await db.query(
        'insert into blocked_browsers (visitor_id) values ($1) on conflict do nothing',
        [event.visitor_id],
      );
    }
    cursor = page.next_cursor;
  } while (cursor !== null);
}

export async function isBlockedBrowser(visitorId) {
  const r = await db.query('select 1 from blocked_browsers where visitor_id = $1', [visitorId]);
  return r.rowCount > 0;
}
```

Other searches serve an investigation: `GET /v1/events?ip=203.0.113.0/24&start=...&end=...` lists everything from one range during an attack, and `GET /v1/events?visitor_id=v_...` everything one browser did, including the visitors merged into it. Each page holds up to `limit` events (1 to 500, 50 by default); pass `next_cursor` back as `cursor` until it is `null`. See [Events API](/api/events).

A webhook on `event.identified` gives you each identification as it happens, which suits a live dashboard or an alert when `signals.bot.value` is `bad`. Its `data` is the event as it was at the identification, so a verdict that turns `bad` later reaches you only through a read or a search. Verify each delivery ([Verify a webhook](/webhooks/verify)); see [Webhooks](/webhooks).

When you confirm a bot that knownprint did not flag, or find a person among the flagged, label the event with `POST /v1/events/{request_id}/feedback` and `fraud` or `legit` ([Feedback](/feedback)).

## Pitfalls

- **Serving a protected endpoint without a request id.** A script that calls your endpoint directly never runs your page and never sends one. If the endpoint answers anyway, knownprint protects nothing. A missing request id is unknown, not a pass.
- **Reading `not_detected` as human.** It means no automation was found. Keep per-browser rate limits on every browser, flagged or not.
- **Rate-limiting per address.** Bots rotate through proxies and home lines, and a whole office or mobile carrier can share one address. Limit per `visitor_id`, and per address only as a backstop.
- **Reading `capped` as a weak verdict.** Under the standard proxy rule most verdicts carry `capped: true`. The cap lowers the confidence for that kind of install and leaves the `value` unchanged: decide on the `value`.
- **Treating `high_activity` as a bot.** Your most loyal customers are among your busiest browsers too. Use it with other signals.
- **Identifying on every request.** Request ids are one-time tickets and identifications have a per-address limit ([Limits](/limits)). Identify per action, or exchange one request id for a short pass as above.
- **Trusting the webhook copy for late verdicts.** The `event.identified` delivery is the event at the identification. Sweep with search, or read the event again, to catch a verdict that turned later.
- **Telling the bot why.** A specific error tells its author what to fix. Answer every refusal the same way.
- **Blocking crawlers you want.** A `crawler` verdict is a client that says it is a bot. If you welcome some, allow them by your own rules on public pages, where you would not identify anyway.

## Related pages

- [Guides](/guides): the decision pattern every guide follows.
- [Bots](/signals/bots): the bot signal in full.
- [Account takeover](/guides/account-takeover): credential stuffing at the login.
- [Fake signups](/guides/fake-signups): scripted signups.
- [Limits](/limits): rate limits for identifications and API calls.
