vi

blog

Static site contact form: Cloudflare Email Sending and Turnstile instead of Web3Forms

One dedicated Worker, one narrow route, a binding that locks the recipient. How I replaced Web3Forms with Cloudflare Email Sending on a static export site, including the anti-spam layers and what I could not verify.

Published
CloudflareWorkersTurnstileEmail Sending
Diagram of a browser sending a form through a Worker to Cloudflare Email Sending

A static site has no backend, but its contact form still needs somewhere to receive a request and send mail. I replaced Web3Forms with a dedicated Worker that sends mail through Cloudflare Email Sending, bound to exactly one route, /forms/contact. Sending the mail is the easy part. The hard part is keeping a public endpoint from exhausting the quota of the whole account.

This post records the design, the anti-spam layers and what I measured. I say where I could not verify something.

Where Web3Forms free stops

The form used to POST straight to api.web3forms.com, with the access_key sitting in the JS. A public key is by design: anyone holding it can submit. The free plan gives 250 submissions/month, and Turnstile and Restrict to Domain are Pro only. The old form's botcheck honeypot was an <input type="hidden"> that always sent an empty string, so it blocked nothing.

To get a real captcha and control over where mail goes, the form has to call an endpoint I own.

One dedicated Worker, one narrow route

The site runs on Workers Static Assets: requests for static files are free and unlimited. A Worker with code is different. Every invocation counts against the 100,000 requests/day limit of the whole account, shared with every other Worker.

My first design attached the code to the site's own Worker. 2 reviews showed the flaw: a Worker with both assets and main is invoked for every non-navigation request to a path with no file, not only /forms/*. A scanner probing /.env would cost an invocation.

The final design splits them:

  • khuong stays untouched, assets only.
  • khuong-forms has code only, bound to exactly nguyentrungkhuong.com/forms/contact.

