Duong Hoang Nam

Search Articles

Find AI, technology, and programming guides

Press Esc to closeFull Search Page →
Tutorials

How to Build a Secure Contact Form in Astro with Cloudflare Turnstile and Pages Functions (2026 Guide)

Build a secure Astro contact form with Cloudflare Turnstile, Pages Functions, server-side verification, input validation, and abuse protection.

By Duong Hoang Nam
How to Build a Secure Contact Form in Astro with Cloudflare Turnstile and Pages Functions (2026 Guide)

A contact form looks simple: a name, an email address, a message, and a submit button. But publishing a form on the open web introduces a backend problem. Anyone can call the submission endpoint directly, including automated scripts that never render your page.

In this tutorial, you’ll build an Astro contact form backed by Cloudflare Pages Functions and Cloudflare Turnstile. The site remains primarily static; a small edge function handles form submissions, verifies Turnstile tokens, validates input, and passes authorized messages to a delivery service.

What you’ll build: a /contact/ page, a POST /api/contact function, server-side Siteverify validation, a safe delivery boundary, and a practical security test plan. Examples are designed for a standard Astro static site deployed on Cloudflare Pages, not an untested copy of an existing site’s configuration.

1. Why a Client-Side Form Is Not Enough

HTML required fields and browser-side JavaScript improve usability, but neither protects a backend endpoint: an attacker can submit HTTP requests without visiting the form. A secure form needs checks at the receiving server or edge function.

The core security requirements are:

  • Validate name, email, message, and request size on the server.
  • Verify every Turnstile token with Cloudflare’s Siteverify API.
  • Keep secret keys out of public Astro HTML and client bundles.
  • Restrict the destination that receives messages.
  • Add abuse controls and safe error handling.

Turnstile helps distinguish legitimate visitors from automated abuse, but it does not deliver email, replace server-side validation, or guarantee that every submission is trustworthy.

2. Architecture: Astro + Turnstile + Pages Functions

The flow is intentionally short:

Visitor -> Astro contact form -> Turnstile token
                             -> POST /api/contact
                             -> Pages Function
                             -> Cloudflare Siteverify
                             -> Validate message
                             -> Delivery API / queue
                             -> Response to visitor

The browser receives a sitekey, which is public. The Pages Function reads the secret key from a server-side environment binding. It submits the token to Siteverify, and only then attempts a delivery operation.

Secure Astro contact form architecture showing browser, Turnstile, Pages Function, Siteverify and delivery service

Figure 1: A secure contact-form request must pass server-side verification before delivery.

3. Prerequisites

You’ll need:

  • An Astro project configured as a static site.
  • Deployment through Cloudflare Pages with support for Pages Functions.
  • A Turnstile widget with an allowed production hostname.
  • A delivery destination that you control, such as an email provider API or queue endpoint.
  • Local Node.js tooling and Cloudflare Wrangler for testing.

The sample uses the Pages file-based Functions directory at the project root. If your application already uses Astro’s Cloudflare server adapter, a custom Worker, or a different deployment mode, verify how routes are deployed before mixing approaches.

4. Create Your Turnstile Widget

In the Cloudflare dashboard, create a Turnstile widget for the contact form and configure its allowed hostnames. Save the sitekey and secret key separately.

For the example below, use a public sitekey accessible to your Astro build and a secret binding available only to the Pages Function:

PUBLIC_TURNSTILE_SITE_KEY=your-public-sitekey
TURNSTILE_SECRET_KEY=your-server-only-secret
CONTACT_DELIVERY_URL=https://your-trusted-delivery-endpoint.example/ingest
CONTACT_DELIVERY_TOKEN=your-server-only-delivery-token

PUBLIC_TURNSTILE_SITE_KEY is intentionally public. The three other values must never be prefixed PUBLIC_ or embedded in client-side HTML.

Treat the delivery URL as a fixed deployment setting, not a URL accepted from the contact form. Only configure a destination that you operate and trust.

5. Build the Astro Contact Page

Create src/pages/contact.astro. This compact version uses the Turnstile widget and a browser fetch handler so visitors see a success or error message without a full page reload.

