Korzen
Bot Protection
In these docs

Web-standard Request

Bot Protection in Hono, Bun, Deno, React Router, Remix, Astro, SvelteKit and Nuxt: one client file, fromRequest on the Fetch Request, and the visitor's IP.

Every server on this page hands your code the Fetch API's Request, so one client serves them all: 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. Only where the request comes in, and where the visitor's IP is, differ. For Next.js, see Next.js; for a Cloudflare Worker, Cloudflare Workers.

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 serves the tag and its beacon from your own domain. First-party mode

The client

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

Install the client:

npm install @korzen/bot-protection

Then one client for the process, in a module of yours. The examples below import it from korzen.js; in React Router name it app/korzen.server.js, in SvelteKit src/lib/server/korzen.js, so it never reaches the browser's bundle:

// korzen.js: one client for the process
import { createClient } from "@korzen/bot-protection";

// The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
export const korzen = createClient({ apiKey: process.env.KORZEN_API_KEY, url: "https://eu.korzen.dev", timeoutMs: 200 });
export { fromHeaders, fromRequest, ipFrom } from "@korzen/bot-protection";

korzen.decide(fromRequest(request, { ip })) reads the request's User-Agent, the headers Bot Protection reads, the _kz cookie, the path and the method, and returns the answer, or null on any error. It reads no body, so your code still reads the form after it. The Fetch API's Headers keep no order, so no header order is sent.

Hono

A middleware on the route that creates the account; the same app runs on Node, Bun and Deno:

// app.js
import { Hono } from "hono";
import { serve } from "@hono/node-server"; // on Bun or Deno, serve app.fetch with their own server
import { fromRequest, ipFrom, korzen } from "./korzen.js";

const app = new Hono();

// Asks before the handler, and keeps the answer as c.get("korzen") (null when there is none).
async function guard(c, next) {
  // protectedAction: sign-up, login and payment: a script that never loaded your page holds no token
  const d = await korzen.decide(fromRequest(c.req.raw, { ip: ipFrom.lastForwarded, protectedAction: true })); // see "The visitor's IP"
  if (d?.action === "block") return c.text("We could not create your account.", 400);
  c.set("korzen", d);
  await next();
}

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

serve({ fetch: app.fetch, port: 3000 });

Bun

With Bun.serve's routes (Bun 1.2.3 and later), the server gives the connection's address:

// server.js: bun run server.js
import { fromRequest, korzen } from "./korzen.js";

Bun.serve({
  port: 3000,
  routes: {
    "/signup": {
      POST: async (req, server) => {
        const d = await korzen.decide(fromRequest(req, { ip: server.requestIP(req)?.address, protectedAction: true })); // see "The visitor's IP"
        if (d?.action === "block") return new Response("We could not create your account.", { status: 400 });
        const user = await createAccount(await req.formData()); // your own code
        await saveRequestID(user.id, d?.request_id); // see "Apply the action"
        return Response.redirect(new URL("/welcome", req.url), 303);
      },
    },
  },
});

Deno

// server.js: deno run --allow-net --allow-env server.js
import { fromRequest, korzen } from "./korzen.js";

Deno.serve({ port: 3000 }, async (req, info) => {
  if (req.method !== "POST" || new URL(req.url).pathname !== "/signup") return new Response("Not found", { status: 404 });
  const d = await korzen.decide(fromRequest(req, { ip: info.remoteAddr.hostname, protectedAction: true })); // see "The visitor's IP"
  if (d?.action === "block") return new Response("We could not create your account.", { status: 400 });
  const user = await createAccount(await req.formData()); // your own code
  await saveRequestID(user.id, d?.request_id); // see "Apply the action"
  return Response.redirect(new URL("/welcome", req.url), 303);
});

React Router and Remix

