Steve Putala

Web application developer

Contact form using Cloudflare Workers and AWS Simple Email Service to get messages

How to use Cloudflare to build a contact form, Turnstile to block spam, D1 to store the submissions and Amazon Simple Email Service (SES) to get notified about messages.

This checklist assumes you are using Cloudflare to serve a static version of your website, I will update the instructions and customization (eventually) for stand-alone contact forms that you can embed into any Content Management System (CMS).

This checklist remembers where you left off, only in this browser. when you want to start fresh

How it works

This plan runs the web site and the form as one Cloudflare Worker with static assets. It serves a static site, handles POST /api/contact, and sends a spam message digest on a schedule.

Browser on example.com/contact/ → HTML form + Turnstile widget (+ honeypot field, render timestamp) → POST /api/contact (same origin; works with or without JS)

Worker src/index.js fetch()

  1. Validate fields (required, lengths, email format) → 400 with a message if invalid (not stored)
  2. Spam checks: Turnstile siteverify, honeypot, time trap, no JavaScript → status 'ok' or 'spam' + spam_reason
  3. Store the row in D1 (including the IP) ← submission is safe from here on
  4. Handle notification email
  • ok → email you now via SES (Reply-To = sender) → email_status sent | failed
  • spam → email_status 'queued' (no email now; it goes in the next digest)
  1. Respond: JSON for fetch(), or a 303 redirect to /contact/thanks/ for a plain POST
  • (spam gets the same success response, so bots learn nothing)

All other paths → static files from public/ (404.html for missing pages)

Worker scheduled on weekdays at 8,16 in America/New_York

  • if any spam is queued, send one digest with all of it and mark those rows sent

Move DNS to Cloudflare

Do this first. Cloudflare needs to host your domain's DNS for the Worker's custom domain, and it's where the SES records go. Moving nameservers only changes who answers DNS queries. Your email and current website keep working, as long as every record is copied exactly.

Before you switch

    • If a record points at a host-specific resource name (such as a load balancer or distribution) rather than an IP or hostname, Cloudflare can't copy it as-is. Use the resource's IP or hostname instead.
    • Skip the NS and SOA records; Cloudflare creates its own.

Add the site in Cloudflare

    • MX: your mail provider's records exactly as they are now including the Priority level
    • SPF TXT on @, e.g. v=spf1 include:_spf.google.com ~all
    • DKIM TXT, e.g. google._domainkey. The scan often misses or truncates long values, so compare it with your mail provider's admin console.
    • DMARC TXT _dmarc, if you have one
    • every verification TXT record (e.g. google-site-verification), and any other TXT or CNAME records (e.g. mail, calendar)
    • the A records for @ and www pointing at your current web server (or www as a CNAME to example.com, whichever you have now)

Switch

Verify

  1. dig NS example.com +short
    dig MX example.com @1.1.1.1 +short
    dig TXT example.com +short
    dig TXT google._domainkey.example.com +short
    The first should show Cloudflare's nameservers, the MX your mail provider, and the TXT records should match the old values.

Turnstile

AWS SES

Everything here is in the AWS console, in the us-east-1 region. Check the region picker at the top right before each step: SES identities and sandbox status are per region.

Create the domain identity

    • MAIL FROM domain: bounce, which becomes bounce.example.com
    • Behavior on MX failure: Use default MAIL FROM domain

Add the DNS records in Cloudflare

Cloudflare → example.com → DNS → Records. In the Name field, enter only the part before .example.com; Cloudflare adds the domain itself.

Type Name Content Notes
CNAME <token1>._domainkey <token1>.dkim.amazonses.com ×3. Copy the three tokens exactly from the SES identity page
CNAME <token2>._domainkey <token2>.dkim.amazonses.com
CNAME <token3>._domainkey <token3>.dkim.amazonses.com
MX bounce.example.com feedback-smtp.us-east-1.amazonses.com, priority 10 Only for the bounce subdomain; the MX on @ stays as-is
TXT bounce.example.com v=spf1 include:amazonses.com ~all SPF for the bounce subdomain only