---
const sitekey = import.meta.env.PUBLIC_TURNSTILE_SITE_KEY;
---

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Contact</title>
    <script
      src="https://challenges.cloudflare.com/turnstile/v0/api.js"
      async defer
    ></script>
  </head>
  <body>
    <main>
      <h1>Contact</h1>
      <form id="contact-form">
        <label>Name <input name="name" required maxlength="100" /></label>
        <label>Email <input name="email" type="email" required maxlength="254" /></label>
        <label>Message <textarea name="message" required maxlength="5000"></textarea></label>
        <div class="cf-turnstile" data-sitekey={sitekey}></div>
        <button type="submit">Send message</button>
        <p id="form-status" role="status" aria-live="polite"></p>
      </form>
    </main>
    <script>
      const form = document.querySelector<HTMLFormElement>('#contact-form');
      const status = document.querySelector<HTMLElement>('#form-status');
      form?.addEventListener('submit', async (event) => {
        event.preventDefault();
        if (!form || !status) return;
        const button = form.querySelector<HTMLButtonElement>('button[type="submit"]');
        if (button) button.disabled = true;
        status.textContent = 'Sending…';
        try {
          const res = await fetch('/api/contact', {
            method: 'POST',
            body: new FormData(form),
          });
          const result = await res.json() as { ok?: boolean; message?: string };
          status.textContent = result.message ?? 'Something went wrong.';
          if (res.ok && result.ok) form.reset();
        } catch {
          status.textContent = 'Network error. Please try again.';
        } finally {
          if (button) button.disabled = false;
          // Turnstile tokens expire and are single-use.
          (window as any).turnstile?.reset();
        }
      });
    </script>
  </body>
</html>

In a real site, embed the form inside your existing layout and accessibility styles rather than copying this full-page skeleton. The default Turnstile rendering mode and the browser widget need to load successfully before a valid token can be submitted.

6. Add a Pages Function for POST Requests

Create a file at the root of the project:

functions/api/contact.ts

Cloudflare Pages maps this to /api/contact. Use onRequestPost for the route. TypeScript is supported in the /functions directory; you can generate Cloudflare-specific types with Wrangler, or use a small local environment interface in a tutorial.

7. Verify the Token and Validate the Message

Here is a practical reference implementation. It expects a form submission, calls Siteverify, checks the verified hostname, and forwards a sanitized JSON payload to a trusted delivery endpoint.

interface Env {
  TURNSTILE_SECRET_KEY: string;
  CONTACT_DELIVERY_URL: string;
  CONTACT_DELIVERY_TOKEN: string;
  EXPECTED_TURNSTILE_HOSTNAME: string;
}

type TurnstileResult = {
  success?: boolean;
  hostname?: string;
  'error-codes'?: string[];
};

const json = (data: unknown, status = 200) =>
  new Response(JSON.stringify(data), {
    status,
    headers: {
      'content-type': 'application/json; charset=utf-8',
      'cache-control': 'no-store',
    },
  });

