Stop form spam in Express
Updated
This guide adds Bot403 to a contact form in Express. The browser solves a small proof of work. Then a middleware checks the token with one call to @bot403/node, before your route accepts the message. The visitor sees no puzzle, and the script sets no cookie. The free plan covers 5,000 checks a month and needs no card.
The example uses Express 5.3.0 and @bot403/node 1.0.2. Both need Node.js 18 or newer. On 12 November 2026, the code on this page ran in a fresh Express app on Node.js 26.13.1, against a local stand-in for the verify API that gives the documented answers. A good token went through. A reused token, a filled honeypot and a form with no token were refused. A multipart form got 415, and the form still went through when the API did not answer.
Before you start
Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). Put the secret key in an environment variable, never in your code or your repository.
npm install express @bot403/node
export BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEYThe app has this layout. package.json needs "type": "module", because the files use import.
app.mjs # createApp() and the requireBot403 middleware
server.mjs # starts the app
public/contact.html # the form
public/thanks.html
test/contact.test.mjs1. The form
The script tag protects every form on the page. Before the browser sends the form, the script adds a hidden _bot403 field with the token, and a hidden honeypot field (by default _website).
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Contact</title>
<script src="https://bot403.com/v1/bot403.js" data-bot403-key="pk_live_YOUR_PUBLIC_KEY" async></script>
</head>
<body>
<form method="post" action="/contact">
<label>Email <input name="email" type="email" required></label>
<label>Message <textarea name="message" required></textarea></label>
<button type="submit">Send</button>
</form>
</body>
</html>2. The middleware and the app
requireBot403 is a middleware, so you can put it on every form route. It sends the whole form to https://bot403.com/api/v1/verify with your secret key. The route runs only when the answer is ok. If Bot403 does not answer, the middleware lets the form through and logs a warning. A wrong secret key or too many verify calls a minute throw an error, so you see them and fix them.
import { fileURLToPath } from "node:url";
import express from "express";
import { Bot403, Bot403Error } from "@bot403/node";
// Checks the form before the route handler runs. Mount it on each form route.
export function requireBot403(bot403) {
return async (req, res, next) => {
// Express 5 leaves req.body undefined when no body parser read the request
if (!req.body) return res.status(415).send("Send the form as application/x-www-form-urlencoded");
let result;
try {
// 1. Post the whole form. Bot403 reads the _bot403 field and the honeypot field
result = await bot403.verifyForm(req.body);
} catch (err) {
if (err instanceof Bot403Error && err.status === 0) {
console.warn("bot403 did not answer, letting the form through:", err.message);
return next();
}
throw err; // 401 wrong key, 429 too many calls: Express 5 sends this to the error handler
}
// 2. Refuse when ok is false, except for reason "quota"
if (!result.ok && result.reason !== "quota") return res.status(400).send("Try again");
next();
};
}
export function createApp({ bot403 } = {}) {
// Make the client here, not at import time: it throws without BOT403_SECRET_KEY
bot403 ??= new Bot403({ secretKey: process.env.BOT403_SECRET_KEY, timeoutMs: 5000 });
const app = express();
app.use(express.static(fileURLToPath(new URL("public", import.meta.url))));
app.use(express.urlencoded({ extended: false }));
app.post("/contact", requireBot403(bot403), (req, res) => {
// A real visitor: send the email or store req.body.message here
res.redirect(303, "/thanks.html");
});
return app;
}import { createApp } from "./app.mjs";
createApp().listen(3000, () => console.log("http://localhost:3000/contact.html"));A failed token is a normal answer, not an error: result.ok is false and result.reason says why. The verify page lists every reason. The quota reason comes only in a capped month. This code lets the form through then, so a capped month loses no message.
The trap: req.body is undefined
In Express 5, req.body stays undefined until a body parser reads the request. express.urlencoded() reads only forms sent as application/x-www-form-urlencoded. That is what a plain HTML form sends, so the form above works.
Two common forms do not send that type:
- A form with
enctype="multipart/form-data", for example one with a file field. - A form sent with
fetchandnew FormData(form)as the body. The browser then sends it as multipart too.
For both, req.body is undefined when the middleware runs. Without the first line of the middleware, verifyForm(undefined) throws "TypeError: Cannot convert undefined or null to object", and the visitor gets a 500 error. With that line, the visitor gets 415 and a message that says what is wrong. The two sections below show how to fix each case.
Forms sent with fetch
Send the form as URLSearchParams, not as FormData. Then express.urlencoded() reads it, and the token and the honeypot field go with it. The script listens to the submit event before your own code does. It waits for the token, puts it in the _bot403 field, and then submits again. So when your handler runs, the form already holds the token.
const form = document.querySelector("form");
form.addEventListener("submit", async (event) => {
event.preventDefault();
// URLSearchParams, not FormData: express.urlencoded() does not read multipart
const body = new URLSearchParams(new FormData(form));
const res = await fetch(form.action, { method: "POST", body });
if (res.ok) location.href = res.url;
});If your front end sends JSON, put the token in the body and call bot403.verify(token) on the server instead of verifyForm(). This sends the token alone, so Bot403 cannot check the honeypot field. Use form fields when you can.
Forms with a file upload
Put a multipart parser such as multer before requireBot403. Multer fills req.body with the text fields, so the middleware sees the token and the honeypot field. The file stays on your server: verifyForm() sends only text fields.
// npm install multer
import multer from "multer";
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 1_000_000 } });
app.post("/apply", upload.single("cv"), requireBot403(bot403), (req, res) => {
// req.file is the upload, req.body holds the text fields
res.redirect(303, "/thanks.html");
});Multer reads the whole upload before the check runs. Keep the size limit, so a bot cannot send a large file to a form it will fail anyway.
When the secret key is wrong
A wrong or missing secret key is a mistake in your setup, not a spam attempt. verifyForm() then throws a Bot403Error with status 401. Express 5 passes errors from an async middleware to the error handler, so the route does not run. The default handler answers with the error's status, here 401, and logs the stack. Add your own error handler if you want a different page. Do not catch the 401 and accept the form: then every form goes through unchecked.
If BOT403_SECRET_KEY is not set at all, new Bot403() throws "secretKey is required" when the app starts. That is why createApp() makes the client, not the top of the module: a test can pass its own client and needs no key.
Test it
The tests give the app a real Bot403 client with a fake fetch that returns a fixed answer. They need no network and no key, and they use only node:test.
import { test } from "node:test";
import assert from "node:assert/strict";
import { Bot403 } from "@bot403/node";
import { createApp } from "../app.mjs";
// A real Bot403 client with a fake fetch: no network, no key
function fakeBot403(status, answer) {
const fetch = async () => {
if (answer instanceof Error) throw answer;
return new Response(JSON.stringify(answer), { status });
};
return new Bot403({ secretKey: "sk_test", fetch });
}
async function post(bot403, body) {
const server = createApp({ bot403 }).listen(0);
try {
const url = `http://localhost:${server.address().port}/contact`;
return await fetch(url, { method: "POST", body, redirect: "manual" });
} finally {
server.close();
}
}
const form = () => new URLSearchParams({ email: "[email protected]", _bot403: "token" });
test("a verified form goes through", async () => {
const res = await post(fakeBot403(200, { ok: true }), form());
assert.equal(res.status, 303);
});
test("a failed token is refused", async () => {
const res = await post(fakeBot403(200, { ok: false, reason: "invalid" }), form());
assert.equal(res.status, 400);
});
test("a capped month lets the form through", async () => {
const res = await post(fakeBot403(402, { ok: false, reason: "quota" }), form());
assert.equal(res.status, 303);
});
test("bot403 down lets the form through", async () => {
const res = await post(fakeBot403(0, new Error("connect ECONNREFUSED")), form());
assert.equal(res.status, 303);
});
test("a multipart form is refused before the check", async () => {
const body = new FormData();
body.set("email", "[email protected]");
const res = await post(fakeBot403(200, { ok: true }), body);
assert.equal(res.status, 415);
});node --testThen run node server.mjs. Open http://localhost:3000/contact.html and send the form. The browser goes to the thanks page, and the site in your dashboard shows one check. If you get a failure that you do not expect, read the troubleshooting page. It lists every reason and its fix. To replace reCAPTCHA in an existing Express form, read Migrate from reCAPTCHA in 10 minutes. For a route handler in Next.js, read Stop form spam in Next.js. For the same middleware on Cloudflare Workers, Bun or Deno, read Stop form spam in Hono. All guides are in the guides index.
Stop spam, not customers.
The CAPTCHA your visitors never see.