Wait for verification

    • Identity status: Verified
    • DKIM: Successful
    • Custom MAIL FROM: Success

    This usually takes minutes, and at most 72 hours. If it's stuck, check the records:

    dig CNAME <token1>._domainkey.example.com +short
    dig MX bounce.example.com +short

    The first should return the amazonses.com target, the second the feedback-smtp host.

New SES accounts are in the sandbox: they can only send to verified identities, up to 200 emails a day. A verified domain counts, so the example.com identity already covers you@example.com if it's on that domain. A recipient on another domain, such as a personal Gmail, needs its own email address identity. Every email from this form goes only to you, so the sandbox is enough: don't request production access.

Send a test email

    • SPF: PASS with bounce.example.com
    • DKIM: PASS with domain example.com
    • DMARC: PASS

Create a send-only IAM key for the Worker

Create IAM Policy

  1. {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "ContactFormSendOnly",
          "Effect": "Allow",
          "Action": "ses:SendEmail",
          "Resource": "arn:aws:ses:us-east-1:<ACCOUNT_ID>:identity/example.com",
          "Condition": {
            "StringEquals": { "ses:FromAddress": "contact@example.com" }
          }
        }
      ]
    }
    • In the sandbox, SES also checks permission on the recipient's identity. For a recipient on example.com that's the same identity, so one ARN covers both.
    • The condition means the key can only send as contact@example.com.

Create IAM User

Build the project


  public/                  your built static site
  src/index.js             the Worker: /api/contact, the spam digest cron, falls through to static files
  migrations/0001_init.sql D1 schema
  wrangler.jsonc           name, assets, D1 binding, cron trigger, vars
  package.json             aws4fetch, wrangler
  .dev.vars.example        local secrets template (Turnstile test keys)

Repository

D1 database

  1. npx wrangler d1 create example-contact-form-db
    Keep the database_id it prints for wrangler.jsonc (next).

Wrangler configuration

    • compatibility_date: replace <YYYY-MM-DD> with today's date
    • database_id: replace <from wrangler d1 create> with the database_id from the previous step:
    {
      "name": "example-contact-form",
      "main": "src/index.js",
      "compatibility_date": "<YYYY-MM-DD>",
    
      "assets": {
        "directory": "./public",
        "binding": "ASSETS",
        "not_found_handling": "404-page", // serves public/404.html
        "run_worker_first": ["/api/*"]
      },
    
      "triggers": {
        // UTC; the code keeps only weekdays at 8,16 in America/New_York
        "crons": ["0 <UTC_HOURS> * * *"]
      },
    
      "d1_databases": [
        {
          "binding": "DB",
          "database_name": "example-contact-form-db",
          "database_id": "<from wrangler d1 create>"
        }
      ],
    
      "vars": {
        "AWS_REGION": "us-east-1",
        "MAIL_TO": "you@example.com",
        "MAIL_FROM": "contact@example.com",
        "MAIL_FROM_NAME": "Example",
        "TURNSTILE_SITE_KEY": "<TURNSTILE_SITE_KEY>",
        "DIGEST_TIMEZONE": "America/New_York",
        "DIGEST_HOURS": "8,16"
      }
    }
    • Cron triggers are always UTC and don't follow daylight saving. The schedule above runs at each digest hour in both standard and summer time, so the digest always arrives on time locally. Each run checks the local time in DIGEST_TIMEZONE and only continues on a weekday at one of the DIGEST_HOURS; the other runs exit straight away.
    • The day of the week is * because a local weekday can fall on a different UTC day. The code does the weekday check instead.
  1. # Local settings for `npx wrangler dev`. Copy this file to .dev.vars,
    # which is git-ignored. Production secrets are set with `wrangler secret put`.
    
    # Turnstile test secret key that always passes:
    TURNSTILE_SECRET_KEY="1x0000000000000000000000000000000AA"
    # Swap in this one, which always fails, to test the turnstile spam check:
    # TURNSTILE_SECRET_KEY="2x0000000000000000000000000000000AA"
    
    # Stub SES: "log" prints each email instead of sending it, "fail" makes
    # every send fail (to test the digest retry). Never set in production.
    SES_STUB="log"