In the action of the route that creates the account (React Router's framework mode, which Remix became):

// app/routes/signup.jsx
import { data, redirect } from "react-router";
import { fromRequest, ipFrom, korzen } from "../korzen.server.js";

export async function action({ request }) {
  const d = await korzen.decide(fromRequest(request, { ip: ipFrom.lastForwarded, protectedAction: true })); // see "The visitor's IP"
  if (d?.action === "block") return data({ error: "We could not create your account." }, { status: 400 });
  const user = await createAccount(await request.formData()); // your own code
  await saveRequestID(user.id, d?.request_id); // see "Apply the action"
  return redirect("/welcome");
}

Astro

An endpoint rendered on demand, with a server adapter (such as @astrojs/node), which gives clientAddress:

// src/pages/api/signup.js
import { fromRequest, korzen } from "../../korzen.js";

export const prerender = false;

export async function POST({ request, clientAddress, redirect }) {
  const d = await korzen.decide(fromRequest(request, { ip: clientAddress, path: "/signup", protectedAction: true })); // see "The visitor's IP"
  if (d?.action === "block") return new Response("We could not create your account.", { status: 400 });
  const user = await createAccount(await request.formData()); // your own code
  await saveRequestID(user.id, d?.request_id); // see "Apply the action"
  return redirect("/welcome", 303);
}

SvelteKit

In the form action of the sign-up page; getClientAddress() is the IP your adapter reads:

// src/routes/signup/+page.server.js
import { fail, redirect } from "@sveltejs/kit";
import { fromRequest, korzen } from "$lib/server/korzen.js";

export const actions = {
  default: async ({ request, getClientAddress }) => {
    const d = await korzen.decide(fromRequest(request, { ip: getClientAddress(), protectedAction: true })); // see "The visitor's IP"
    if (d?.action === "block") return fail(400, { error: "We could not create your account." });
    const user = await createAccount(await request.formData()); // your own code
    await saveRequestID(user.id, d?.request_id); // see "Apply the action"
    redirect(303, "/welcome");
  },
};

Nuxt

A server route. fromHeaders(event.headers) reads the request's headers and leaves its body to readFormData; building a second Request with toWebRequest(event) would leave the form unread:

// server/api/signup.post.js
import { fromHeaders, ipFrom, korzen } from "../utils/korzen.js";

export default defineEventHandler(async (event) => {
  const d = await korzen.decide(fromHeaders(event.headers, { ip: ipFrom.lastForwarded, path: "/api/signup", protectedAction: true })); // see "The visitor's IP"
  if (d?.action === "block") {
    setResponseStatus(event, 400);
    return "We could not create your account.";
  }
  const user = await createAccount(await readFormData(event)); // your own code
  await saveRequestID(user.id, d?.request_id); // see "Apply the action"
  return sendRedirect(event, "/welcome", 303);
});

The visitor's IP

Send the address your own proxy saw, never one the visitor could have written. With nothing in front of your server, that is the connection's address: server.requestIP(req) in Bun, info.remoteAddr in Deno. Behind one load balancer or nginx of yours, it is the last entry of X-Forwarded-For, the one your proxy added: ipFrom.lastForwarded. Behind Cloudflare, ipFrom.cloudflare reads CF-Connecting-IP, if your server only takes traffic from Cloudflare.

Astro's clientAddress and SvelteKit's getClientAddress() are what the adapter reads. With @sveltejs/adapter-node behind a proxy, set ADDRESS_HEADER=X-Forwarded-For and XFF_DEPTH=1 (one proxy of yours), where every request comes through that proxy: the adapter refuses a request without the header. In Nuxt, h3's getRequestIP(event, { xForwardedFor: true }) takes the first entry, which the visitor writes: use ipFrom.lastForwarded, as above.

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 dev server 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; with ipFrom.lastForwarded and no proxy in front, it is none, which is fine too.

  1. Set KORZEN_API_KEY in the server's environment 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

  • The first entry of X-Forwarded-For, as ipFrom.vercel or h3's xForwardedFor read it, behind a proxy that appends to it. The visitor writes that entry, so a bot picks its own IP. ipFrom.vercel is right on Vercel only, which overwrites the header.
  • The client imported into code that reaches the browser. The API key would reach every visitor; keep it in a server-only module.
  • An Astro page left prerendered. Without prerender = false (or output: "server"), the endpoint has no request to judge, and clientAddress throws.
  • 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.