The specific route wins over nguyentrungkhuong.com/*, so only that exact path reaches the Worker. I tested this on the existing /ads.txt route: /ads.txt?x=1, /ads.txt/ and /ADS.txt all fall through to the assets and return a free 404. Rollback is deleting the route.

A request passing through WAF, Worker, Turnstile and KV before reaching Email Sending
A request passing through WAF, Worker, Turnstile and KV before reaching Email Sending

Cloudflare Email Sending: onboard the domain by API, lock the binding

Onboarding a sending domain is one API call, no dashboard:

bash
cf post '/zones/{zone}/email/sending/subdomains' '{"name":"example.com"}'

The apex is accepted. Cloudflare adds MX and SPF records for cf-bounce and a cf-bounce._domainkey DKIM record. An existing _dmarc record is left alone, even though the preview list suggests p=reject. A .../subdomains/preview endpoint runs a dry run that shows the records it would create and any DNS conflicts before writing anything.

On Workers Free, mail can only go to a verified destination address of the account. That suits a contact form: the recipient is always me. The send_email binding locks both ends:

json
{
  "send_email": [{
    "name": "EMAIL",
    "destination_address": "owner@example.net",
    "allowed_sender_addresses": ["form@example.com"]
  }]
}

A bug in the code still cannot send mail anywhere else, and the endpoint cannot become an open relay. The server builds to, from and subject. Visitor input only goes into the body and replyTo.

Anti-spam: cheap layers first, expensive layers last

There are 2 risks: spam flooding the inbox, and requests draining the 100,000 invocations/day. For the second one, be honest: every layer at the edge only blocks malformed requests. An attacker who deliberately uses curl with the right headers still reaches the Worker. The layers below lower the cost, they do not guarantee anything.

At the edge (a blocked request costs no invocation): one WAF custom rule blocks any request to /forms/* that is not a POST, or whose Origin is wrong, or whose Content-Type does not contain application/json. Origin and headers can be forged, so this rule only filters clumsy clients. The zone's existing rate limit is 20 requests/10 seconds/IP, which is also just a per-IP cap. One IP sending 1.2 requests/second never hits the threshold and still adds up to 100,000 requests/day.

Inside the Worker, each step runs only if the previous one passed:

  1. Right path, method, Origin and Content-Type.
  2. Read the body as a stream with a hard 10 KB cap before JSON.parse.
  3. Field allowlist, type and length limits, control characters rejected in single-line fields. A missing Turnstile token stops here, before any network call.
  4. Limiter of 3 requests/60 seconds/IP, with IPv6 grouped by /64.
  5. Turnstile siteverify with a 4 second timeout, checking hostname and action. A network error or a 5xx fails closed, no retry.
  6. Daily cap in KV: 30 mails/day overall and 3 mails/day/IP. Written only right before sending.
  7. Send plain text, with a header line saying the content came from the visitor and the email is unverified.

The limiter sits before siteverify so junk requests do not cost a network call. KV is written only when a send is certain, because Free allows 1,000 writes/day. KV is not atomic, so concurrent requests can exceed the cap by a few mails. I accept that: the recipient is fixed, and mail to a verified address does not use the mail quota.

Turnstile uses execution: "execute" and fetches the token when the visitor clicks send. A token lives 300 seconds and works once, so call turnstile.reset() after every response.

Deploy by API, not by wrangler

The code lives in the site repo (forms/src/index.js, no dependencies, with node --test tests). It does not deploy through the site's CI. On the Cloudflare side the code is bundled with esbuild, then the Worker, version and deployment are created through the API. The Turnstile secret goes straight from the API into a secret_text binding, never through argv or a file in the repo.

The upside: the site's asset deploy is untouched, and the site's CI token needs no extra permission. The cost: changing the Worker is its own procedure, not a git push.

Traps I hit

  • ratelimit binding on Free: the docs do not say whether it works. The API accepted all 4 bindings when creating the version, and at runtime it counted correctly. The code still keeps a Cache API fallback for when env.LIMITER is missing.
  • Non-JSON responses: a WAF 403 and a rate limit 429 return HTML. The client must handle a body that does not parse, so the visitor never sees SyntaxError.
  • Cache on /lien-he: s-maxage=300. After a deploy, visitors can still see the old form for up to 5 minutes. My first test still went to Web3Forms for exactly this reason.
  • The path must match exactly: the client POSTs to /forms/contact, no query, no trailing /. Any variant falls through to the assets and returns 404.
  • Email Routing and Email Sending are independent: mail to contact@ kept forwarding normally alongside.

Measurements

A real mail sent from the Worker landed in the inbox, not in spam. Original headers: dkim=pass (header.s=cf-bounce), spf=pass, dmarc=pass. The DKIM d= matches the From domain. SPF passes through relaxed alignment, because cf-bounce. is a subdomain of From and _dmarc sets no aspf. Vietnamese UTF-8 is intact in both subject and body.

One full send costs about 4.7 ms of CPU, under the 10 ms cap of Free. With 5 consecutive requests from one IP and a fake token, the limiter returned 4 400 turnstile_failed and then 429 rate_limited on the 5th. The fake token was rejected by siteverify, not a 503, which means the secret is correct.

Not verified, and the trade-offs

A few things I do not know for sure, so I do not claim them:

  • The 30 mails/day and 3 mails/IP/day caps with many real tokens: not tested, it needs a real token for every attempt.
  • How Turnstile managed treats a visitor it suspects.
  • Behaviour under a large attack. The 100,000 invocations/day is shared by the whole account, and past it requests to the Worker are refused until 00:00 UTC while static pages keep working.
  • Whether Email Sending is still beta outside Workers Free: the docs I read do not say.
  • Whether the suppression list applies to a verified destination address. If mail stops arriving, that is the first place to look.

The biggest trade-off: a mail that hits a send error is lost, because I chose not to store a fallback copy. The visitor sees an error message with the contact@ address, and I cover the gap with daily monitoring in the first week. If monitoring shows a real attack, the next step is upgrading to Workers Paid or adding a challenge in the WAF.

Related posts

all posts →