Database schema

  1. CREATE TABLE spam_digests (
      id         INTEGER PRIMARY KEY AUTOINCREMENT,
      created_at TEXT NOT NULL DEFAULT (datetime('now')),
      status     TEXT NOT NULL DEFAULT 'sending',          -- sending | sent | failed
      count      INTEGER,
      error      TEXT
    );
    
    CREATE TABLE submissions (
      id           INTEGER PRIMARY KEY AUTOINCREMENT,
      created_at   TEXT    NOT NULL DEFAULT (datetime('now')),
      name         TEXT    NOT NULL,
      email        TEXT    NOT NULL,
      message      TEXT    NOT NULL,
      status       TEXT    NOT NULL DEFAULT 'ok',      -- ok | spam
      spam_reason  TEXT,                               -- turnstile | honeypot | too_fast | no_js (comma-joined)
      email_status TEXT    NOT NULL DEFAULT 'pending', -- ok rows: pending | sent | failed; spam rows: queued | sending | sent
      email_error  TEXT,
      digest_id    INTEGER REFERENCES spam_digests (id),
      ip           TEXT,                               -- CF-Connecting-IP
      country      TEXT,                               -- request.cf.country
      user_agent   TEXT
    );
    CREATE INDEX submissions_created_at ON submissions (created_at);
    CREATE INDEX submissions_queued ON submissions (email_status) WHERE email_status = 'queued';
  2. npx wrangler d1 migrations apply example-contact-form-db --local
    npx wrangler d1 migrations apply example-contact-form-db --remote
    • If the remote command fails try logging out and back in with the commands

Rows are kept forever. To read submissions later, use the D1 console in the Cloudflare dashboard, or:

npx wrangler d1 execute example-contact-form-db --remote --command "SELECT id, created_at, status, name, email FROM submissions ORDER BY id DESC LIMIT 20"

