Background Work Without a Server
Webhooks: Trust Nobody, Answer Fast
Other Systems Calling You
A webhook is another service hitting your URL: payment went through, code got pushed, form got filled. The URL is public. Anyone can send "payment succeeded" to it. So the job is always the same four steps:
- Read the raw body.
- Check the signature.
- Queue it.
- Answer.
async function handleWebhook(request, env) {
const body = await request.text(); // the raw bytes, before any parsing
const signature = request.headers.get("X-Signature");
if (!(await verifySignature(body, signature, env.WEBHOOK_SECRET))) {
return new Response("Bad signature", { status: 401 });
}
await env.JOBS.send(JSON.parse(body)); // hand it to the queue
return new Response("Accepted", { status: 202 }); // answer right away
}
The signature proves the sender knows a secret only you two have:
async function verifySignature(body, signature, secret) {
if (!signature || !/^[0-9a-f]{64}$/.test(signature)) return false;
const sent = new Uint8Array(32);
for (let i = 0; i < 32; i++) {
sent[i] = parseInt(signature.slice(i * 2, i * 2 + 2), 16);
}
const enc = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"],
);
return crypto.subtle.verify("HMAC", key, sent, enc.encode(body));
}
Don't memorize it. Know what to look for:
request.text()before any parsing. Parse and rebuild the JSON and the bytes can change, and a real signature fails.crypto.subtle.verify, not===. A plain compare can leak the answer through timing.- Nothing happens before the check. No database write, no log of the body.
- Duplicates are expected. Senders retry. Use the event ID the same way as the last lesson.
Every provider signs a little differently, and some add a timestamp so an old message can't be replayed. Use the provider's own docs or library for theirs.
Slow Down the Noise
Public forms and endpoints get hammered. Workers have a limiter built in. The first block goes inside wrangler.jsonc, the second in your code:
"ratelimits": [
{ "name": "RL_FORM", "namespace_id": "1001", "simple": { "limit": 5, "period": 60 } }
]
const ip = request.headers.get("CF-Connecting-IP") ?? "unknown";
const { success } = await env.RL_FORM.limit({ key: "form:" + ip });
if (!success) return new Response("Slow down", { status: 429 });
The period has to be 10 or 60 seconds. It's approximate and counts separately in each Cloudflare location. Good for stopping a flood. Not good for billing anyone.
namespace_id is shared across your whole account. Two apps with the same number share counters, so give each app its own range. AI loves to copy 1001 straight from the docs.
What has to happen before a webhook handler does anything else with the data?