WhatsApp· 6 min read

Receive WhatsApp webhooks on Cloudflare Workers


A Worker receives WhatsApp webhooks in its fetch handler. A GET echoes hub.challenge when the verify token matches. A POST reads the raw body with request.arrayBuffer() and checks X-Hub-Signature-256 with crypto.subtle.verify. It then awaits one Cloudflare Queues message per message or status and returns 200. The same Worker consumes the queue, deduplicates by message ID and does the work. Use a queue rather than ctx.waitUntil(), because waitUntil work is cancelled after 30 seconds and Meta won’t resend after a 200.

Create the Worker and the queue

npm create cloudflare@latest -- whatsapp-webhook
cd whatsapp-webhook
npx wrangler queues create whatsapp-events

Pick a TypeScript Worker when the setup asks. The commands follow Cloudflare’s Workers guide and Queues guide (both accessed 2026-11-04).

Replace the generated wrangler.jsonc with this. The Worker is both producer and consumer of whatsapp-events.

{
  "name": "whatsapp-webhook",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-04",
  "queues": {
    "producers": [{ "queue": "whatsapp-events", "binding": "WHATSAPP_EVENTS" }],
    "consumers": [{ "queue": "whatsapp-events", "max_batch_size": 10, "max_batch_timeout": 5 }]
  }
}

Cloudflare says “you should always set compatibility_date to the current date” when you start a project (compatibility dates, accessed 2026-11-04). Run npx wrangler types after editing the config. It regenerates worker-configuration.d.ts, a file you shouldn’t edit by hand (Workers TypeScript).

The Worker

// src/index.ts
type WaMessage = {
  id: string
  from?: string
  from_user_id?: string
  timestamp: string
  type: string
  text?: { body: string }
}

type WaStatus = {
  id: string
  status: string
  recipient_id?: string
  recipient_user_id?: string
  errors?: unknown[]
}

type WaPayload = {
  object?: string
  entry?: Array<{
    changes?: Array<{
      field?: string
      value?: {
        metadata?: { phone_number_id?: string }
        messages?: WaMessage[]
        statuses?: WaStatus[]
      }
    }>
  }>
}

type WaEvent =
  | { kind: 'message'; phoneNumberId: string; message: WaMessage }
  | { kind: 'status'; phoneNumberId: string; status: WaStatus }

interface WebhookEnv {
  WHATSAPP_APP_SECRET: string
  WHATSAPP_VERIFY_TOKEN: string
  WHATSAPP_EVENTS: Queue<WaEvent>
}

const seen = new Set<string>() // demo dedupe in one isolate; use a unique key in your database

function hexToBytes(hex: string) {
  if (!/^[0-9a-fA-F]{64}$/.test(hex)) return null // SHA-256 is 32 bytes, 64 hex characters
  const bytes = new Uint8Array(32)
  for (let i = 0; i < 32; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
  return bytes
}

async function validSignature(secret: string, body: ArrayBuffer, header: string | null): Promise<boolean> {
  if (header === null || !header.startsWith('sha256=')) return false
  const signature = hexToBytes(header.slice('sha256='.length))
  if (signature === null) return false
  const key = await crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify'],
  )
  return crypto.subtle.verify('HMAC', key, signature, body)
}

function toEvents(payload: WaPayload): WaEvent[] {
  const events: WaEvent[] = []
  if (payload.object !== 'whatsapp_business_account') return events
  for (const entry of payload.entry ?? []) {
    for (const change of entry.changes ?? []) {
      if (change.field !== 'messages' || change.value === undefined) continue
      const phoneNumberId = change.value.metadata?.phone_number_id ?? ''
      for (const message of change.value.messages ?? []) events.push({ kind: 'message', phoneNumberId, message })
      for (const status of change.value.statuses ?? []) events.push({ kind: 'status', phoneNumberId, status })
    }
  }
  return events
}

function dedupeKey(event: WaEvent): string {
  return event.kind === 'message'
    ? `msg:${event.message.id}`
    : `status:${event.status.id}:${event.status.status}`
}

function handle(event: WaEvent): void {
  if (event.kind === 'message') {
    const msg = event.message
    // Meta omits `from` when it cannot include the phone number; fall back to the BSUID
    const sender = msg.from ?? msg.from_user_id
    const text = msg.type === 'text' ? msg.text?.body : `[${msg.type}]`
    console.log(`message ${msg.id} to ${event.phoneNumberId} from ${sender}: ${text}`)
  } else {
    const st = event.status
    console.log(`status ${st.status} for ${st.id} to ${st.recipient_id ?? st.recipient_user_id}`)
    if (st.status === 'failed') console.log(JSON.stringify(st.errors))
  }
}

