Cloudflare · Security · Web Development · JavaScript

Stopping Contact Form Spam on Static Sites: Honeypots, Timing and Turnstile

Layered contact form spam protection for static sites: honeypot fields, timing checks, server-side validation, rate limiting and Cloudflare Turnstile verified in a Pages Function.

Sander Yazıcıoğlu Published: 3 min read Türkçe oku

Stopping Contact Form Spam on Static Sites: Honeypots, Timing and Turnstile

On almost every corporate site I have built, for health-tourism clinics, logistics firms and other businesses, the contact form is the page that matters most commercially. It is also the first thing bots find. Within days of launch the inbox fills with SEO offers and link spam, and a real patient enquiry gets lost in it. I wrote in lessons from corporate websites that invisible methods come first and CAPTCHA is the last resort. This post is the practical version of that advice.

Think in layers

No single check stops all spam. Each layer is cheap and catches a different kind of bot:

LayerCatchesUser friction
Honeypot fieldBots that fill every inputNone
Timing checkBots that submit instantlyNone
Server-side validationMalformed and link-stuffed payloadsNone
Rate limitingFloods from one sourceNone for normal users
TurnstileSmarter, browser-driven botsUsually none

1. The honeypot

Add a field humans never see. Bots that blindly fill inputs fill it too.

<div class="hp" aria-hidden="true">
  <label for="company_site">Leave this empty</label>
  <input id="company_site" name="company_site" type="text" tabindex="-1" autocomplete="off">
</div>
.hp { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }

Avoid display: none and obvious names like honeypot; some bots skip those. Use tabindex="-1" and aria-hidden so keyboard and screen-reader users never land on it, which keeps the form accessible. Never reject based on the honeypot in the browser only: the check must run on the server.

2. The timing check

Humans need several seconds to fill a form; scripts need milliseconds. Record when the form was rendered and reject submissions that are too fast:

form.elements.rendered_at.value = Date.now().toString();

A plain timestamp can be forged, so for stronger protection the server signs it (an HMAC of the timestamp) and verifies the signature. Keep the threshold low, a few seconds, so fast typists and browser autofill don't get blocked.

3. Validate on the server

Static sites tempt you to send the form straight to a third-party email API from the browser. Don't: any key in the browser is public, and you lose the place to run checks. On Cloudflare Pages, a Pages Function at functions/api/contact.ts is the natural place:

interface Env { TURNSTILE_SECRET: string; }

export const onRequestPost: PagesFunction<Env> = async ({ request, env }) => {
  const form = await request.formData();

  if (form.get('company_site')) return new Response('OK'); // honeypot: pretend success
  const rendered = Number(form.get('rendered_at'));
  if (!rendered || Date.now() - rendered < 3000) return new Response('OK');

  const message = String(form.get('message') ?? '').trim();
  const links = (message.match(/https?:\/\//g) ?? []).length;
  if (message.length < 10 || message.length > 5000 || links > 2) {
    return new Response('Invalid message', { status: 400 });
  }

  const ok = await verifyTurnstile(form.get('cf-turnstile-response'), request, env);
  if (!ok) return new Response('Verification failed', { status: 403 });

  await sendNotification(form); // email, CRM, or a queue
  return new Response('OK');
};

Note the honeypot and timing failures return a normal success. Telling a bot exactly why it failed helps it adapt. Real validation errors (too short, too long) get honest messages because humans hit them.

4. Cloudflare Turnstile

Turnstile is Cloudflare's CAPTCHA alternative. In most cases it runs checks in the background and the visitor never solves a puzzle. Add the script and the widget:

<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<div class="cf-turnstile" data-sitekey="YOUR_SITE_KEY"></div>

The widget adds a hidden cf-turnstile-response field to the form. That token means nothing until the server verifies it:

async function verifyTurnstile(token: FormDataEntryValue | null, request: Request, env: Env) {
  if (typeof token !== 'string' || !token) return false;
  const body = new FormData();
  body.append('secret', env.TURNSTILE_SECRET);
  body.append('response', token);
  const ip = request.headers.get('CF-Connecting-IP');
  if (ip) body.append('remoteip', ip);
  const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body });
  const data = (await res.json()) as { success: boolean };
  return data.success;
}

Things to know:

  • Tokens are single-use and expire after a few minutes, so verify once, at submit time.
  • Store the secret as an encrypted environment variable, never in the repo.
  • If you run a strict Content Security Policy, allow https://challenges.cloudflare.com in script-src and frame-src. The CSP guide explains how to roll that out without breaking the page.

5. Rate limiting

Even with everything above, a single IP sending hundreds of requests should be stopped before your function runs. Cloudflare's WAF rate limiting rules can do this on the path /api/contact with no code. If you prefer it in code, a small counter per IP in KV or a Durable Object works, but a WAF rule is simpler and cheaper.

Don't forget the humans

  • Show a clear success message and keep what the user typed if something fails.
  • Send yourself the enquiry with a Reply-To header set to the visitor's address, so replying is one click.
  • Test the form after every deploy. A broken form looks exactly like a quiet week. An end-to-end test that submits the form against a test key is worth having.

Conclusion

Stack cheap, invisible layers: a honeypot, a timing check, server-side validation that silently drops bots, rate limiting at the edge, and Turnstile verified on the server. Visitors fill in a normal form, the inbox stays clean, and the enquiries that actually matter don't get buried.

All articles →