Korzen
Bot Protection
In these docs

Fastify and NestJS

Bot Protection in Fastify or NestJS: the tag, the client file, a preHandler hook in Fastify, the Express middleware in NestJS, and the visitor's IP.

This guide is for Fastify 5, and NestJS 12 as nest new makes it (an ES module project on Express), on Node 22 or later, with the client the Express guide uses: the npm package @korzen/bot-protection, with no dependencies, that asks /v1/decide, gives up at your timeout and lets the visitor through on any error.

Run Node 22.23.4, 24.22.1 or 26.12.1, or a later release of the same line. Earlier releases carry CVE-2026-111497, a flaw in the Brotli decoder that fetch and node:zlib use: malformed compressed data can corrupt the process's memory. Node 20, 23 and 25 get no fix.

Payment, login and sign-up routes: turn on protectedAction ("protected_action": true in the call), so a script that never loads your page cannot take the action. Protecting a checkout

The tag

Put the tag in the <head> of the layout that renders your sign-up, sign-in and checkout pages:

<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>

In the page, before the form is sent, call await window.korzen?.ready(): it reports what the visitor did since the tag last reported, and resolves within a few seconds whatever happens. The tag

For visitors whose network blocks Korzen's host, firstParty: true on NestJS's protect, or a Cloudflare Worker in front of Fastify, serves the tag and its beacon from your own domain. First-party mode

The call

Behind Cloudflare? A Worker can do this without changing your app. Cloudflare Workers

Install the client:

npm install @korzen/bot-protection

Node's fetch closes a connection after 4 seconds idle; an undici Agent with a longer keepAliveTimeout, passed as dispatcher, keeps it open (see Express for why undici 7).

Fastify

A preHandler hook on the route that creates the account. It keeps the answer on request.korzen, or null when there is none. fromNodeRequest(request.raw) reads Node's own request, so the call carries the order the headers came in:

// app.js
import Fastify from "fastify";
import formbody from "@fastify/formbody";
import { Agent } from "undici"; // optional (npm install undici@7): keeps the connection open between calls
import { createClient, fromNodeRequest } from "@korzen/bot-protection";

// The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
const korzen = createClient({ apiKey: process.env.KORZEN_API_KEY, url: "https://eu.korzen.dev", timeoutMs: 200, dispatcher: new Agent({ keepAliveTimeout: 300_000 }) });
const app = Fastify({ trustProxy: "loopback,uniquelocal" }); // your proxy on a private network: see "The visitor's IP"
app.decorateRequest("korzen", null);
await app.register(formbody);

// Asks before the handler, and keeps the answer on request.korzen (null when there is none).
async function guard(request, reply) {
  request.korzen = await korzen.decide(fromNodeRequest(request.raw, { ip: request.ip, protectedAction: true }));
  if (request.korzen?.action === "block") return reply.code(400).send("We could not create your account.");
}

app.post("/signup", { preHandler: guard }, async (request, reply) => {
  const user = await createAccount(request.body); // your own code
  await saveRequestID(user.id, request.korzen?.request_id); // see "Apply the action"
  return reply.redirect("/welcome", 303);
});

await app.listen({ port: 3000 });

NestJS

NestJS runs on Express, so protect, the client's Express middleware, guards the route in main.ts:

// src/main.ts
import { NestFactory } from "@nestjs/core";
import type { NestExpressApplication } from "@nestjs/platform-express";
import { Agent } from "undici"; // optional (npm install undici@7): keeps the connection open between calls
import { AppModule } from "./app.module.js";
import { createClient, protect } from "@korzen/bot-protection";

// The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
const korzen = createClient({ apiKey: process.env.KORZEN_API_KEY!, url: "https://eu.korzen.dev", timeoutMs: 200, dispatcher: new Agent({ keepAliveTimeout: 300_000 }) });

const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.set("trust proxy", 1); // one proxy of yours in front: see "The visitor's IP"
// Asks before every route under /signup; the answer is on req.korzen, or null when there is none.
app.use("/signup", protect({
  client: korzen,
  ip: (_get, req) => req.ip, // with "trust proxy" set
  protectedAction: true, // sign-up, login and payment: a script that never loaded your page holds no token; a page load spends none
  onBlock: (_req, res) => res.status(400).send("We could not create your account."),
}));
await app.listen(process.env.PORT ?? 3000);

Then, in the controller, the answer is on the request:

// src/signup.controller.ts
import { Body, Controller, Get, Post, Redirect, Req } from "@nestjs/common";
import type { Request } from "express";
import type { Decision } from "@korzen/bot-protection";

@Controller("signup")
export class SignupController {
  @Get()
  form() {
    return renderSignupForm(); // your own code
  }

  @Post()
  @Redirect("/welcome", 303)
  async create(@Req() req: Request & { korzen?: Decision | null }, @Body() body: Record<string, string>) {
    const user = await createAccount(body); // your own code
    await saveRequestID(user.id, req.korzen?.request_id); // see "Apply the action"
  }
}

The visitor's IP

Fastify reads X-Forwarded-For only from the proxies trustProxy names, by address or network: "loopback,uniquelocal" trusts a proxy on this machine or on a private network (10.x, 172.16–31.x, 192.168.x, fc00::/7), and request.ip is then the entry that proxy added. Fastify 5 takes no number of hops: a number trusts nothing. true trusts every entry, the first of which the visitor writes. In NestJS on Express, trust proxy is the number of proxies in front, as in the Express guide. Behind Cloudflare, read CF-Connecting-IP (ipFrom.cloudflare), if your server only takes traffic from Cloudflare.

Apply the action

Read only action. On block, answer with the same error the action shows when it fails for any other reason, so a bot learns nothing. The account starts in monitor mode, where action is always allow: nothing changes for visitors until you turn on block mode.

Keep the answer's request_id with what the action created, such as the account or the order: it names that decision when you ask us about it. The answer

Test it on your machine

Run your server with node --env-file=.env app.js (in NestJS, npm run start:dev) and open it on localhost. Pages on localhost always accept the tag and are never listed as a domain. Locally the IP is 127.0.0.1 or ::1, and that is fine.

  1. Set KORZEN_API_KEY in .env and open the sign-up page. In the browser's developer tools, the _kz cookie appears after a few seconds.
  2. Sign up. The decision shows on the dashboard's Decisions page, under the path you sent.
  3. Check fail open: set a wrong key and sign up again. The call answers 401, and the sign-up goes through.

Common mistakes

  • trustProxy: 1 in Fastify 5. It trusts no proxy, so request.ip is your load balancer's address for every visitor.
  • trustProxy: true, or trust proxy set to true in NestJS. Every hop is trusted, so the IP becomes what the visitor wrote in X-Forwarded-For.
  • Calling /v1/decide from the browser. The API key would reach every visitor; the call belongs on your server.
  • No timeout, or an error that stops the sign-up. Any answer other than 200, and no answer in time, means: let the visitor through.