This guide builds a Cloudflare Worker that receives WhatsApp webhooks for a Dualhook connection: Meta's GET handshake, payload validation, Coexistence fields, deduplication, and a template send. The code was tested with Wrangler 4.169.1 in local development (wrangler dev) on 30 November 2026, not on a deployed Worker.
Prerequisites
- A Cloudflare account and Node.js
- A Dualhook connection in progress or active. Dualhook asks for your webhook URL and verify token before Meta's signup opens, so deploy the Worker first
- A verify token you choose, at least 16 characters, used only for the GET handshake
- A per-connection Dualhook
dh_live_...key and yourPHONE_NUMBER_IDfor outbound runtime sends - Your
WABA_IDfor payload-side validation
No
META_APP_SECRET? In the Embedded Signup flowX-Hub-Signature-256is signed by Dualhook's Meta app and isn't customer-verifiable: validate inbound webhook payload shape instead. These checks do not prove the sender is Meta, so treat the URL as a secret. See Messaging Webhook → Inbound Webhook POST Validation.
Architecture Overview
With Dualhook, Meta sends message-path webhooks directly to your Worker URL. Dualhook stays out of the message content path.
Meta → Worker: messages, statuses, errors; Coexistence echoes, history, contacts
Dualhook → Worker: management events (templates, phone number quality, account)
Worker → api.dualhook.com → Meta: outbound sends with your dh_live_ key
The Worker becomes part of your message-processing boundary. What it logs or stores is kept in your Cloudflare account, even though Dualhook itself does not store message content. See Compliance & Data Retention and Architecture & Security for the privacy split.
Create the Worker Project
Create the project with C3, Cloudflare's project generator:
npm create cloudflare@latest -- whatsapp-webhook
cd whatsapp-webhook
Choose Hello World example, Worker only and JavaScript, and answer No when it asks to deploy.
C3 writes wrangler.jsonc and src/index.js, and installs Wrangler, Cloudflare's CLI, in the project. It also adds a sample test, test/index.spec.js, that expects the Hello World response. Delete it or rewrite it for the code below.
Configure Wrangler
Keep what C3 wrote in wrangler.jsonc and add the durable_objects and exports blocks:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "whatsapp-webhook",
"main": "src/index.js",
"compatibility_date": "2026-11-27",
"observability": {
"enabled": true
},
"upload_source_maps": true,
"durable_objects": {
"bindings": [{ "name": "SEEN_EVENTS", "class_name": "SeenEvents" }]
},
"exports": {
"SeenEvents": { "type": "durable-object", "storage": "sqlite" }
}
}
namebecomes the hostname:whatsapp-webhook.<YOUR_SUBDOMAIN>.workers.dev.compatibility_datepins the Workers runtime version. Cloudflare's convention is the date you start the project. Keep the value C3 wrote: old dates stay supported.observability.enabledturns on Workers Logs.durable_objectsandexportsdeclare the SQLite-backed Durable Object that deduplicates deliveries. Older projects declare the class in amigrationsarray instead. A Worker cannot declare a Durable Object both ways.
Write the Worker
Replace src/index.js with this file. It is the whole receiver.
import { DurableObject } from "cloudflare:workers";
const DUALHOOK_API = "https://api.dualhook.com/v25.0";
const DAY_MS = 24 * 60 * 60 * 1000;
// Fields Meta sends straight to this URL. All four carry metadata.phone_number_id.
const MESSAGE_PATH_FIELDS = new Set([
"messages",
"smb_message_echoes",
"history",
"smb_app_state_sync",
]);
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// The path is a secret. Every other path answers 404.
if (!env.WEBHOOK_PATH || url.pathname !== `/${env.WEBHOOK_PATH}`) {
return new Response("Not found", { status: 404 });
}
if (request.method === "GET") return verifyHandshake(url, env);
if (request.method !== "POST") {
return new Response("Method not allowed", {
status: 405,
headers: { Allow: "GET, POST" },
});
}
// Before the IDs are set, say so. A wrong ID gets 401 below.
const missing = ["WABA_ID", "PHONE_NUMBER_ID"].filter((name) => !env[name]);
if (missing.length > 0) {
console.error("not configured, missing secrets:", missing.join(", "));
return new Response("Not configured", { status: 503 });
}
const payload = await request.json().catch(() => null);
if (!isExpectedPayload(payload, env)) {
return new Response("Unauthorized", { status: 401 });
}
// Answer now. The work continues after the response.
const dualhookEvent = request.headers.get("X-Dualhook-Event");
ctx.waitUntil(
processPayload(payload, dualhookEvent, env).catch((error) =>
console.error("webhook processing failed", error),
),
);
return new Response("OK", { status: 200 });
},
};
function verifyHandshake(url, env) {
const mode = url.searchParams.get("hub.mode");
const token = url.searchParams.get("hub.verify_token");
const challenge = url.searchParams.get("hub.challenge");
if (env.VERIFY_TOKEN && mode === "subscribe" && token === env.VERIFY_TOKEN) {
return new Response(challenge ?? "", {
status: 200,
headers: { "Content-Type": "text/plain" },
});
}
return new Response("Forbidden", { status: 403 });
}
function isExpectedPayload(payload, env) {
if (payload?.object !== "whatsapp_business_account") return false;
if (!Array.isArray(payload.entry) || payload.entry.length === 0) return false;
for (const entry of payload.entry) {
if (entry?.id !== env.WABA_ID) return false;
if (!Array.isArray(entry.changes) || entry.changes.length === 0) return false;
for (const change of entry.changes) {
if (typeof change?.field !== "string") return false;
// Management fields forwarded by Dualhook have no metadata.phone_number_id.
if (
MESSAGE_PATH_FIELDS.has(change.field) &&
change.value?.metadata?.phone_number_id !== env.PHONE_NUMBER_ID
) {
return false;
}
}
}
return true;
}
async function processPayload(payload, dualhookEvent, env) {
if (dualhookEvent === "test_ping") {
console.log("Dualhook Test endpoint ping");
return;
}
for (const entry of payload.entry) {
for (const change of entry.changes) {
const value = change.value ?? {};
switch (change.field) {
case "messages":
for (const message of value.messages ?? []) {
if (await isFirstDelivery(env, `message:${message.id}`)) {
await onCustomerMessage(message, value, env);
}
}
for (const status of value.statuses ?? []) {
if (await isFirstDelivery(env, `status:${status.id}:${status.status}`)) {
await onStatus(status, env);
}
}
for (const error of value.errors ?? []) {
console.error("whatsapp error", error.code, error.title);
}
break;
case "smb_message_echoes":
// Sent by your staff from the WhatsApp Business app. Not a customer message.
for (const echo of value.message_echoes ?? []) {
if (await isFirstDelivery(env, `echo:${echo.id}`)) {
await onStaffReply(echo, env);
}
}
break;
case "history":
case "smb_app_state_sync":
// Coexistence sync, already answered with 200. To keep the history,
// store each chunk before the 200 instead (see the history note below).
console.log("coexistence sync", change.field);
break;
default:
// A management event forwarded by Dualhook, for example
// message_template_status_update or account_update.
console.log("management event", change.field);
}
}
}
}
// If the Durable Object fails, process the event anyway:
// a storage failure should cause a duplicate, not a lost message.
async function isFirstDelivery(env, id) {
try {
return await env.SEEN_EVENTS.getByName(env.PHONE_NUMBER_ID).claim(id);
} catch (error) {
console.error("dedupe failed, processing anyway", id, error);
return true;
}
}
async function onCustomerMessage(message, value, env) {
// Log IDs and types only. Workers Logs stores what you log.
console.log("customer message", message.type, message.id);
// Your logic goes here. For example, with an approved template without variables:
// if (message.from) await sendTemplate(env, message.from, "opening_hours_v1", "en_US");
}
async function onStatus(status, env) {
console.log("status", status.status, status.id);
if (status.status === "failed") {
console.error("send failed", status.id, status.errors?.[0]?.code);
}
}
async function onStaffReply(echo, env) {
console.log("staff reply", echo.type, echo.id);
}
async function sendTemplate(env, to, templateName, languageCode) {
const response = await fetch(`${DUALHOOK_API}/${env.PHONE_NUMBER_ID}/messages`, {
method: "POST",
headers: {
Authorization: `Bearer ${env.DUALHOOK_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
messaging_product: "whatsapp",
to,
type: "template",
template: { name: templateName, language: { code: languageCode } },
}),
});
const result = await response.json().catch(() => null);
if (!response.ok) {
console.error(
"send rejected",
response.status,
result?.error?.code,
response.headers.get("X-Dualhook-Request-Id"),
);
}
return result;
}
// Remembers event IDs, so a delivery that Meta repeats is processed once.
export class SeenEvents extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
ctx.storage.sql.exec(
"CREATE TABLE IF NOT EXISTS seen (id TEXT PRIMARY KEY, at INTEGER NOT NULL)",
);
}
// Returns true the first time an ID is claimed and false for a duplicate.
async claim(id) {
const inserted = this.ctx.storage.sql
.exec(
"INSERT INTO seen (id, at) VALUES (?, ?) ON CONFLICT (id) DO NOTHING RETURNING id",
id,
Date.now(),
)
.toArray();
if ((await this.ctx.storage.getAlarm()) === null) {
await this.ctx.storage.setAlarm(Date.now() + DAY_MS);
}
return inserted.length === 1;
}
// Runs once a day. Meta retries for up to 7 days, so 8 days of IDs is enough.
async alarm() {
this.ctx.storage.sql.exec("DELETE FROM seen WHERE at < ?", Date.now() - 8 * DAY_MS);
await this.ctx.storage.setAlarm(Date.now() + DAY_MS);
}
}
Set the Secrets
The Worker reads five secrets from env. Two exist before Meta's signup, three after it.
| Secret | Value | Known |
|---|---|---|
WEBHOOK_PATH | A random path segment, for example the output of openssl rand -hex 32 | Before signup |
VERIFY_TOKEN | The verify token you choose | Before signup |
WABA_ID | The connection's WhatsApp Business Account ID | After signup |
PHONE_NUMBER_ID | The connection's phone number ID | After signup |
DUALHOOK_API_KEY | The dh_live_... key from Connection → Overview → Outbound API key, shown once | After signup |
Deploy the Worker, then store the first two. If Wrangler is not logged in to your Cloudflare account yet, run npx wrangler login first.
npx wrangler deploy
npx wrangler secret put WEBHOOK_PATH
npx wrangler secret put VERIFY_TOKEN
Each secret put asks for the value, creates a new version of the Worker and deploys it immediately. Do not put these values under vars in wrangler.jsonc: Cloudflare keeps vars for values that are not sensitive.
Your webhook URL is now:
https://whatsapp-webhook.<YOUR_SUBDOMAIN>.workers.dev/<WEBHOOK_PATH>
Meta accepts callback URLs of up to 200 characters. This URL stays below that with a 64-character path.
For local development, put the same five names in a .dev.vars file next to wrangler.jsonc. C3's .gitignore already excludes it.
WEBHOOK_PATH="local-test-path"
VERIFY_TOKEN="local-verify-token-0001"
WABA_ID="102290129340398"
PHONE_NUMBER_ID="123456789012345"
DUALHOOK_API_KEY="dh_live_your_key"
Run npx wrangler dev and send the handshake and a sample event to http://localhost:8787:
curl "http://localhost:8787/local-test-path?hub.mode=subscribe&hub.verify_token=local-verify-token-0001&hub.challenge=1903260781"
curl -i -X POST "http://localhost:8787/local-test-path" \
-H "Content-Type: application/json" \
-d '{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"phone_number_id":"123456789012345"},"messages":[]}}]}]}'
The first prints 1903260781. The second answers 200.
Handle the Verification Handshake
Meta verifies your callback URL with a GET request that carries hub.mode=subscribe, hub.verify_token and hub.challenge. verifyHandshake returns 200 with the challenge as a text/plain body when the mode is subscribe and the token equals VERIFY_TOKEN. Anything else gets 403.
Do not respond with JSON: Meta needs the raw challenge as the body, and Dualhook's setup check reports a JSON-wrapped challenge as a failure.
The token check runs on GET only. Real deliveries are POST requests with no hub.verify_token, so a token check on them drops every message. The VERIFY_TOKEN secret must match the verify token you enter in Dualhook.
Validate the Webhook Payload
isExpectedPayload checks every POST before any work starts:
objectequalswhatsapp_business_account- every
entry[].idequals yourWABA_ID - every
changes[].fieldis read, and the next check depends on it - for message-path fields,
value.metadata.phone_number_idequals yourPHONE_NUMBER_ID
The same URL receives two kinds of fields:
- Message-path fields, sent by Meta directly:
messages(inbound messages andstatuses), plussmb_message_echoes,historyandsmb_app_state_syncon Coexistence numbers. All four carryvalue.metadata.phone_number_id. - Management fields such as
message_template_status_updateoraccount_update, forwarded by Dualhook with anX-Dualhook-Eventheader and noX-Hub-Signature-256. They have nometadata.phone_number_id, so the Worker checksentry[].idonly. See Forwarding Headers.
If the envelope or an ID check fails, the Worker answers 401. A POST that arrives while WABA_ID or PHONE_NUMBER_ID is not set gets 503 instead, with an error log that names the missing secret, so an unset ID and a wrong ID look different in the logs. A field the Worker does not process is not a failure: it answers 200 and logs the field name. Meta retries a rejected message-path delivery for up to 7 days, while a rejected management event is lost, because Dualhook forwards each one once.
processPayload then routes on field. A staff reply sent from the WhatsApp Business app arrives as smb_message_echoes and goes to onStaffReply, never to onCustomerMessage.
Coexistence history sync: right after onboarding, Meta sends the one-time
historysync in chunks, often hundreds of events and up to 3 MB each. Answer every chunk with200, even ones you discard. Once Meta's retries end, Dualhook cannot request a rejected chunk again, and a re-onboard is not guaranteed to bring the history back. If you need the history, write each chunk to your own storage before you answer200, not in the background work: Meta does not send a chunk again once it has a200, and Dualhook has no copy. This Worker answers everyPOSTwith503untilWABA_IDandPHONE_NUMBER_IDare set, so set them as soon as the signup finishes. Cloudflare accepts request bodies up to 100 MB on its Free and Pro plans, so the size fits. CPU time is the limit to watch: see Production Caveats and History Webhook.
Keep the URL unguessable
A Worker on workers.dev or a Custom Domain receives every path of its hostname in the same fetch handler, so the code compares the path with WEBHOOK_PATH and answers 404 for everything else. Treat that path as a secret: do not paste it into shared chat, do not commit it to repos, and rotate it if it leaks (set a new WEBHOOK_PATH, then save the new URL in Dualhook). The payload checks stop stray and casual requests, but anyone who learns your URL and IDs could send a matching payload, so do not let a webhook alone trigger anything irreversible.
Answer Fast, Work After the Response
The Worker returns 200 as soon as the payload passes validation and hands the rest to ctx.waitUntil(). Cloudflare keeps running the promise you pass to it after the response is sent. Work that is neither awaited nor passed to waitUntil() can be cancelled when the response ends.
waitUntil() extends the Worker for up to 30 seconds after the response, shared by all waitUntil() calls of the same request. Promises that have not settled by then are cancelled.
Meta sees the 200 and does not send the event again, so a failure after the response is yours to handle. The code logs it with console.error. For work that takes longer or must be retried, Cloudflare's documentation points to Queues: send each event to a queue and process it in a consumer Worker. A queue message holds up to 128 KB, so queue single events, not a whole history chunk.
Deduplicate Deliveries
Meta can deliver the same event more than once, so the Worker claims each event ID before it processes the event:
- inbound messages on
messages[].id - statuses on the message ID plus the status, because one message gets several statuses
- staff replies on
message_echoes[].id
The IDs live in a Durable Object, not in Workers KV. KV is eventually consistent: a write can take 60 seconds or more to be visible in other locations, and a "key not found" answer is cached too, so two deliveries of one event can both look new. A Durable Object has strongly consistent, transactional storage and runs single-threaded, so the INSERT ... ON CONFLICT DO NOTHING in claim() succeeds for exactly one of them. In our local test, 25 parallel deliveries of one message ran onCustomerMessage once.
If the call to the Durable Object fails, the Worker logs the error and processes the event anyway: a storage failure should cause a duplicate, not a lost message.
getByName(env.PHONE_NUMBER_ID) gives one object per phone number. A daily alarm deletes IDs older than 8 days, one day more than Meta's retry window.
The example does not deduplicate management events. Dualhook forwards each one once. It drops a management event only when it is identical to the last one logged for the same connection and event type (and, for template events, the same template) within 60 seconds, so make a management handler with side effects idempotent.
Send Template Messages via Dualhook
The Worker sends outbound messages through Dualhook's allowlisted runtime. Inbound routing remains direct from Meta.
sendTemplate posts the template to https://api.dualhook.com/v25.0/<PHONE_NUMBER_ID>/messages with Authorization: Bearer <DH_LIVE_KEY>. Call it from one of the handlers, for example in onCustomerMessage:
if (message.from) await sendTemplate(env, message.from, "opening_hours_v1", "en_US");
The example assumes an approved template named opening_hours_v1 that has no variables. The call is guarded because message.from can be missing under Meta's phone-number rules. Without it, send to the user's BSUID with recipient instead of to: see BSUID webhook changes and the Runtime API reference.
Dualhook never retries a send. Every response carries X-Dualhook-Request-Id, which the function logs when a send is rejected.
For variables, media headers, and button parameters, see Sending Template Messages. For error responses, see Runtime API Errors.
Test with Dualhook
- Deploy the Worker and set
WEBHOOK_PATHandVERIFY_TOKEN. - In Dualhook, click Connect WhatsApp, enter the connection name, the Worker URL and the verify token, and click Test endpoint.
- Complete Meta's signup.
- Set
WABA_ID,PHONE_NUMBER_IDandDUALHOOK_API_KEYwithnpx wrangler secret put. - Run
npx wrangler tailto watch the Worker's logs, then run Test endpoint on the connection's Overview page. - Send a real WhatsApp message to your number.
- Confirm that:
- verification succeeds
- the Worker answers
200to the sample event from Test endpoint (a Meta-shaped envelope with your WABA and phone number ID, an emptymessagesarray andX-Dualhook-Event: test_ping) and logsDualhook Test endpoint ping - the real message logs
customer message, and a send producesstatuslines - on Coexistence, a reply sent from the WhatsApp Business app logs
staff reply
Meta itself sends nothing during Test endpoint, so a pass shows that your Worker answers and that Meta lists your URL, not that a real message was delivered.
Production Caveats
- Cloudflare recommends a Custom Domain or route for production Workers and describes
workers.devas intended for personal or hobby projects. Every request to aworkers.devhostname also passes Cloudflare's Browser Integrity Check, which cannot be turned off there. A request it blocks never reaches the Worker and does not appear in its logs. On your own domain you can skip that check for the webhook path. - Workers Free allows 100,000 requests per day and 10 ms of CPU time per request. Cloudflare lists parsing large payloads among the workloads that typically use 10 to 20 ms, and a 3 MB
historychunk is one. A Worker that exceeds its CPU limit returns Cloudflare error 1102 instead of your200, and requests over the daily limit get error 1027. Durable Objects also have daily free limits, and operations over a limit fail until it resets at 00:00 UTC; the Worker then processes events without deduplication. Workers Paid has no daily request limit and a default of 30 seconds of CPU time per request. For a Coexistence number or production traffic, use Workers Paid. See Workers limits. - Workers Logs stores what the Worker logs. Log IDs and types, as the code does, not message text or phone numbers. Each request also gets an invocation log that records the request, including its method and URL, so the secret path is in the logs and anyone who can read the Worker's logs can read the webhook URL. To switch invocation logs off, add
"logs": { "invocation_logs": false }insideobservabilityinwrangler.jsonc. - Every Dualhook connection under the same WABA uses the same webhook URL and verify token. With more than one number on the WABA, this Worker receives all of them and answers
401for the numbers that are notPHONE_NUMBER_ID. Accept a list of phone number IDs, and keep onedh_live_...key per number. - An inbound media webhook can include a
url, but downloading it needs a Meta access token, which a Dualhook connection does not give you. Download by media ID through the Runtime APIGET /v25.0/<MEDIA_ID>/contentroute. - If the Worker runs an AI agent, route on
fieldfirst, so a staff reply insmb_message_echoesis not treated as a customer message. Keep the agent about your own business and give customers a way to reach a person: Meta's terms restrict general-purpose AI assistants, and its policy requires escalation paths when you automate replies. See AI agents on WhatsApp Business and human takeover.
Dualhook Boundary
Dualhook sets Webhook Override at Meta with the URL and verify token you enter, forwards management events to the same URL, and passes the sends you make through the Runtime API on to Meta.
Dualhook is not in the message path. messages, smb_message_echoes, history and smb_app_state_sync go from Meta straight to your Worker, and Dualhook does not receive, store, or replay them. If the Worker misses a delivery, Dualhook has no copy to resend. Each management event is forwarded once, with a 15 second timeout, and a failed forward shows in the connection's webhook log.
Dualhook does not host or deploy the Worker. The Cloudflare account, the Worker's logs, and the Durable Object's storage are yours.