Cloudflare Turnstile Next.js forms: what to protect

Cloudflare Turnstile on Next.js forms: which forms need it, per-IP limits first, explicit render for client navigation, token resets, and failing closed.

By

Any public form that sends an email or creates a row is a tool a script can use against you. I recently went through a production app and closed that gap on every such form, using per-IP limits and Cloudflare Turnstile on Next.js forms backed by an Express API. This post covers which forms get it, why verification runs after the rate limit, the explicit render that client navigation needs, why the token resets after every attempt, and what the server does when Cloudflare can't answer. Every gap described here is closed.

Which forms need Cloudflare Turnstile?

Protect any public form that sends an email or creates a row. Those are the two things a script can make your server do for free, at volume, to you or to strangers. That usually means signup, forgot password, magic link requests, resend verification and contact. Forms behind a login already have an identity attached, so they can wait.

The list is longer than it first looks, and small buttons are easy to forget. Resend verification appeared in two places, one at checkout and one in the account area, and both needed the token. Routes like these send mail to an address the caller supplies, so an open one lets a script use your domain to email strangers. Your sending domain carries that cost, and the setup side of protecting it is in transactional email setup.

The contact form had a simpler risk. Every message lands in the support inbox, so a script could have flooded it.

Per-IP limits first, Turnstile second

The two defences answer different attackers, so I use both. A per-IP limit stops one machine hammering a route, and it's cheap. It can't do much against a bot that rotates addresses. Turnstile covers that case, since each attempt needs a token that Cloudflare confirms.

The order is deliberate. Register, forgot password, magic link and resend verification all verify the token after their per-IP limits. As Express middleware it reads router.post("/contact", contactLimit, verifyTurnstile, submitContact). The limit is a local check, while verification is a network call, so a flood stops at the cheap step and never reaches the slow one.

The contact form allows five messages an hour per IP address, and each one must also carry a confirmed token.

Rate limits matter on their own too. Guest checkout accepts any email, and an unpaid checkout earns that address a reminder email. Left open, a script could have made the server email strangers and fill the payments table with junk rows. It's now limited to ten an hour per IP address, far above what a real buyer retrying needs. Pick numbers like these by asking what a real person would do on a bad day, then leave some room.

One detail worth copying if you write your own limiter: for IPv6, key on the /64 block. Clients can rotate the low bits freely, so keying on the full address gives one machine a fresh budget every time.

Cloudflare Turnstile Next.js setup: explicit render

Turnstile has two modes. Implicit rendering scans the page for cf-turnstile containers when the script loads, which suits static pages. In a Next.js app, people often reach a form by client navigation, long after that scan ran, and the widget never appears. The Turnstile client-side rendering docs recommend explicit rendering for this case, and that's what I used:

useEffect(() => {
  if (!SITE_KEY || !ready || !box.current || !window.turnstile) return;
  widget.current = window.turnstile.render(box.current, {
    sitekey: SITE_KEY,
    action,
    callback: setToken,
    "expired-callback": () => setToken(""),
    "error-callback": () => setToken(""),
  });
  return () => {
    if (widget.current) window.turnstile?.remove(widget.current);
    widget.current = null;
  };
}, [ready, action]);

Load the script with next/script from api.js?render=explicit, and set ready from its onReady callback. ready also starts as true when window.turnstile already exists, which covers a second form reached later in the same visit. The cleanup removes the widget when the user leaves, so nothing stacks up across navigations.

All of this lives in a small useTurnstile hook that returns the widget, the token and a reset function. Each form takes a few lines to adopt it: render the widget, send the token, call reset. With six places to wire up, I wanted the awkward parts written once.

The widget stays hidden while NEXT_PUBLIC_TURNSTILE_SITE_KEY is unset. That value is inlined at build time, so it comes from a CI secret when the frontend builds.

Why reset the token after every attempt?

A Turnstile token is single use. Cloudflare's docs give it a lifetime of 300 seconds, and a token that has already been validated fails with timeout-or-duplicate. If a submit fails for any reason, such as a mistyped field or a rate limit, the form still holds a token that may already be spent. The retry would then fail verification with a confusing message.

So the token is reset after every attempt, success or failure. The expired and error callbacks clear it too, so the form can't submit a dead token, and the submit handler knows when a check is required but not yet passed.

Verify on the server and fail closed

The widget alone protects nothing, because anyone can call your API directly. The Turnstile server-side validation docs say it plainly: you must call Siteverify to complete the implementation.

export async function verifyTurnstile(req: Request, res: Response, next: NextFunction) {
  const secret = process.env.TURNSTILE_SECRET_KEY;
  if (!secret) return next();

  const token = typeof req.body?.turnstileToken === "string" ? req.body.turnstileToken : "";
  if (!token) return res.status(400).json({ message: "Please complete the check." });

  try {
    const r = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
      method: "POST",
      body: new URLSearchParams({ secret, response: token, remoteip: req.ip ?? "" }),
      signal: AbortSignal.timeout(8000),
    });
    const { success } = (await r.json()) as { success?: boolean };
    if (success) return next();
    return res.status(400).json({ message: "Verification failed. Please try again." });
  } catch {
    return res.status(503).json({ message: "Could not verify right now. Please try again soon." });
  }
}

The check is off while the secret is unset, which keeps local development working. Once the secret is set, it fails closed: a missing token, a rejected token or an unreachable Cloudflare all stop the request. The cost is that forms wait during a Cloudflare outage. For routes that send mail, I'd take a retry message over an open door. The timeout keeps a hung call from tying up the request.

If you copy this design, plan for the unset case: a secret missing from production would turn the check off with no error. My default is to log it loudly at startup or fail the deploy.

Rolling it out without locking people out

The order I'd use is frontend first. Ship the site key so forms start sending tokens while the backend still ignores them, then set the secret to turn enforcement on. Do it the other way round and every form fails until the frontend catches up. Tabs left open from before the deploy will have no token, so the message should tell people to try again.

Test the path before you rely on it. Cloudflare publishes testing keys that always pass or always fail, and they belong in development only, for the reasons in keeping test keys out of production builds.

Bot protection is one layer. Sessions and inbound webhooks need their own checks, which I wrote up in refresh token rotation with reuse detection and webhook security for purchases.

The short version

List every public form that sends email or creates a row, including the small resend buttons. Put a per-IP limit first and token verification second. Render the widget explicitly so client navigation works, reset the token after every attempt, verify on the server, and fail closed once the secret is set.

If you want a review of your public forms, see my services page.

Want this kind of work on your product?

Get in touch