An Astro site with the default static output is a folder of HTML files, and a folder of files can’t receive a POST. So the usual advice is to sign up for a hosted form service. On Cloudflare you don’t have to. A few dozen lines of TypeScript can receive the form on your own domain, check it, and email it to you, on the free plan.
This guide covers the two ways to run that code next to an Astro site on Cloudflare, then builds the simpler one step by step: a form that works with JavaScript turned off, gets better with it on, drops bots with a honeypot, and validates everything on the server.
The original, canonical version of this guide lives on the Formharbor site: Astro contact form on Cloudflare, without a form backend.
Two ways to run the handler
- Static Astro plus a Pages Function. Astro stays fully static, with no adapter. You add a
functions/api/contact.tsfile at the project root, and Cloudflare Pages serves it as/api/contacton the same domain. Nothing about your Astro build changes. - The
@astrojs/cloudflareadapter with an API endpoint. You writesrc/pages/api/contact.tsas a normal Astro endpoint and mark itprerender = false. The rest of the site can stay prerendered. Since Astro 6 (adapter v13), the adapter deploys to Cloudflare Workers with static assets, not Pages, and bindings come fromimport { env } from "cloudflare:workers". Older tutorials that useAstro.locals.runtime.envare out of date.
Which to pick: if your site is static and already on Pages (or you just want the least moving parts), use the Pages Function. It doesn’t touch your Astro config, and the function is easy to move later. Use the adapter if you’re starting a new project on Workers or already render other pages on demand. The form markup and the validation code are the same either way.
A third option, a separate Worker on its own workers.dev URL, is covered in the Hugo, Astro, and Eleventy guide. It’s the right shape when several sites share one inbox, but it means handling CORS. Keeping the endpoint on the same origin avoids that.
Project layout (Pages Function route)
my-astro-site/ functions/ api/ contact.ts # → POST /api/contact (runs on Cloudflare) public/ src/ components/ ContactForm.astro pages/ contact.astro thanks.astro astro.config.mjs # no adapter, default static output package.json The functions/ folder sits at the project root, next to src/, not inside public/ or dist/. Pages finds it at build time and deploys it alongside the static files. In the Pages dashboard, use npm run build as the build command and dist as the output directory.
The form component
Start with a plain HTML form that posts to /api/contact. This is the version that has to work with no JavaScript at all, so it uses method="post", real name attributes, and the browser’s built-in required and length checks.
--- // src/components/ContactForm.astro --- <form class="contact" method="post" action="/api/contact"> <div class="hp" aria-hidden="true"> <label>Website <input name="website" tabindex="-1" autocomplete="off" /></label> </div> <label>Name <input name="name" required maxlength="80" autocomplete="name" /></label> <label>Email <input name="email" type="email" required maxlength="254" autocomplete="email" /></label> <label>Message <textarea name="message" required minlength="10" maxlength="5000"></textarea></label> <button type="submit">Send</button> <p class="form-status" role="status" aria-live="polite"></p> </form> <style> .hp { position: absolute; left: -10000px; } </style> The website field is the honeypot. It’s moved off-screen with CSS rather than type="hidden", because many bots skip hidden inputs but fill every visible-looking one. tabindex="-1" and autocomplete="off" keep keyboard users and password managers out of it. Astro scopes the <style> to this component, so the .hp class won’t leak into the rest of your site.
Use it on any page with <ContactForm />, and add the page the form redirects to:
--- // src/pages/thanks.astro import Layout from "../layouts/Layout.astro"; --- <Layout title="Thanks"> <h1>Thanks, your message is on its way.</h1> <p>I usually reply within two working days. <a href="/">Back to the home page</a></p> </Layout> With Astro’s default build.format, that file becomes /thanks/index.html, which is the URL the handler redirects to.
The Pages Function: honeypot, validation, delivery
Pages picks the handler by its export name: onRequestPost only answers POST. A GET to /api/contact skips this file and falls through to your static files, which usually means a 404. Pages compiles TypeScript for you. For editor types, install @cloudflare/workers-types or run npx wrangler types.
// functions/api/contact.ts interface Env { RESEND_API_KEY: string; CONTACT_TO: string; // your inbox CONTACT_FROM: string; // e.g. "Website <forms@yourdomain.com>" } type Errors = Record<string, string>; export const onRequestPost: PagesFunction<Env> = async ({ request, env }) => { const wantsJson = (request.headers.get("Accept") ?? "").includes("application/json"); const form = await request.formData(); // Honeypot: people never see this field. Pretend it worked so bots learn nothing. if (form.get("website")) return done(request, wantsJson); const name = String(form.get("name") ?? "").replace(/\s+/g, " ").trim(); const email = String(form.get("email") ?? "").trim(); const message = String(form.get("message") ?? "").trim(); const errors: Errors = {}; if (!name || name.length > 80) errors.name = "Please enter your name."; if (email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { errors.email = "Please enter a valid email address."; } if (message.length < 10 || message.length > 5000) { errors.message = "Your message should be 10 to 5,000 characters."; } if (Object.keys(errors).length) return fail(wantsJson, 400, errors); try { await sendMail(env, { name, email, message }); } catch (err) { console.error("contact form delivery failed", err); return fail(wantsJson, 502, { form: "Your message could not be sent. Please try again in a minute.", }); } return done(request, wantsJson); }; function done(request: Request, wantsJson: boolean): Response { if (wantsJson) return Response.json({ ok: true }); // 303 so a refresh on /thanks/ doesn't resubmit the form. return Response.redirect(new URL("/thanks/", request.url).href, 303); } function fail(wantsJson: boolean, status: number, errors: Errors): Response { if (wantsJson) return Response.json({ ok: false, errors }, { status }); // Only fixed strings go into this page, never what the visitor typed. const items = Object.values(errors).map((e) => `<li>${e}</li>`).join(""); const page = `<!doctype html><meta charset="utf-8"> <title>Please check the form</title> <h1>Please check the form</h1><ul>${items}</ul> <p>Use your browser's Back button. Most browsers keep what you typed.</p>`; return new Response(page, { status, headers: { "Content-Type": "text/html; charset=utf-8" }, }); } async function sendMail( env: Env, m: { name: string; email: string; message: string }, ): Promise<void> { const res = await fetch("https://api.resend.com/emails", { method: "POST", headers: { Authorization: `Bearer ${env.RESEND_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ from: env.CONTACT_FROM, to: [env.CONTACT_TO], reply_to: m.email, subject: `Contact form: ${m.name}`, text: `${m.message}\n\n${m.name} <${m.email}>`, }), }); if (!res.ok) throw new Error(`Resend ${res.status}: ${await res.text()}`); } A few details that matter:
- Validate on the server even though the HTML already does. The
requiredandmaxlengthattributes are a courtesy to people. A bot posts straight to the URL and never sees them. - The honeypot returns success. An error would tell the bot author what to change.
- Two response shapes. A normal form post gets a 303 redirect or a small HTML error page. The
fetchversion below asks for JSON with anAcceptheader and gets{"ok": true}or a list of field errors. - Newlines are flattened in the name, because it goes into the email subject.
Where the message goes
The example emails each message to you through Resend’s HTTP API, which needs a verified sending domain and an API key. If you’d rather not use a third party, Cloudflare’s send_email binding can email a verified address on your own account for free. Both are covered, with working code, in Send email from a Worker contact form.
Email alone has one weakness: if delivery fails, the message is gone. The handler above at least tells the visitor so they can retry. If you can’t afford to lose a single message, save it to a D1 table first and send the email afterwards with waitUntil. The Pages Functions guide shows the D1 version.
Progressive enhancement: submit without a page load
The form already works. This script makes it nicer for visitors with JavaScript: it posts in the background, shows the result in the status line, and leaves the plain POST as the fallback. Put it at the bottom of ContactForm.astro.
<script> // Progressive enhancement: without JavaScript the form still posts normally. for (const form of document.querySelectorAll<HTMLFormElement>("form.contact")) { const status = form.querySelector<HTMLElement>(".form-status")!; const button = form.querySelector<HTMLButtonElement>('button[type="submit"]')!; form.addEventListener("submit", async (event) => { event.preventDefault(); button.disabled = true; status.textContent = "Sending…"; let text = "Thanks! Your message was sent."; try { const res = await fetch(form.action, { method: "POST", body: new FormData(form), headers: { Accept: "application/json" }, }); const data = await res.json().catch(() => ({})); if (res.ok) { form.reset(); } else { const first = Object.values(data.errors ?? {})[0]; text = String(first ?? "Something went wrong. Please try again."); } } catch { text = "Network error. Please check your connection and try again."; } status.textContent = text; button.disabled = false; }); } </script> Astro processes and bundles a <script> tag like this one as a module, so TypeScript works, it runs after the HTML is parsed, and it’s included once even if the form appears twice on a page. The script never decides whether a submission is valid. It only shows what the server said.
Run it locally and deploy
astro dev doesn’t run the functions/ folder, so /api/contact returns a 404 there. Build the site and serve it with Wrangler instead, which runs your Function next to the static files:
npx astro build npx wrangler pages dev dist # .dev.vars (local only, add it to .gitignore) RESEND_API_KEY=re_xxxxxxxx CONTACT_TO=you@example.com CONTACT_FROM=Website <forms@yourdomain.com> For production, add CONTACT_TO and CONTACT_FROM as variables and RESEND_API_KEY as a secret in the Pages project under Settings → Variables and Secrets, or from the terminal:
npx wrangler pages secret put RESEND_API_KEY --project-name=my-astro-site Then push to the connected repo, or upload dist with npx wrangler pages deploy dist. Run that from the project root so Wrangler picks up the functions/ folder too.
The adapter version, briefly
If you go the adapter route, add it with:
npx astro add cloudflare Leave output at its default. Pages stay prerendered, and only routes that opt out run on request. The endpoint uses the same logic with Astro’s endpoint API:
// src/pages/api/contact.ts import type { APIRoute } from "astro"; import { env } from "cloudflare:workers"; export const prerender = false; // run on request, not at build time export const POST: APIRoute = async ({ request, redirect }) => { const wantsJson = (request.headers.get("Accept") ?? "").includes("application/json"); const form = await request.formData(); if (form.get("website")) { return wantsJson ? Response.json({ ok: true }) : redirect("/thanks/", 303); } // ...the same validation and sendMail(env, ...) as the Pages Function... return wantsJson ? Response.json({ ok: true }) : redirect("/thanks/", 303); }; Differences from the Function:
- Variables and secrets come from
import { env } from "cloudflare:workers". If you needwaitUntil, it’s onlocals.cfContext. -
astro devruns on Cloudflare’sworkerdruntime in Astro 6, so the endpoint works in dev. Put local secrets in.dev.vars. - Astro’s
security.checkOriginis on by default for on-demand routes. Same-origin form posts pass, but a form on another domain posting to this endpoint gets a 403.
npx astro build npx wrangler deploy npx wrangler secret put RESEND_API_KEY Add Turnstile when bots get past the honeypot
The honeypot plus server-side validation stops most low-effort spam. If a targeted bot gets through, add Cloudflare Turnstile. It’s free and usually invisible. Add the widget inside the form:
<div class="cf-turnstile" data-sitekey={import.meta.env.PUBLIC_TURNSTILE_SITE_KEY}></div> <script is:inline src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script> The Turnstile script needs is:inline so Astro loads it from Cloudflare as-is instead of trying to bundle it. The site key is public, so a PUBLIC_ variable is fine. The secret key is not. Store it as TURNSTILE_SECRET next to your other secrets and check every token on the server:
// In the handler, after the honeypot check and before sending anything: const verify = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ secret: env.TURNSTILE_SECRET, response: String(form.get("cf-turnstile-response") ?? ""), remoteip: request.headers.get("CF-Connecting-IP") ?? undefined, }), }); const outcome = (await verify.json()) as { success: boolean }; if (!outcome.success) { return fail(wantsJson, 400, { form: "Please complete the verification and try again." }); } Each token works only once, so after a failed fetch submission, call window.turnstile?.reset() before letting the visitor retry. If you use Astro’s <ClientRouter /> for view transitions, the widget won’t render itself again after a client-side navigation. Render it explicitly with turnstile.render() on the astro:page-load event. The same goes for the enhancement script above: bundled scripts run once per full page load, so with the client router, wrap the loop in a document.addEventListener("astro:page-load", …) listener. Time traps, link rules, and rate limiting are covered in Stop contact form spam without a CAPTCHA.
Before you call it done
- Turn JavaScript off and submit. You should land on
/thanks/, and the email should arrive. - Submit a one-word message and check that the error makes sense, both with and without JavaScript.
- Fill the honeypot from the dev tools and confirm nothing is sent, even though the page says it was.
- Reply to a test email and check that the reply goes to the visitor’s address, not to your sending address.
If you’d rather start from a finished site
For an existing Astro site, the code above is all you need. If you’re starting a new site and would rather not wire this up yourself, the Formharbor Astro Starter ($39) is an Astro 7 site for Cloudflare Pages built around the same Pages Function approach. Its contact form adds server-side Turnstile and optional D1 storage, and the starter comes with a blog, RSS, a sitemap, and SEO tags.
Related guides, all free to read:
- Stop contact form spam without a CAPTCHA
- Contact form with Pages Functions
- Send email from a Worker contact form
- Turnstile contact form tutorial
- Free contact form for Hugo, Astro, and Eleventy
- Add a contact form to Cloudflare Pages
- A free Formspree alternative
- Netlify Forms alternative on Cloudflare
