Skip to content

Repository files navigation

cleantalk-antispam

Stop form spam, fake sign-ups and bots in Node.js and TypeScript with one API call. No CAPTCHA for your visitors.

npm version npm downloads license

cleantalk-antispam is the official server-side SDK for the CleanTalk Anti-Spam API. It checks a contact form, comment, review, registration or visitor against the CleanTalk cloud: sender email and IP reputation, message content, behaviour data from the Bot Detector and a blocklist built from 1,000,000+ protected websites. Works in Next.js (Route Handlers and Server Actions), Express, Fastify, NestJS, Remix, SvelteKit, Nuxt and any runtime with fetch (Node.js 18+, Bun, Deno, edge runtimes).

  • One call, one verdict: isSpam, reason, codes, requestId.
  • No runtime dependencies, ESM and CommonJS builds, full TypeScript types.
  • Fails open by default: if the cloud is unreachable your form keeps working.
  • Server-side only: your access key never ships to the browser.

Install

npm install cleantalk-antispam

Get an access key at cleantalk.org (7-day free trial, no card) and put it in CLEANTALK_API_KEY.

Quick start

import { CleanTalk } from "cleantalk-antispam";

const cleantalk = new CleanTalk({ apiKey: process.env.CLEANTALK_API_KEY! });

const verdict = await cleantalk.checkMessage({
  email: "visitor@example.com",
  name: "Jane",
  ip: "203.0.113.10",
  message: "Hello, I have a question about pricing",
});

if (verdict.isSpam) {
  // reject: verdict.reason explains why, verdict.codes has the rule codes
}

Try it with email: "stop_email@example.com": CleanTalk always marks this address as spam, so you can test your integration without real spam.

Which method to call

Form Method API
Contact form, comment, review, support ticket, anything with a text field checkMessage() check_message
Registration, newsletter sign-up, poll, order, any form without a message checkNewUser() check_newuser
Page view, API endpoint, contact decoding: is this visitor a bot? checkBot() check_bot

Next.js (App Router)

Step-by-step tutorial: How to protect a Next.js contact form from spam without a CAPTCHA.

// app/api/contact/route.ts
import { NextResponse } from "next/server";
import { CleanTalk, getClientIp, getEventToken } from "cleantalk-antispam";

const cleantalk = new CleanTalk({ apiKey: process.env.CLEANTALK_API_KEY! });

export async function POST(request: Request) {
  const form = await request.formData();
  const verdict = await cleantalk.checkMessage({
    email: String(form.get("email") ?? ""),
    message: String(form.get("message") ?? ""),
    ip: getClientIp(request.headers),
    eventToken: getEventToken(form),
  });
  if (verdict.isSpam) return NextResponse.json({ error: "Spam" }, { status: 400 });
  return NextResponse.json({ ok: true });
}

A Server Action version is in examples/next-server-action.ts.

Express

import express from "express";
import { CleanTalk, getClientIp, getEventToken } from "cleantalk-antispam";

const app = express();
app.use(express.urlencoded({ extended: true }));
const cleantalk = new CleanTalk({ apiKey: process.env.CLEANTALK_API_KEY });

app.post("/contact", async (req, res) => {
  const verdict = await cleantalk.checkMessage({
    email: req.body.email,
    message: req.body.message,
    ip: getClientIp(req.headers) ?? req.ip,
    eventToken: getEventToken(req.body),
  });
  if (verdict.isSpam) return res.status(400).send("Spam");
  res.send("Thanks!");
});

Better accuracy: add the Bot Detector to your page

The server-side check already works on email, IP and text. Add one script to the page with the form and CleanTalk also gets behaviour data (mouse, keyboard, headless browser signs), which catches bots that pass every other check:

<script src="https://fd.cleantalk.org/ct-bot-detector-wrapper.js" defer></script>

The script adds a hidden field ct_bot_detector_event_token to every form. Read it with getEventToken(form) and pass it as eventToken. When eventToken is set, submitTimeSeconds and jsEnabled are not needed.

API

new CleanTalk(options)

Option Default Description
apiKey required Access key from cleantalk.org/my
timeoutMs 5000 Request timeout
onError "allow" "allow" returns skipped: true and lets the submission through when the cloud is unreachable; "throw" raises CleanTalkError
agent node-cleantalk-<version> Agent string shown in your CleanTalk dashboard
endpoint https://moderate.cleantalk.org/api2.0 Override for a self-hosted proxy
fetch global fetch Custom fetch implementation

checkMessage(input) and checkNewUser(input)

Input fields: email, name, ip, message (checkMessage only), eventToken, submitTimeSeconds, jsEnabled, senderInfo ({ REFFERRER, USER_AGENT }), allHeaders.

Return SpamVerdict:

{
  isSpam: boolean;         // reject the submission
  isObviousSpam: boolean;  // stop_queue = 1, safe to drop without moderation
  reason: string;          // "*** Forbidden. Sender blacklisted. ***"
  codes: string[];         // ["DENIED", "BL"]
  requestId?: string;      // find the request in your CleanTalk dashboard
  skipped: boolean;        // true when the cloud was unreachable and onError is "allow"
  raw: SpamCheckResponse | null; // full API response
}

checkBot({ ip, eventToken?, pageUrl?, senderInfo? })

Returns { isBot, botExpectation (0..1), reason, skipped, raw }.

Helpers

  • getEventToken(formDataOrBody) reads ct_bot_detector_event_token.
  • getClientIp(headers) reads cf-connecting-ip, x-real-ip, x-forwarded-for.
  • checkMessage(apiKey, input) and checkNewUser(apiKey, input) for one-off calls.

Errors

CleanTalkError with code: INVALID_INPUT, KEY_INACTIVE (wrong key or expired account), HTTP_ERROR, NETWORK_ERROR, BAD_RESPONSE.

Pricing

CleanTalk Anti-Spam is $12 per year per website with unlimited API calls. Free 7-day trial, no card: cleantalk.org/register.

Links

License

MIT

Releases

Packages

Contributors

Languages