export const onRequestPost = async ({ request, env }: {
  request: Request;
  env: Env;
}) => {
  const size = Number(request.headers.get('content-length'));
  if (Number.isFinite(size) && size > 12_000) {
    return json({ ok: false, message: 'Request too large.' }, 413);
  }

  const type = request.headers.get('content-type') ?? '';
  if (!type.includes('multipart/form-data') &&
      !type.includes('application/x-www-form-urlencoded')) {
    return json({ ok: false, message: 'Unsupported content type.' }, 415);
  }

  let data: FormData;
  try {
    data = await request.formData();
  } catch {
    return json({ ok: false, message: 'Invalid form data.' }, 400);
  }

  const name = String(data.get('name') ?? '').trim();
  const email = String(data.get('email') ?? '').trim();
  const message = String(data.get('message') ?? '').trim();
  const token = String(data.get('cf-turnstile-response') ?? '');

  if (!name || name.length > 100 ||
      !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254 ||
      !message || message.length > 5000 ||
      !token || token.length > 2048) {
    return json({ ok: false, message: 'Check your input and verification.' }, 400);
  }

  if (!env.TURNSTILE_SECRET_KEY || !env.EXPECTED_TURNSTILE_HOSTNAME ||
      !env.CONTACT_DELIVERY_URL || !env.CONTACT_DELIVERY_TOKEN) {
    return json({ ok: false, message: 'Service is not configured.' }, 503);
  }

  let result: TurnstileResult;
  try {
    const body = new FormData();
    body.set('secret', env.TURNSTILE_SECRET_KEY);
    body.set('response', token);
    const response = await fetch(
      'https://challenges.cloudflare.com/turnstile/v0/siteverify',
      { method: 'POST', body }
    );
    if (!response.ok) throw new Error('Siteverify unavailable');
    result = await response.json() as TurnstileResult;
  } catch {
    return json({ ok: false, message: 'Verification is unavailable.' }, 503);
  }

  if (!result.success || result.hostname !== env.EXPECTED_TURNSTILE_HOSTNAME) {
    return json({ ok: false, message: 'Verification failed. Please retry.' }, 403);
  }

  try {
    const delivered = await fetch(env.CONTACT_DELIVERY_URL, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'authorization': `Bearer ${env.CONTACT_DELIVERY_TOKEN}`,
      },
      body: JSON.stringify({ name, email, message }),
    });
    if (!delivered.ok) throw new Error('Delivery rejected');
  } catch {
    return json({ ok: false, message: 'Message could not be delivered.' }, 502);
  }

  return json({ ok: true, message: 'Your message has been received.' });
};

Important security boundaries: This is a tutorial scaffold, not a certified production implementation. Enforce a real body-size limit at the edge before reading request bodies, rather than relying only on Content-Length, which can be missing or untrusted. Add rate limiting, delivery timeouts, controlled retries, and anti-duplicate processing before using it for important messages. Validate CONTACT_DELIVERY_URL as a trusted HTTPS destination in deployment configuration; do not turn it into an arbitrary user-supplied fetch target.

The CONTACT_DELIVERY_URL example requires your own delivery handler/provider that accepts this JSON and bearer authorization. Pages Functions does not automatically send email, and an HTTP 2xx from a queueing provider may mean accepted rather than delivered to an inbox.

Cloudflare Turnstile Siteverify server-side verification with success and failure branches

Figure 2: The Pages Function must call Siteverify; rendering a widget alone is not server-side protection.

8. Why Checking the Hostname Matters

A successful Siteverify response can include a hostname. Your backend should confirm it matches the expected site. Set EXPECTED_TURNSTILE_HOSTNAME to the exact host configured for the deployment, such as duonghoangnam.com (without a scheme or path). For staging, use a matching staging value and appropriately scoped widget keys.

This avoids confusing a valid token for a different host with authorization to submit to your production form. Cloudflare’s documentation also describes optional action and cdata fields; use them when your deployment needs additional context binding.

9. Store Secrets in Cloudflare, Not in Git

Configure server-only bindings in your Pages project for:

  • TURNSTILE_SECRET_KEY
  • CONTACT_DELIVERY_TOKEN
  • CONTACT_DELIVERY_URL
  • EXPECTED_TURNSTILE_HOSTNAME

Keep production and preview credentials separate. If you run a local development session, use the mechanism supported by your Wrangler/Pages setup for local secrets; never commit real secret values to the repository.

Also consider where form submissions will be delivered, how long they will be retained, and who can access the resulting personal information.

10. Test Valid, Invalid, and Replayed Submissions

Test both the UI and the backend. A browser displaying a green verification check is not proof that the server performed validation.

Scenario Expected behavior
Valid token and valid fields Accepted by delivery service
Missing token Rejected before delivery
Expired token Siteverify fails; visitor can retry
Reused token Rejected as duplicate/expired
Wrong hostname Rejected
Missing name or invalid email Rejected
Delivery service unavailable Safe failure message; no false success
Excess traffic Rate-limit policy applies
Very large body Rejected before expensive parsing

Cloudflare provides dedicated testing sitekeys and secrets. Use test credentials for automated tests rather than assuming production challenges will behave deterministically.