export default {
  async fetch(request, env): Promise<Response> {
    if (request.method === 'GET') {
      const params = new URL(request.url).searchParams
      const challenge = params.get('hub.challenge')
      const valid =
        env.WHATSAPP_VERIFY_TOKEN !== '' &&
        params.get('hub.mode') === 'subscribe' &&
        params.get('hub.verify_token') === env.WHATSAPP_VERIFY_TOKEN &&
        challenge !== null
      if (!valid) return new Response(null, { status: 403 })
      return new Response(challenge, { status: 200, headers: { 'Content-Type': 'text/plain' } })
    }
    if (request.method !== 'POST') {
      return new Response(null, { status: 405, headers: { Allow: 'GET, POST' } })
    }
    if (!env.WHATSAPP_APP_SECRET) return new Response('WHATSAPP_APP_SECRET is not set', { status: 500 })

    const body = await request.arrayBuffer() // the exact bytes Meta signed
    if (!(await validSignature(env.WHATSAPP_APP_SECRET, body, request.headers.get('x-hub-signature-256')))) {
      return new Response(null, { status: 401 })
    }

    let payload: WaPayload
    try {
      payload = JSON.parse(new TextDecoder().decode(body)) as WaPayload
    } catch {
      return new Response(null, { status: 400 })
    }

    const events = toEvents(payload)
    try {
      // One small message per event: a queue message is capped at 128 KB, a webhook at 3 MB.
      // sendBatch takes up to 100 messages (or 256 KB in total) per call.
      for (let i = 0; i < events.length; i += 100) {
        await env.WHATSAPP_EVENTS.sendBatch(events.slice(i, i + 100).map((event) => ({ body: event })))
      }
    } catch (err) {
      console.error('enqueue failed', err)
      return new Response(null, { status: 500 }) // non-200, so Meta retries
    }
    return new Response(null, { status: 200 })
  },

  async queue(batch): Promise<void> {
    for (const msg of batch.messages) {
      const key = dedupeKey(msg.body)
      if (seen.has(key)) {
        msg.ack()
        continue
      }
      try {
        handle(msg.body)
        seen.add(key)
        msg.ack()
      } catch (err) {
        console.error('handler failed', err)
        msg.retry()
      }
    }
  },
} satisfies ExportedHandler<WebhookEnv, WaEvent>

The WebhookEnv interface types the two secrets and the queue binding. Cloudflare’s get-started sample uses the placeholder env.<MY_QUEUE>, which doesn’t compile, so the code uses the real binding, env.WHATSAPP_EVENTS. One fetch handler serves every method, so anything except GET and POST gets 405.

Verify the signature with Web Crypto

Meta defines the header as an “HMAC-SHA256 hash, calculated using the post body payload and your app secret as the secret key”. You compare it with “everything after sha256=” (Meta create a webhook endpoint, accessed 2026-11-04). The Worker hashes the bytes from arrayBuffer() and decodes them for JSON.parse only after the check passes.

The importKey and verify calls follow Cloudflare’s signing requests example (accessed 2026-11-04). That example warns against computing the HMAC and comparing strings, because “string comparisons bail out on the first mismatch”.

The example decodes a base64 signature with Buffer. Meta sends hex, so hexToBytes does that conversion with no imports. It also rejects anything that isn’t exactly 64 hex characters. Cloudflare doesn’t document what verify does with a signature of the wrong length, so the code never passes it one. A missing, short or malformed header returns 401.

Workers also documents crypto.subtle.timingSafeEqual, a non-standard extension. Its buffers “must be of equal length, otherwise an exception is thrown” (timing attacks example, accessed 2026-11-04). It also “is not constant time with respect to the length of the parameters”. With verify you don’t handle either case.

If you’d rather share Node code, node:crypto works too. With a compatibility date of 2026-08-04 or later, Workers enables nodejs_compat by default (Workers Node.js compatibility, accessed 2026-11-04). The Next.js version shows createHmac with timingSafeEqual. The signature verification guide explains why a re-serialized body fails the hash.

ctx.waitUntil or a queue

Meta publishes no response deadline in seconds. On any status other than 200 it retries “with decreasing frequency until the request succeeds, for up to 7 days” (Meta webhooks overview, accessed 2026-11-04). “These retries can result in duplicate webhook notifications.” Answer 200 fast, then do the work somewhere the 200 can’t lose it.

ctx.waitUntil() Cloudflare Queues
Time after the response Up to 30 s, shared by all calls in the request Consumer runs up to 15 min wall clock per batch
When the work fails Unsettled promises are cancelled after 30 s Message is retried, 3 times by default
After Meta’s 200 Cancelled work is lost Message is on disk once send() resolves