The Worker

  1. import { AwsClient } from "aws4fetch";
    
    const LIMITS = { name: 100, email: 254, message: 5000 };
    const MIN_ELAPSED_MS = 3000;           // faster than this is a bot
    const THANKS_PATH = "/contact/thanks/"; // where a plain (no-JavaScript) POST lands
    const DIGEST_PREVIEW = 5;              // spam messages shown in full in each digest
    const EMAIL = /^[^\s@<>,;"]+@[^\s@<>,;"]+\.[^\s@<>,;"]+$/;
    
    export default {
        async fetch( request, env, ctx ) {
            const url = new URL( request.url );
    
            if ( url.pathname === "/api/contact" ) {
                if ( request.method !== "POST" ) {
                    return new Response( "Method not allowed", { status: 405, headers: { Allow: "POST" } } );
                }
    
                return handleContact( request, env, ctx );
            }
    
            // Everything else is the static site (404.html for missing pages).
            return env.ASSETS.fetch( request );
        },
    
        async scheduled( controller, env ) {
            const now = new Date( controller.scheduledTime );
    
            // The cron runs at every UTC hour a digest hour can fall on, in
            // both standard and daylight saving time. Only one of them is right.
            if ( isDigestTime( now, env ) ) {
                await sendDigest( env );
            }
        }
    };
    
    // ---- Contact form ------------------------------------------------------
    
    async function handleContact( request, env, ctx ) {
        // The page's script asks for JSON; a plain form POST gets a redirect.
        const wantsJson = ( request.headers.get( "Accept" ) || "" ).includes( "application/json" );
        let form;
    
        try {
            form = await request.formData();
        } catch {
            return reply( wantsJson, 400, "The form couldn't be read. Please try again." );
        }
    
        const field = key => String( form.get( key ) ?? "" ).trim();
        const name = field( "name" ).replace( /\s+/g, " " );
        const email = field( "email" );
        const message = field( "message" );
        const error = validate( name, email, message );
    
        // Typos, not spam: tell the visitor and don't store anything.
        if ( error ) {
            return reply( wantsJson, 400, error );
        }
    
        const reasons = await spamReasons( request, env, form );
        const status = reasons.length ? "spam" : "ok";
        const ip = request.headers.get( "CF-Connecting-IP" );
        const country = request.cf?.country ?? null;
        const userAgent = ( request.headers.get( "User-Agent" ) || "" ).slice( 0, 500 ) || null;
        let id;
    
        try {
            const result = await env.DB.prepare(
                `INSERT INTO submissions (name, email, message, status, spam_reason, email_status, ip, country, user_agent)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
            ).bind(
                name, email, message, status, reasons.join( "," ) || null,
                status === "ok" ? "pending" : "queued",
                ip, country, userAgent
            ).run();
    
            id = result.meta.last_row_id;
        } catch ( err ) {
            console.error( "D1 insert failed", err );
    
            return reply( wantsJson, 500, "Sorry, your message couldn't be saved. Please try again later." );
        }
    
        // Stored, so nothing is lost if the email fails. Genuine messages are
        // emailed now, without making the visitor wait; spam waits for the digest.
        if ( status === "ok" ) {
            ctx.waitUntil( notify( env, { id, name, email, message, ip, country } ) );
        }
    
        // Spam gets the same answer, so bots learn nothing.
        return reply( wantsJson, 200, "Thanks, your message was sent." );
    }
    
    function validate( name, email, message ) {
        if ( !name || !email || !message ) {
            return "Please fill in your name, email and message.";
        }
    
        if ( name.length > LIMITS.name ) {
            return `Please keep your name to ${ LIMITS.name } characters or fewer.`;
        }
    
        if ( email.length > LIMITS.email || !EMAIL.test( email ) ) {
            return "Please enter one valid email address.";
        }
    
        if ( message.length > LIMITS.message ) {
            return `Please keep your message to ${ LIMITS.message } characters or fewer.`;
        }
    
        return null;
    }
    
    async function spamReasons( request, env, form ) {
        const reasons = [];
    
        if ( !await turnstilePasses( request, env, form ) ) {
            reasons.push( "turnstile" );
        }
    
        if ( String( form.get( "website" ) ?? "" ).trim() ) {
            reasons.push( "honeypot" );
        }
    
        // The page's script fills in elapsed_ms when the form is sent, so a
        // POST without it came from a browser with JavaScript off, or a bot.
        const elapsed = Number( form.get( "elapsed_ms" ) || NaN );
    
        if ( !Number.isFinite( elapsed ) ) {
            reasons.push( "no_js" );
        } else if ( elapsed < MIN_ELAPSED_MS ) {
            reasons.push( "too_fast" );
        }
    
        return reasons;
    }
    
    async function turnstilePasses( request, env, form ) {
        const token = form.get( "cf-turnstile-response" );
    
        if ( !token ) {
            return false;
        }
    
        const body = new FormData();
        const ip = request.headers.get( "CF-Connecting-IP" );
    
        body.append( "secret", env.TURNSTILE_SECRET_KEY );
        body.append( "response", token );
    
        if ( ip ) {
            body.append( "remoteip", ip );
        }
    
        try {
            const response = await fetch( "https://challenges.cloudflare.com/turnstile/v0/siteverify", { method: "POST", body } );
            const outcome = await response.json();
    
            // The token must be for this site (your domain, or workers.dev while
            // testing). Turnstile's test keys don't report your hostname, so the
            // check is skipped locally, where SES_STUB is set.
            const hostname = new URL( request.url ).hostname;
    
            return outcome.success === true && ( Boolean( env.SES_STUB ) || outcome.hostname === hostname );
        } catch ( err ) {
            // Turnstile unreachable: the message is kept as spam, so it still
            // reaches you in the next digest.
            console.error( "Turnstile siteverify failed", err );
    
            return false;
        }
    }
    
    function reply( wantsJson, status, message ) {
        if ( wantsJson ) {
            const body = status === 200 ? { ok: true, message } : { ok: false, error: message };
    
            return Response.json( body, { status } );
        }
    
        if ( status === 200 ) {
            return new Response( null, { status: 303, headers: { Location: THANKS_PATH } } );
        }
    
        const html = `<!doctype html><meta charset="utf-8"><title>Message not sent</title>
            <p>${ escapeHtml( message ) }</p><p><a href="javascript:history.back()">Go back to the form</a></p>`;
    
        return new Response( html, { status, headers: { "Content-Type": "text/html; charset=utf-8" } } );
    }
    
    async function notify( env, submission ) {
        const text = [
            `Name:    ${ submission.name }`,
            `Email:   ${ submission.email }`,
            `Time:    ${ new Date().toISOString().replace( "T", " " ).slice( 0, 16 ) } UTC`,
            `Country: ${ submission.country ?? "unknown" }`,
            `IP:      ${ submission.ip ?? "unknown" }`,
            `ID:      ${ submission.id }`,
            "",
            submission.message
        ].join( "\n" );
    
        try {
            await sendEmail( env, {
                subject: `Contact form: ${ submission.name }`,
                text,
                replyTo: submission.email
            });
    
            await env.DB.prepare( "UPDATE submissions SET email_status = 'sent' WHERE id = ?" )
                .bind( submission.id ).run();
        } catch ( err ) {
            console.error( "Email failed", err );
    
            await env.DB.prepare( "UPDATE submissions SET email_status = 'failed', email_error = ? WHERE id = ?" )
                .bind( String( err.message || err ).slice( 0, 1000 ), submission.id ).run();
        }
    }
    
    // ---- Spam digest -------------------------------------------------------
    
    function localTime( date, timeZone ) {
        const parts = new Intl.DateTimeFormat( "en-US", {
            timeZone, weekday: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23"
        }).formatToParts( date );
        const get = type => parts.find( part => part.type === type ).value;
    
        return { weekday: get( "weekday" ), hour: Number( get( "hour" ) ), minute: Number( get( "minute" ) ),
            label: `${ get( "weekday" ) } ${ get( "hour" ) }:${ get( "minute" ) }` };
    }
    
    function isDigestTime( date, env ) {
        const { weekday, hour, minute } = localTime( date, env.DIGEST_TIMEZONE );
        const hours = env.DIGEST_HOURS.split( /[\s,]+/ ).map( Number );
    
        return weekday !== "Sat" && weekday !== "Sun" && minute === 0 && hours.includes( hour );
    }
    
    async function sendDigest( env ) {
        const db = env.DB;
        const digest = await db.prepare( "INSERT INTO spam_digests DEFAULT VALUES" ).run();
        const digestId = digest.meta.last_row_id;
    
        // Claim everything queued in one statement, so an overlapping run can't
        // send the same rows twice.
        const claim = await db.prepare(
            "UPDATE submissions SET email_status = 'sending', digest_id = ? WHERE email_status = 'queued'"
        ).bind( digestId ).run();
        const count = claim.meta.changes;
    
        if ( !count ) {
            await db.prepare( "DELETE FROM spam_digests WHERE id = ?" ).bind( digestId ).run();
    
            return;
        }
    
        try {
            const last = await db.prepare(
                "SELECT created_at FROM spam_digests WHERE status = 'sent' ORDER BY id DESC LIMIT 1"
            ).first();
            const { results: reasonRows } = await db.prepare(
                "SELECT spam_reason FROM submissions WHERE digest_id = ?"
            ).bind( digestId ).all();
            const { results: recent } = await db.prepare(
                `SELECT id, created_at, name, email, message, country, ip, spam_reason
                 FROM submissions WHERE digest_id = ? ORDER BY id DESC LIMIT ?`
            ).bind( digestId, DIGEST_PREVIEW ).all();
    
            const tally = new Map();
    
            reasonRows.forEach( row => ( row.spam_reason || "unknown" ).split( "," ).forEach( reason => {
                tally.set( reason, ( tally.get( reason ) || 0 ) + 1 );
            }) );
    
            const fromUtc = text => new Date( text.replace( " ", "T" ) + "Z" );
            const since = last ? ` since ${ localTime( fromUtc( last.created_at ), env.DIGEST_TIMEZONE ).label }` : "";
            const noun = count === 1 ? "submission" : "submissions";
            const lines = [
                `${ count } contact form spam ${ noun }${ since }.`,
                `By reason: ${ [ ...tally ].map( ( [ reason, n ] ) => `${ reason }: ${ n }` ).join( ", " ) }`,
                "",
                count > DIGEST_PREVIEW ? `The ${ DIGEST_PREVIEW } most recent:` : "Messages:"
            ];
    
            recent.forEach( row => {
                const message = row.message.length > 500 ? row.message.slice( 0, 500 ) + "…" : row.message;
    
                lines.push(
                    "",
                    `--- #${ row.id }, ${ localTime( fromUtc( row.created_at ), env.DIGEST_TIMEZONE ).label }, ` +
                        `${ row.country ?? "?" }, ${ row.ip ?? "?" }, reason: ${ row.spam_reason }`,
                    `${ row.name } <${ row.email }>`,
                    message
                );
            });
    
            lines.push(
                "",
                "See them all with:",
                `npx wrangler d1 execute example-contact-form-db --remote --command "SELECT id, created_at, name, email, spam_reason, message FROM submissions WHERE digest_id = ${ digestId }"`
            );
    
            // No Reply-To: replying to spam shouldn't reach the sender.
            await sendEmail( env, { subject: `[SPAM] ${ count } contact form spam ${ noun }${ since }`, text: lines.join( "\n" ) } );
    
            await db.batch( [
                db.prepare( "UPDATE submissions SET email_status = 'sent' WHERE digest_id = ?" ).bind( digestId ),
                db.prepare( "UPDATE spam_digests SET status = 'sent', count = ? WHERE id = ?" ).bind( count, digestId )
            ] );
        } catch ( err ) {
            // Put the rows back, so the next digest includes them.
            console.error( "Spam digest failed", err );
    
            await db.batch( [
                db.prepare( "UPDATE submissions SET email_status = 'queued', digest_id = NULL WHERE digest_id = ?" ).bind( digestId ),
                db.prepare( "UPDATE spam_digests SET status = 'failed', count = ?, error = ? WHERE id = ?" )
                    .bind( count, String( err.message || err ).slice( 0, 1000 ), digestId )
            ] );
        }
    }
    
    // ---- Email (SES v2 SendEmail, signed with aws4fetch) -------------------
    
    async function sendEmail( env, { subject, text, replyTo } ) {
        // Local development only: SES_STUB is set in .dev.vars.
        if ( env.SES_STUB === "fail" ) {
            throw new Error( "SES_STUB is set to fail" );
        }
    
        if ( env.SES_STUB ) {
            console.log( `[SES stub] To: ${ env.MAIL_TO }\nReply-To: ${ replyTo ?? "-" }\nSubject: ${ subject }\n\n${ text }` );
    
            return;
        }
    
        const aws = new AwsClient({
            accessKeyId: env.AWS_ACCESS_KEY_ID,
            secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
            region: env.AWS_REGION,
            service: "ses"
        });
    
        const message = {
            FromEmailAddress: `${ displayName( env.MAIL_FROM_NAME ) } <${ env.MAIL_FROM }>`,
            Destination: { ToAddresses: [ env.MAIL_TO ] },
            Content: {
                Simple: {
                    Subject: { Data: subject.slice( 0, 200 ), Charset: "UTF-8" },
                    Body: { Text: { Data: text, Charset: "UTF-8" } }
                }
            }
        };
    
        if ( replyTo ) {
            message.ReplyToAddresses = [ replyTo ];
        }
    
        const response = await aws.fetch( `https://email.${ env.AWS_REGION }.amazonaws.com/v2/email/outbound-emails`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify( message )
        });
    
        if ( !response.ok ) {
            throw new Error( `SES ${ response.status }: ${ ( await response.text() ).slice( 0, 500 ) }` );
        }
    }
    
    // A From display name: quoted, or MIME-encoded when it isn't plain ASCII.
    function displayName( name ) {
        const clean = String( name || "" ).replace( /["\\\r\n]/g, "" ).trim();
    
        if ( /^[\x20-\x7e]*$/.test( clean ) ) {
            return `"${ clean }"`;
        }
    
        const bytes = new TextEncoder().encode( clean );
    
        return `=?UTF-8?B?${ btoa( String.fromCharCode( ...bytes ) ) }?=`;
    }
    
    function escapeHtml( text ) {
        return String( text ).replace( /[&<>"']/g, char => `&#${ char.charCodeAt( 0 ) };` );
    }
    • THANKS_PATH: change it if your thanks page isn't at /contact/thanks/.
    • Genuine messages are emailed straight away with Reply-To set to the sender. Spam is stored as queued and goes out in the next weekday digest at 8,16 in America/New_York.
    • A submission is spam if any check fails, and every reason is kept in spam_reason (e.g. turnstile,no_js): turnstile (no token, a failed siteverify, or a token for another hostname), honeypot (the hidden website field is filled in), no_js (sent without JavaScript) and too_fast (sent within 3 seconds of the page loading).
    • Missing fields, a name over 100 characters, an email that isn't exactly one valid address (up to 254 characters) and a message over 5,000 characters get a 400 with a message, and aren't stored.

Contact page

  1. <form id="contact-form" action="/api/contact" method="post">
        <p>
            <label for="contact-name">Name</label>
            <input id="contact-name" name="name" type="text" required maxlength="100" autocomplete="name">
        </p>
        <p>
            <label for="contact-email">Email</label>
            <input id="contact-email" name="email" type="email" required maxlength="254" autocomplete="email">
        </p>
        <p>
            <label for="contact-message">Message</label>
            <textarea id="contact-message" name="message" required maxlength="5000" rows="8"></textarea>
        </p>
    
        <!-- Honeypot: off-screen for people; bots fill it in. -->
        <div aria-hidden="true" style="position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden;">
            <label for="contact-website">Website</label>
            <input id="contact-website" name="website" type="text" tabindex="-1" autocomplete="off">
        </div>
    
        <!-- Time on the page, filled in by the script below. Empty means no JavaScript. -->
        <input type="hidden" name="elapsed_ms">
    
        <div class="cf-turnstile" data-sitekey="<TURNSTILE_SITE_KEY>"></div>
    
        <noscript>
            <p>JavaScript is turned off, so your message will be held for review and may take longer to reach me.</p>
        </noscript>
    
        <p><button type="submit">Send</button></p>
        <p id="contact-status" role="status" aria-live="polite"></p>
    </form>
    
    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
    <script>
    ( function () {
        const form = document.getElementById( "contact-form" );
        const status = document.getElementById( "contact-status" );
        const button = form.querySelector( "button[type=submit]" );
        const loaded = Date.now();
    
        form.addEventListener( "submit", async function ( event ) {
            event.preventDefault();
    
            form.elements.elapsed_ms.value = Date.now() - loaded;
            button.disabled = true;
            status.textContent = "Sending…";
    
            try {
                const response = await fetch( form.action, {
                    method: "POST",
                    body: new FormData( form ),
                    headers: { Accept: "application/json" }
                });
                const result = await response.json();
    
                if ( response.ok && result.ok ) {
                    form.reset();
                    status.textContent = result.message;
                } else {
                    status.textContent = result.error || "Sorry, your message couldn't be sent. Please try again.";
                }
            } catch {
                status.textContent = "Sorry, your message couldn't be sent. Please check your connection and try again.";
            } finally {
                // Turnstile tokens work once, so get a fresh one for the next send.
                window.turnstile?.reset();
                button.disabled = false;
            }
        });
    })();
    </script>
    • With JavaScript, the form sends in the background and shows the result under the button.
    • Without JavaScript, it posts normally, is stored as spam (no_js, plus turnstile since the widget can't run) and lands on the thanks page. It reaches you in the next digest.
    • If your site sends a Content-Security-Policy header, allow https://challenges.cloudflare.com in script-src and frame-src.
  2. <h1>Thanks for your message</h1>
    <p>It's been received, and I'll get back to you as soon as I can.</p>
    <p><a href="/">Back to the home page</a></p>

Test locally

Run npx wrangler dev --test-scheduled. This uses the local D1 database, the Turnstile test keys and the SES stub.

Deploy

  1. npx wrangler secret put TURNSTILE_SECRET_KEY
    npx wrangler secret put AWS_ACCESS_KEY_ID
    npx wrangler secret put AWS_SECRET_ACCESS_KEY

Cutover

Optional extras

Two things you can skip:

If a send to you@example.com ever hard-bounces, SES adds the address to the account suppression list, and later sends silently fail. To clear it: SES → Suppression list → remove the address.