Secure contact form production validation, abuse protection and monitoring checklist

Figure 3: Test every security layer before enabling a production contact form.

11. Handle Token Expiration and Retries Correctly

Cloudflare documents that Turnstile tokens expire after 300 seconds and can be validated only once. After a failed request, refresh the widget to obtain a new token. Do not submit a previously verified token again.

There is a subtle delivery problem here: the token may be consumed before the downstream email provider times out. A blind retry using the same token can fail verification even if the first downstream request was accepted. For an important form, use a durable job ID and separate submission acceptance from later delivery retries.

12. Add Abuse Protection Beyond Turnstile

Turnstile should be one defense, not the only defense. Consider:

  • Cloudflare rate limiting for /api/contact and per-IP abuse patterns.
  • Request body limits enforced at the proxy/edge, plus content-size checks after parsing.
  • Input schema validation and message length caps.
  • A server-controlled destination, never arbitrary form-provided URLs.
  • Minimal logs with no raw messages, secrets, or full form submissions.
  • Optional honeypot fields as an additional low-cost signal, not as a substitute for verification.
  • Delivery provider restrictions, quotas, and alerts.

Avoid placing the sender’s email address into an untrusted email header without validation and escaping; use provider-supported reply_to fields appropriately.

13. Debug Common Issues

The widget appears, but every form submission fails: Check the sitekey/secret pairing, hostname allowlist, Siteverify response, and whether the token is fresh.

The form returns 404 on /api/contact: Verify that /functions/api/contact.ts exists at the Pages project root and that deployment actually includes Pages Functions. A locally generated static dist folder alone does not make that endpoint available.

The endpoint returns 503: Confirm all environment bindings and the Siteverify network call. Avoid logging tokens or secrets while troubleshooting.

The endpoint returns 502: The downstream delivery API was unavailable or rejected the request; diagnose your email provider independently of Turnstile.

The form works locally but not in preview: Verify environment-scoped keys and expected hostnames. Preview deployments may use different hostnames from production.

14. Production Deployment Checklist

  • The form uses HTTPS and accessible field labels.
  • The client sends the Turnstile token.
  • The server calls Siteverify for every submission.
  • Secret keys are stored server-side.
  • The verified hostname matches the expected deployment.
  • Input, content type, and body size are validated.
  • Request rate limits are enforced.
  • Delivery failures do not produce a false success message.
  • Message retention and privacy notices are appropriate.
  • Preview, production, timeout, and replay tests pass.

15. Frequently Asked Questions

Does Turnstile send form emails?

No. It provides a bot-management and token-verification component. You still need a separate email or delivery service.

Can Astro use Pages Functions without becoming fully server-rendered?

Yes, for a compatible static Astro deployment on Cloudflare Pages, a /functions directory can provide selected dynamic routes while most pages remain static.

Is verifying the token in JavaScript enough?

No. Client code can be bypassed. Verify every token server-side through Siteverify before trusting a submission.

Can I reuse Turnstile tokens after a network failure?

Do not assume so. Tokens expire after five minutes and are single-use. Refresh the widget and design delivery retries separately to avoid duplicate downstream actions.

Does this eliminate spam completely?

No anti-abuse control makes that guarantee. Use multiple layers, monitor actual traffic, and adjust limits to avoid rejecting legitimate visitors.

16. Final Thoughts

A secure Astro contact form separates presentation, verification, and delivery. Astro renders a fast form. Turnstile creates a challenge token. A Cloudflare Pages Function validates that token and the submitted fields before passing the message to a trusted service.

The most important lesson is simple: a visible CAPTCHA widget is not a substitute for server-side enforcement. Add request controls, measured delivery reliability, and careful handling of visitor information before calling the system production-ready.

Continue Reading

Official References

Disclosure: All code is illustrative and has not been executed against the author’s production website. Adapt to your Astro deployment, delivery provider, and security requirements before publishing a live form.

About the Author

Duong Hoang Nam

Duong Hoang Nam

Software engineer sharing practical tutorials, real-world experiments, and insights on AI tools, automation, and web development.

Read My Story →

Related Articles