The waitUntil row comes from Cloudflare’s Context page, which itself suggests you “send messages to a Queue and process them in a separate consumer Worker”. This post keeps producer and consumer in one Worker, as Cloudflare’s own Queues get-started sample does. The Queues rows come from the JavaScript APIs, batching and retries and limits pages (all accessed 2026-11-04). Of send(), Cloudflare writes “When the promise resolves, the message is confirmed to be written to disk.” The Worker awaits each sendBatch() call before returning 200, so a failed write becomes a 500 that Meta retries.

waitUntil is fine for logging and other work you can afford to drop. Anything else lost after the 200 stays lost, because “There are no APIs for fetching historical webhook data” (Meta create a webhook endpoint). Webhook queue architecture covers the same split outside Cloudflare.

Why one queue message per event

A queue message is capped at 128 KB (Queues limits). Meta says “Webhook payloads can be up to 3 MB”, so the raw body doesn’t always fit. A POST also carries up to 1000 updates, and “batching cannot be guaranteed”. The Worker sends one queue message per messages[] or statuses[] item, with the phone_number_id it arrived on. It groups them into sendBatch calls of 100, the per-call maximum. A call is also capped at 256 KB in total, so use smaller chunks if your events run large.

If a send fails, the Worker returns 500 and Meta retries the whole POST. Events that were already enqueued then arrive twice, which the consumer’s dedupe absorbs. If you also need the raw body, store larger payloads elsewhere and enqueue a reference.

The consumer: ack, retry, dedupe

Each message in the batch is acknowledged on its own. If the handler throws without per-message ack(), “the entire batch is retried” (batching and retries). retry() puts one message back for a later batch. After the retries run out, the delivery is marked failed, or written to a dead letter queue if you configure one.

Duplicates come from two directions. Meta’s retries resend events, and Queues “provides at least once delivery by default” (delivery guarantees, accessed 2026-11-04). The consumer keys messages on the wamid in id and statuses on id plus status. The Set lives in one isolate, so replace it with a unique key in your database. Webhook retries covers the retry side.

The handler reads the sender as from ?? from_user_id and the status recipient as recipient_id ?? recipient_user_id. Meta says from “Will be omitted if the phone number cannot be included”. For statuses, recipient_id “Will be set to the user’s phone number, if you sent the message to the user’s phone number” (Meta business-scoped user IDs, accessed 2026-11-04). recipient_user_id carries the BSUID.

CPU and time limits

CPU time per HTTP request is 10 ms on Workers Free. On Workers Paid the default is 30 seconds, and limits.cpu_ms in the config raises it to 5 minutes (Workers limits, accessed 2026-11-04). Time spent waiting on network requests doesn’t count as CPU time. The request body limit starts at 100 MB, well above Meta’s 3 MB.

A Worker over its CPU limit fails with Error 1102, “Worker exceeded resource limits”. Cloudflare publishes no figure for one HMAC verify, so watch CPU time in your logs on the Free plan.

Test locally, then deploy

The Worker reads two secrets. WHATSAPP_APP_SECRET is your Meta app secret. WHATSAPP_VERIFY_TOKEN is any string you choose and type into the App Dashboard. For local runs, create .dev.vars next to wrangler.jsonc and keep it out of version control (Workers secrets, accessed 2026-11-04).

WHATSAPP_APP_SECRET="APP_SECRET"
WHATSAPP_VERIFY_TOKEN="VERIFY_TOKEN"

Start npx wrangler dev, which serves the Worker on http://localhost:8787. In a second terminal, export the same two values. Then check the GET and post Meta’s sample text webhook, compacted to one line and signed with your app secret.

curl -i "http://localhost:8787/?hub.mode=subscribe&hub.challenge=12345&hub.verify_token=$WHATSAPP_VERIFY_TOKEN"

cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$WHATSAPP_APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:8787/ \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary @sample.json

The GET returns 12345 and the POST returns 200. Queues work under wrangler dev, where “Your Worker and resources are simulated locally via Miniflare” (Queues local development, accessed 2026-11-04). Within the batch timeout the consumer logs the message. A second identical POST logs nothing. Change one character in sample.json without re-signing and the Worker returns 401.

npx wrangler deploy
npx wrangler secret put WHATSAPP_APP_SECRET
npx wrangler secret put WHATSAPP_VERIFY_TOKEN

Once set, “secret values are not visible within Wrangler or Cloudflare dashboard”. Without the app secret the POST answers 500, and without the verify token the GET answers 403. Set the callback URL to the Worker’s HTTPS URL in the App Dashboard and subscribe to the messages field.

Z-API Omni team