Guide: Cloudflare Workers
A Cloudflare Worker contact form that sends through Resend
The Worker reads the form post, sends the mail through Resend's API, waits for Resend's answer and tells the visitor what really happened. Keep the API key in a Worker secret, send from a domain you verified in Resend, and hand the report of each send to ctx.waitUntil so it runs after the visitor has their answer.
- €2 a month per form€1 from the 11th
- 14-day trialCard added at the start
- Ready codeCloudflare Workers, Supabase Edge Functions, Astro sites on Cloudflare, Next.js sites on Vercel or Node.js and plain PHP sites, sending through Resend, and FormHaven forms with no code
- 01Verify your sending domain in Resend
- 02Add the HTML form
- 03Write the Worker
- 04Set the secrets and deploy
- 05Send one message and watch the log
- 06Report each send
Step 1
Verify your sending domain in Resend
Resend sends only from a domain you verified. Do this first: without it every send from the Worker comes back as a 403.
- On Resend's Domains page, press Add Domain and enter a subdomain such as
mail.example.com. Resend recommends a subdomain over the root domain. - Copy the DKIM and SPF records from the Records tab into Cloudflare DNS, exactly as Resend shows them. Set each CNAME to DNS only (grey cloud): a proxied record stops verification.
- Wait for the domain to show as verified. It often takes under 15 minutes; DNS can take up to 72 hours.
- Create an API key on the API Keys page. A key that can only send is enough.
MAIL_FROM | An address on the verified domain, for example Website <form@mail.example.com>. A plain variable. |
OWNER_TO | Where enquiries go. A plain variable, never read from the form. |
RESEND_API_KEY | The API key. A secret. |
Step 2
Add the HTML form
A plain form that posts name, email and message to the Worker's URL. It needs no JavaScript on your page.
The website field is a honeypot. People never see it; a bot that fills in every field fills it too, and the Worker then sends nothing. That also keeps a bot from using up your Resend quota.
The Worker answers with a short text page: "Thanks, your message was sent." when Resend accepted the mail, and an apology with a 502 when it did not.
<form action="https://contact-form.your-subdomain.workers.dev" method="POST">
<label>Name <input name="name" autocomplete="name"></label>
<label>Email <input name="email" type="email" autocomplete="email" required></label>
<label>Message <textarea name="message" rows="6" required></textarea></label>
<!-- Bots fill this in; people never see it. -->
<div aria-hidden="true" style="position:absolute; left:-9999px">
<label>Leave this empty <input name="website" tabindex="-1" autocomplete="off"></label>
</div>
<button type="submit">Send</button>
</form>
Step 3
Write the Worker
Save this as src/worker.js with the wrangler.toml below. What it does, in order:
- Refuses anything that is not a POST, and reads the form.
- Builds the mail. The recipient comes from
OWNER_TO, never from the form, and the visitor's address goes inreply_toso you can answer them. - Sends it through Resend and waits for Resend's answer, so the visitor is told what really happened.
- Logs the status and Resend's error name on a refusal.
- Hands the report of the send to
ctx.waitUntiland answers the visitor.
The bottom half is copied unchanged from the handler code DidMyFormSend ships: the Resend call, and the report with the recipient masked before it leaves the Worker.
name = "contact-form"
main = "src/worker.js"
compatibility_date = "2026-11-01"
[vars]
MAIL_FROM = "Website <form@mail.example.com>"
OWNER_TO = "you@example.com"
// Contact form handler for Cloudflare Workers, sending through Resend.
// It sends the message to you, waits for Resend's answer, tells the visitor what
// happened, and then reports the outcome of the send to your monitor.
//
// Secrets (set each with: npx wrangler secret put <NAME>):
// RESEND_API_KEY your Resend API key
// DIDMYFORMSEND_HEARTBEAT_KEY your monitor's heartbeat key (leave it unset and no report is sent)
// Variables (wrangler.toml [vars]):
// MAIL_FROM sender address on a domain you verified in Resend, for example "Website <form@mail.example.com>"
// OWNER_TO the address that receives the enquiries
//
// The form posts the fields name, email and message, plus an empty "website" field
// that people never see and bots fill in.
const HEARTBEAT_URL = "https://didmyformsend.com/api/v1/heartbeat";
const RESEND_URL = "https://api.resend.com/emails";
export default {
async fetch(request, env, ctx) {
if (request.method !== "POST") {
return new Response("Method not allowed", { status: 405, headers: { allow: "POST" } });
}
let form;
try {
form = await request.formData();
} catch {
return new Response("Could not read the form", { status: 400 });
}
const field = (name, max) => String(form.get(name) ?? "").trim().slice(0, max);
const name = field("name", 200);
const email = field("email", 254);
const message = field("message", 10000);
const mail = {
from: env.MAIL_FROM,
// Always from your settings, never from the form.
to: [env.OWNER_TO],
subject: name ? `New enquiry from ${name.replace(/\s+/g, " ")}` : "New enquiry",
text: `Name: ${name}\nEmail: ${email}\n\n${message}`,
};
if (/^[^\s@<>,;"]+@[^\s@<>,;"]+\.[^\s@<>,;"]+$/.test(email)) mail.reply_to = email;
const key = env.DIDMYFORMSEND_HEARTBEAT_KEY;
const report = (outcome) => {
if (typeof key !== "string" || key === "") return;
try {
ctx.waitUntil(sendHeartbeat(key, outcome, mail));
} catch {
// The report is optional: never let it change the visitor's answer.
}
};
// A bot filled in the hidden field: send nothing, report it as skipped on purpose.
if (field("website", 200) !== "") {
report({ result: "skipped", provider: "resend", occurred_at: Math.floor(Date.now() / 1000) });
return new Response("Thanks, your message was sent.", { status: 200 });
}
if (!message) return new Response("Please write a message", { status: 400 });
// Wait for Resend's answer, so the visitor is told the truth.
const outcome = await sendWithResend(env.RESEND_API_KEY, mail);
if (outcome.result !== "sent") {
console.log("Resend refused the send:", outcome.http_status, outcome.provider_status);
}
// The report runs after the visitor has their answer, and never changes it.
report(outcome);
return outcome.result === "sent"
? new Response("Thanks, your message was sent.", { status: 200 })
: new Response("Sorry, your message could not be sent. Please try again later.", { status: 502 });
},
};
// ---- Copied unchanged from the handler code DidMyFormSend ships ----
// Sends the mail and returns the report: Resend's real answer, read from its body.
async function sendWithResend(apiKey, mail) {
const report = { result: "failed", provider: "resend", occurred_at: Math.floor(Date.now() / 1000) };
let res;
try {
res = await fetch(RESEND_URL, {
method: "POST",
// Resend's docs say a request without a User-Agent is refused with 403, and
// Cloudflare Workers send none by default, so it is set here.
headers: {
authorization: `Bearer ${apiKey}`,
"content-type": "application/json",
"user-agent": "didmyformsend-snippet/1",
},
body: JSON.stringify(mail),
signal: AbortSignal.timeout(10000),
});
} catch (err) {
report.provider_status = err && err.name === "TimeoutError" ? "timeout" : "network_error";
return report;
}
report.http_status = res.status;
let body = null;
try {
body = await res.json();
} catch {
report.provider_status = "non_json_response";
return report;
}
const ok = res.ok && body && typeof body.id === "string" && body.id !== "" && !body.error;
if (ok) {
report.result = "sent";
report.provider_status = String(res.status);
const id = safe(body.id, /^[A-Za-z0-9_-]{1,64}$/);
if (id) report.event_id = id;
return report;
}
// Only Resend's short error code goes in the report, never its error sentence.
const code = body && (body.name ?? (body.error && body.error.name));
report.provider_status =
safe(code, /^[A-Za-z0-9_.:-]{1,64}$/) ?? (res.ok ? "no_message_id" : "unknown_error");
return report;
}
function safe(value, pattern) {
return typeof value === "string" && pattern.test(value) ? value : undefined;
}
async function sendHeartbeat(key, report, mail) {
try {
const recipients = await recipientsOf(mail);
await fetch(HEARTBEAT_URL, {
method: "POST",
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
body: JSON.stringify(recipients.length > 0 ? { ...report, recipients } : report),
signal: AbortSignal.timeout(3000),
});
} catch {
// Ignored on purpose: one attempt, no retry.
}
}
// Where this handler sends real enquiries, reduced here before it leaves your code: the
// first character and the domain of each address (j***@client.nl) and a SHA-256 of the
// whole address in lower case, so your monitor sees a change without ever getting the
// address. At most 5; an address it cannot read is left out.
async function recipientsOf(mail) {
const addresses = [];
for (const entry of [mail.to, mail.cc, mail.bcc].flat()) {
for (const part of String(entry ?? "").split(",")) {
const named = /<([^<>]*)>\s*$/.exec(part);
const address = (named ? named[1] : part).trim().toLowerCase();
if (address.length <= 254 && /^[a-z0-9._%+-]+@[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(address)
&& !addresses.includes(address) && addresses.length < 5) addresses.push(address);
}
}
return Promise.all(addresses.map(async (address) => {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(address)));
const sha256 = Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
return { masked: `${address[0]}***${address.slice(address.indexOf("@"))}`, sha256 };
}));
}
Step 4
Set the secrets and deploy
Keep the API key out of wrangler.toml and out of git. npx wrangler secret put asks for the value and stores it encrypted with the Worker; each run creates a new version and deploys it at once.
For npx wrangler dev on your own machine, put the same names in a .dev.vars file next to wrangler.toml, and keep that file out of git too.
Then point the form's action at the URL npx wrangler deploy prints.
npx wrangler secret put RESEND_API_KEY
npx wrangler deploy
Step 5
Send one message and watch the log
Run npx wrangler tail, then send the form from the live page. Each request streams to your terminal with its log lines.
- "Thanks, your message was sent." and no log line: Resend accepted it. Look for it in the inbox of
OWNER_TO, then on Resend's Emails page if it is not there. - A "Resend refused the send" line: the status and name say why. A 403
validation_errorhere points at thefromaddress: a domain that is not verified, or stillresend.dev. Every Resend error and its fix. - No request at all: the form's
actionpoints somewhere else.
npx wrangler tail
# a refused send logs, for example:
Resend refused the send: 403 validation_error
Step 6
Report each send, after the visitor has their answer
The log tells you about a failure while you watch it. The report tells you when nobody is watching. After the visitor has their answer, the Worker posts one small JSON body to DidMyFormSend with what Resend answered.
ctx.waitUntil keeps the Worker alive after the response: Cloudflare gives that work up to 30 seconds once the response is sent. The report itself gives up after 3 seconds, is sent once, and its result is ignored. If our endpoint is slow or down, the form works as before.
It holds the result, Resend's status or error name, Resend's message id and the time. Where enquiries go is reported masked (o***@example.com) with a hash, so you hear when the address changes without us ever seeing it. Nothing the visitor typed is in it.
- Create a monitor in DidMyFormSend and copy its heartbeat key. It is shown once.
- Run
npx wrangler secret put DIDMYFORMSEND_HEARTBEAT_KEYand paste it. - Send one message through the form yourself. The monitor shows it as its first heartbeat.
From then on, you get an email when Resend refuses a send. For signed tests every week, deploy the complete handler from your dashboard instead: this Worker plus a Turnstile check and the test check. A signed test shows the mail left your handler and reached our mailbox; where your own copy lands is outside what the test can see.
Or tell your agent:Read didmyformsend.com/llms.txt and add a monitor to our contact form handler.
{
"result": "sent",
"provider": "resend",
"occurred_at": 1795465385,
"http_status": 200,
"provider_status": "200",
"event_id": "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794",
"recipients": [{
"masked": "o***@example.com",
"sha256": "c8cd3c64...7124c351"
}]
}
"result": "failed" with, for example, "http_status": 403 and "provider_status": "validation_error"; a bot post reports "skipped".ExampleSources and other guides
Every error code, name and message on this page was read on the pages below on 23 November 2026. Providers change their wording, so check the page when something does not match.
- Contact form not sending email? Check these six things.
Usually the form works and the mail provider says no: a revoked API key, a sending domain that is no longer verified, or a sending limit. Many handlers show "Thanks" anyway, because they never read that answer. Log the provider's status code and error name, fix what it names, then check DNS and the spam folder.
- Resend email not sending? Each error, what it means and the fix.
Resend answers every send with an HTTP status and an error name. On a contact form the usual ones are 401 validation_error (the API key is invalid), 403 validation_error (the from domain is not verified, or resend.dev is sending to someone other than you) and 429 (a quota or the rate limit). Log the status and the name, then fix it where the table below says.
Hear about the next refused send from us.
Add the heartbeat to your handler and get an email when the provider says no. €2 a month per form, and the first charge comes after 14 days.