Project
CompletedBuilding a Contact Form
Adding a captcha-protected contact form to a static website with Cloudflare Turnstile, Cloud Run and Resend

This website has never had a way for anyone to get in touch. That’s partly by design, since a mailto: link is an open invitation to spam harvesters, but mostly because the site is entirely static. Astro builds it into HTML files, Cloud Build copies them into a Cloud Storage bucket, and a Google Cloud load balancer serves them through Cloud CDN, with Cloudflare in front of the lot. There’s no server sitting there waiting to receive a form submission.
So a contact form meant building a small one, and putting a captcha in front of it so it doesn’t become a spam pipe straight into my inbox. I paired with Claude Code on this one.
The choices
There were four decisions to make before writing any code.
The captcha: Cloudflare Turnstile. Google’s reCAPTCHA is the obvious default, but it sets tracking cookies, and I’d rather not hand my visitors to Google just so they can say hello. Turnstile is free, usually invisible (most people never see a challenge at all), and works whether or not your DNS is on Cloudflare. Mine is, which made it an easy pick.
Somewhere to receive the form: Cloud Run. I already run a small Cloud Run service for the now playing widget, with Terraform and a GitHub Actions deploy pipeline around it. A contact form backend is the same shape: a tiny service that scales to zero and costs next to nothing when nobody is using it.
Delivering messages: Resend. The form needs to end up as an email. Resend is a transactional email API with a free tier that comfortably covers a personal website. I also considered sending through Gmail with an app password, which felt fragile, and storing messages in a database, which I’d never remember to check.
Routing: the site’s own domain. The browser could post straight to Cloud Run’s *.run.app address, but that’s a cross-site request, with CORS to configure. Instead I added a path rule to the existing load balancer so elliotx.com/api/contact goes to the service. The form posts to its own domain, there’s no CORS at all, and the Cloud Run service can be locked down to accept traffic only from the load balancer.
Architecture
Following a message through:
- The visitor loads
/contactlike any other page: through Cloudflare, then the load balancer, then the bucket. - The Turnstile widget on the page quietly checks the browser and issues a token.
- On submit, the page posts the form and the token to
/api/contact. The load balancer’s path rule sends that one path to Cloud Run instead of the bucket. - The service checks the token with Cloudflare’s
siteverifyAPI, then hands the message to Resend. - Resend delivers it to my inbox, with the reply-to set to the visitor, so hitting reply just works.
The secrets (the Turnstile secret key, the Resend API key and my inbox address) live in Secret Manager. Cloud Run passes them to the service as environment variables at startup.
The page
The page itself is plain Astro: name, email and message fields, plus the Turnstile widget, which is one div and a script tag.
<div class="cf-turnstile" data-sitekey="<your-site-key>" data-theme="auto"></div>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
The site key is public by design, since it ships in the page. The matching secret key never leaves the server.
When the widget finishes, it drops a hidden cf-turnstile-response input into the form. A few lines of JavaScript post the fields and that token as JSON, show a “sent” or “something went wrong” message inline, and reset the widget afterwards, because each token can only be used once.
There’s one more field you can’t see. A hidden “website” input sits off-screen, out of the tab order and hidden from screen readers. People never fill it in. Naive bots fill in every field they find, which gives them away.
The backend
The service is a small TypeScript app with no runtime dependencies: Node’s built-in HTTP server and fetch cover everything. It follows the same pattern as my other apps, with a distroless container image, linting and type checks on every pull request, and a shared GitHub Actions workflow that builds, scans and deploys it.
Every submission runs a gauntlet of checks, cheapest first, so junk is thrown out before it costs a call to Cloudflare or Resend.
A few of these are worth explaining.
The origin check. The form is only ever served from my own domain, so any POST that arrives from another site’s page is rejected outright. That stops someone embedding my form somewhere else.
The honeypot answers “200 OK”. If the hidden field has anything in it, the service pretends everything went fine and quietly drops the message. Returning an error would tell the bot it had been caught.
The rate limit counts after validation. It’s a small per-visitor limit, held in memory, as a backstop behind the captcha. I deliberately count only submissions that pass validation, so someone who fumbles the email field a few times doesn’t lock themselves out.
The captcha is checked on the server. This is the step that actually matters. The widget on its own stops nothing: a bot can skip the page entirely and post straight to the API. The real check is the server asking Cloudflare whether the token is genuine:
const form = new URLSearchParams({ secret, response: token });
if (remoteIp) form.set('remoteip', remoteIp);
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
body: form,
signal: AbortSignal.timeout(10_000),
});
const data = await res.json();
// Also check the token was issued on my site, not someone else's.
return data.success && data.hostname === expectedHostname;
Tokens are single-use and expire after five minutes, so a captured token can’t be replayed.
Finally, the message goes to Resend’s API with reply_to set to the visitor’s address. The email comes from a send-only address on my domain, with no mailbox behind it.
Infrastructure
Everything is in Terraform, in the same repo as the rest of the site’s infrastructure, with one folder (and one state file) per app. The contact form’s stack creates:
- a runtime service account that can read its own three secrets and nothing else
- a deploy service account for GitHub Actions, authenticated with Workload Identity Federation, so there are no long-lived keys
- an Artifact Registry repository for the container images
- three Secret Manager secrets, created empty
- the Cloud Run service, with its ingress set to accept traffic only from the load balancer
Notice that Terraform creates the secrets but never their values. Anything Terraform writes ends up in its state file, so the values are added by hand afterwards:
# zsh: read's "name?prompt" syntax
for s in turnstile-secret-key resend-api-key contact-to-email; do
read -rs "v?$s: " && echo && printf '%s' "$v" | gcloud secrets versions add "$s" --data-file=-
done
read -rs prompts without echoing what you type, so nothing lands on screen or in shell history.
On the load balancer side, the change is a serverless network endpoint group pointing at the Cloud Run service, a backend service, and one path rule on the existing URL map. Every other path still goes to the bucket:
path_matcher {
name = "site"
default_service = google_compute_backend_bucket.static_backend.id
path_rule {
paths = ["/api/contact"]
service = google_compute_backend_service.contact_form[0].id
}
}
Rolling it out
This took more steps than I expected, because of one Cloud Run rule: it won’t create a service whose secrets have no value yet. And the values can’t exist until Terraform has created the secrets. It’s a chicken-and-egg problem.
The fix was a create_service switch, defaulting to off. The first Terraform run creates everything except the service, then I add the secret values, then a second, one-line change flips the switch. The load balancer route sits behind a matching switch, so the live site doesn’t change until there’s something behind /api/contact.
The page went out last of all, so nobody could ever find a form with nothing behind it.
Gotchas
- Cloudflare in front changes the visitor’s IP. With Cloudflare proxying the site, the load balancer’s idea of “the visitor” is actually a Cloudflare edge server. The rate limit’s first draft used the first entry of the
X-Forwarded-Forheader, which looks right but is the one part of that header a client controls. Anyone could have sent a fake one. The service now uses Cloudflare’sCF-Connecting-IPheader, which Cloudflare sets itself, overwriting anything the client sent. - Email DNS records must not be proxied. Resend verifies your domain with a couple of DNS records, and Cloudflare proxies new records by default. A proxied record doesn’t return what Resend is looking for, so they need to be “DNS only” (the grey cloud). In the end Resend connected to Cloudflare and set them up itself, correctly.
- Test with Cloudflare’s test keys. The real Turnstile site key only works on the hostname it’s registered for, so it fails on
localhost. Cloudflare publishes dummy keys that always pass or always fail, which made it easy to test both paths locally. gcloudstamps every deploy. Eachgcloud run deploylabels the service with the client that deployed it. Terraform then showed a pointless change on every plan, and the next deploy put the label straight back. Telling Terraform to ignore those two fields stopped the noise for every Cloud Run service on the site, not just this one.
Testing
Before anything went near production, I ran the whole chain locally. That was the built site plus the backend, behind a tiny Node script standing in for the load balancer, so /api/contact was routed exactly as it would be in production. Using Cloudflare’s test keys and a deliberately fake Resend key, I submitted the form in a real browser and watched the token get issued, verified, and handed to Resend (which rejected the fake key, as expected). Every rejection path in the checks diagram was tested with curl too.
Once it was all deployed, the real test was simple: I sent myself a message. It arrived.
Result
There’s now a contact page. For visitors, it’s a short form and a captcha that usually passes without them doing anything. Behind it sits a stateless service that costs nothing when idle, sets no tracking cookies, keeps every secret out of git and Terraform state, and refuses to talk to anything except my own load balancer.
It’s a lot of plumbing for one form. But most of it was already there from earlier projects, and the new pieces (the path rule, the secrets, the two-step rollout) are now a pattern I can reuse the next time the site needs a little bit of backend.