# FAQ Source: https://solvejet.github.io/whatsapp-cloud-api/faq/ ## How do I send a WhatsApp template message? Use `client.messages.sendTemplate` with the approved template name and language. Template messages are the only messages you can send outside the 24-hour customer service window. ```ts await client.messages.sendTemplate('15551234567', { name: 'hello_world', language: { code: 'en_US' }, }); ``` To create, list, edit, or delete templates, see [Template management](/whatsapp-cloud-api/guides/templates/). ## Does this SDK have any dependencies? No runtime dependencies. It uses the `fetch` and `AbortController` built into Node.js 20+. ## Which Node.js versions are supported? Node.js 20 or newer, as `engines.node` states. CI imports the built ESM and CommonJS entry points on Node 20 and runs the full checks on Node 22 and 24. See [Runtime support](/whatsapp-cloud-api/getting-started/install/#runtime-support). ## Do I need a Meta WhatsApp Business account? Yes. You need a WhatsApp Business Account (WABA), a business phone number ID and an access token. The SDK calls Meta's Graph API on your behalf. ## How do I handle rate limits and errors? Every API failure is a typed subclass of `WhatsAppApiError`, for example `WhatsAppRateLimitError` (with `retryAfterMs`) and `WhatsAppReEngagementError`. See [Error handling](/whatsapp-cloud-api/guides/errors/). --- # Using with AI coding assistants Source: https://solvejet.github.io/whatsapp-cloud-api/getting-started/ai-assistants/ - **Context7:** the library ID is `/solvejet/whatsapp-cloud-api`. Ask your assistant to use Context7 for it, for example "use context7 with `/solvejet/whatsapp-cloud-api`". - **DeepWiki:** [deepwiki.com/SolveJet/whatsapp-cloud-api](https://deepwiki.com/SolveJet/whatsapp-cloud-api). - **llms.txt:** [llms.txt](https://solvejet.github.io/whatsapp-cloud-api/llms.txt) lists the pages, and [llms-full.txt](https://solvejet.github.io/whatsapp-cloud-api/llms-full.txt) has their full text. - **In `node_modules`:** the package ships [`AGENTS-CONSUMER.md`](https://github.com/SolveJet/whatsapp-cloud-api/blob/master/AGENTS-CONSUMER.md) with usage rules for coding agents. Contributors working on this repository should read [`AGENTS.md`](https://github.com/SolveJet/whatsapp-cloud-api/blob/master/AGENTS.md) instead. --- # Choosing a WhatsApp Cloud API library for Node.js Source: https://solvejet.github.io/whatsapp-cloud-api/getting-started/choosing-a-library/ This page compares the npm packages most often used to call Meta's WhatsApp Cloud API from Node.js. Every figure below was read from the npm registry, the npm downloads API and the GitHub API on **2026-11-21**. Packages change, so check the linked pages before you decide. This project is one of the packages compared, so treat the "pick it if" column as a starting point and verify the claims yourself. Last verified against Graph API v26.0 on 2026-11-21. ## At a glance | Package | Latest release (date) | GitHub repository | Runtime dependencies | Downloads, last 30 days | Node.js requirement | | -------------------------------------------------------------------------------------------- | -------------------------- | ----------------- | --------------------------------------- | ----------------------- | ------------------------ | | [`@solvejet/whatsapp-cloud-api`](https://www.npmjs.com/package/@solvejet/whatsapp-cloud-api) | `1.4.0` (2026-11-21) | Not archived | None | 134 | `>=20` | | [`whatsapp-api-js`](https://www.npmjs.com/package/whatsapp-api-js) | `6.3.0` (2026-09-21) | Not archived | None | 27,829 | `>=22.13.0` (warns only) | | [`meta-cloud-api`](https://www.npmjs.com/package/meta-cloud-api) | `3.13.0` (2026-11-12) | Not archived | None | 8,352 | `>=20.12.0` | | [`@kapso/whatsapp-cloud-api`](https://www.npmjs.com/package/@kapso/whatsapp-cloud-api) | `0.4.0` (2026-10-23) | Not archived | `zod` | 391,042 | `>=20.19` | | [`@great-detail/whatsapp`](https://www.npmjs.com/package/@great-detail/whatsapp) | `9.2.0` (2026-09-22) | Not archived | `ky`, `openapi-fetch` | 17,695 | `>=22` | | [`whatsapp`](https://www.npmjs.com/package/whatsapp) (Meta's Node.js SDK) | `0.0.5-Alpha` (2023-04-11) | Archived | `@types/node` | 14,671 | `>=16.19.1` | | [`whatsapp-cloud-api`](https://www.npmjs.com/package/whatsapp-cloud-api) (unscoped) | `0.3.1` (2023-04-11) | Archived | `axios`, `dotenv`, `express` and others | 27,949 | `>=12` | All packages in the table publish TypeScript declarations. Download counts include installs from CI and mirrors, so they say little about how many people use a package. The `@kapso` figure may include traffic from the vendor's own platform; that was not checked. The GitHub repositories for [Meta's `whatsapp` SDK](https://github.com/WhatsApp/WhatsApp-Nodejs-SDK) and [`tawn33y/whatsapp-cloud-api`](https://github.com/tawn33y/whatsapp-cloud-api) are archived, so they are read-only and get no fixes. If you use one of them, see [Migrating from `whatsapp-cloud-api`](/whatsapp-cloud-api/migration/from-whatsapp-cloud-api/) or [Migrating from Meta's `whatsapp` package](/whatsapp-cloud-api/migration/from-meta-whatsapp-sdk/). ## Webhooks and runtimes Webhook support differs more between these packages than the send APIs do. This summary is based on each package's published README on the date above, not on running the code. | Package | Webhook support described in its README | Runtimes named in its README | | ------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | `@solvejet/whatsapp-cloud-api` | GET handshake, `X-Hub-Signature-256` check over the raw body, typed events, dedupe, secret rotation, test helpers | Node.js 20+, Bun, Deno, Cloudflare Workers (all run in CI) | | `whatsapp-api-js` | GET verification handler and `x-hub-signature-256` checking | See its README | | `meta-cloud-api` | Built-in adapters for Express, Next.js, Hono and Fastify, with optional signature verification | Node.js, Bun, Deno, Cloudflare Workers, Vercel Edge | | `@kapso/whatsapp-cloud-api` | `verifySignature` and `normalizeWebhook` utilities | See its README | | `@great-detail/whatsapp` | Webhook support listed | Node.js, Deno, Bun (tested on Deno and Bun LTS versions) | | `whatsapp` (Meta, archived) | Verification token and a listener endpoint configured through environment variables | Node.js | | `whatsapp-cloud-api` (archived) | Built-in Express server that handles the verify token | Node.js | ## When to pick which - **`@solvejet/whatsapp-cloud-api`**: you want no runtime dependencies, strict TypeScript types, one webhook handler that also runs on Cloudflare Workers, Bun and Deno, and test helpers for webhook endpoints. It has little adoption so far (see the download count above), a smaller community than the older packages, and no framework adapters beyond the web-standard `Request` and `Response` pair and raw-body input. - **`whatsapp-api-js`**: you want a library with a longer track record and a larger user base, and you run Node.js 22.13 or newer. - **`meta-cloud-api`**: you want ready-made Express, Next.js, Hono or Fastify webhook adapters and a dedicated documentation site. - **`@kapso/whatsapp-cloud-api`**: you already use, or plan to use, the Kapso platform, or you want its hosted features alongside the SDK. - **`@great-detail/whatsapp`**: you prefer a client built on `openapi-fetch` and `ky`. - **Meta's `whatsapp` and the unscoped `whatsapp-cloud-api`**: not for new projects, because their repositories are archived and their last releases are from 2023. ## When not to use this package - You need a hosted inbox, a no-code flow builder or a managed platform. This is a client library only. - You want built-in Express, Next.js, Hono or Fastify webhook adapters instead of passing the raw body yourself. [`meta-cloud-api`](https://www.npmjs.com/package/meta-cloud-api) ships them. - You want a request client generated from an OpenAPI description. - You need Node.js 18 or older. This package requires Node.js 20 or newer. - You want to drive a regular WhatsApp account rather than use the business API. Baileys and whatsapp-web.js do that through the WhatsApp Web protocol or browser automation, and WhatsApp's [terms of service](https://www.whatsapp.com/legal/terms-of-service) restrict automated access, so read them first. ## How to check this yourself ```sh npm view version time.modified dependencies engines curl -s https://api.npmjs.org/downloads/point/last-month/ curl -s https://api.github.com/repos// ``` The GitHub response has an `archived` field. If any cell above is out of date, [open an issue](https://github.com/SolveJet/whatsapp-cloud-api/issues) and we will correct it. --- # Configuration Source: https://solvejet.github.io/whatsapp-cloud-api/getting-started/configuration/ `WhatsAppClient` takes a single configuration object. Only `accessToken` is required; everything else has a sensible default. | Option | Type | Default | Description | | ------------------- | --------- | ---------------------------- | ------------------------------------------------------------------------------------------- | | `accessToken` | `string` | — (required) | Permanent or temporary access token used to authenticate requests. | | `phoneNumberId` | `string` | — | Default sender phone number ID for messaging and media calls. | | `businessAccountId` | `string` | — | WhatsApp Business Account (WABA) ID. Default id for `client.waba` methods. | | `apiVersion` | `string` | `v26.0` | Graph API version to target. | | `baseUrl` | `string` | `https://graph.facebook.com` | Base URL for the Graph API (override for a proxy or a mock). | | `timeoutMs` | `number` | `30000` | Per-attempt request timeout in milliseconds. | | `maxRetries` | `number` | `2` | Max retries (total attempts = `maxRetries` + `1`). See [Retries](/whatsapp-cloud-api/guides/errors/#retries). | | `retryMessageSends` | `boolean` | `false` | Also retry message sends on `5xx`, network and timeout errors. Can send a message twice. | The defaults are exported as `DEFAULT_API_VERSION`, `DEFAULT_BASE_URL`, `DEFAULT_TIMEOUT_MS`, and `DEFAULT_MAX_RETRIES`. ```ts const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, businessAccountId: process.env.WHATSAPP_WABA_ID, apiVersion: 'v26.0', timeoutMs: 15_000, maxRetries: 3, }); client.getPhoneNumberId(); // the configured default sender, if any client.getApiVersion(); // 'v26.0' client.getBaseUrl(); // 'https://graph.facebook.com/v26.0' ``` **Per-call phone number override.** Every message and media method accepts an optional trailing `phoneNumberId` so a single client can send from multiple numbers. When omitted, the client's configured `phoneNumberId` is used; if neither is set, the call throws `WhatsAppValidationError`. The HTTP core retries with jittered exponential backoff, honoring a `Retry-After` header when present. `GET`, `DELETE` and non-message `POST` requests retry on `429`, `5xx` and network/timeout errors. A `POST` to `{phoneNumberId}/messages` (sends, `sendRaw`, mark-as-read, typing indicators) retries on `429` only, because Meta documents no idempotency for sends and a retry after a lost response could deliver the message twice. Set `retryMessageSends: true` to retry those on `5xx` and network errors too. See [Retries](/whatsapp-cloud-api/guides/errors/#retries). --- # Install Source: https://solvejet.github.io/whatsapp-cloud-api/getting-started/install/ ## Install ```sh pnpm add @solvejet/whatsapp-cloud-api # or: npm install @solvejet/whatsapp-cloud-api # or: yarn add @solvejet/whatsapp-cloud-api ``` ## Runtime support | Runtime | Status | | ------------------ | ------------------------------------------------------------------------------------ | | Node.js 20 | Verified in CI (built package is imported as ESM and CJS, signed request round trip) | | Node.js 22, 24 | Verified in CI (lint, typecheck, tests, build) | | Bun | Verified in CI (`/web` entry runs under Bun) | | Deno | Verified in CI only (`/web` entry runs under Deno) | | Cloudflare Workers | Verified in CI in workerd without `nodejs_compat` (`/web` entry) | | Vercel, Next.js | Use `handleRequest` with `waitUntil` or `after()`; documented, not run in CI | The HTTP client only needs `fetch` and `AbortController`. The main entry's webhook helpers import `node:crypto`. On runtimes without it, import from `@solvejet/whatsapp-cloud-api/web`, which uses Web Crypto only. See [Edge runtimes](/whatsapp-cloud-api/webhooks/handling-events/#edge-runtimes). **Verified against:** Graph API `v26.0`, Meta changelog checked 2026-11-21. Change it with the `apiVersion` option. --- # Overview Source: https://solvejet.github.io/whatsapp-cloud-api/getting-started/overview/ ## Why this library - **Zero runtime dependencies.** It uses the platform `fetch` and `AbortController`, so there is no `axios` or `node-fetch` in your tree. - **Fully typed.** Every method, option, payload and webhook event ships with `.d.ts` declarations, for both ESM and CommonJS. - **Fail-fast validation.** Documented API limits (body and footer lengths, button counts, list rows, reaction emoji and more) are checked before the request is sent. Nothing is silently truncated. - **Typed errors.** Rate limits, re-engagement, authentication, validation and webhook failures are distinct classes. Requests retry with backoff. Message sends retry on `429` only, so a retry cannot deliver a message twice. - **Business-scoped user IDs.** Webhook types expose BSUID and username fields, and senders accept a `{ bsuid }` recipient. See [Usernames and BSUIDs](/whatsapp-cloud-api/guides/usernames-and-bsuids/). - **Released from CI** with npm provenance through OIDC trusted publishing. | Capability | API | | ------------------------- | ------------------------------------------------------------------------------------------------------------- | | Send text & media | `client.messages.sendText`, `sendImage`, `sendVideo`, `sendAudio`, `sendDocument`, `sendSticker` | | Send templates | `client.messages.sendTemplate` | | Interactive messages | `sendInteractiveButtons`, `sendInteractiveList`, `sendInteractiveCtaUrl`, `sendInteractiveFlow` | | Location, contacts, more | `sendLocation`, `sendContacts`, `sendLocationRequest`, `sendProduct`, `sendProductList`, `sendAddressMessage` | | Reactions & typing | `sendReaction`, `markAsRead`, `sendTypingIndicator` | | Any other message body | `client.messages.sendRaw` | | Upload & download media | `client.media.upload`, `getUrl`, `download`, `delete` | | Receive & verify webhooks | `verifyWebhook`, `verifySignature`, `parseWebhook`, `extractMessages`, `WebhookHandler` | | Manage phone numbers | `client.phoneNumbers` (register, verify, business profile, two-step PIN) | | Manage WABAs | `client.waba` (list numbers, subscribe webhooks) | | Manage templates | `client.templates` (list, get, create, edit, delete) | | Manage flows | `client.flows` (create, publish, update JSON, list, get, deprecate, delete, assets, preview) | | Block & unblock users | `client.blocks` (block, unblock, list) | | Calling settings & calls | `client.calls` (getSettings, updateSettings, initiate, preAccept, accept, reject, terminate) | ## How it compares Facts below were checked against the npm registry and GitHub on 2026-11-21. Check each project yourself before choosing; they change. | Option | What it is | Status when checked | Runtime dependencies | | ------------------------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------- | | This package | Cloud API SDK for TypeScript | Actively released | None | | [`whatsapp`](https://www.npmjs.com/package/whatsapp) (Meta's Node.js SDK) | Cloud API SDK | GitHub repository archived; last npm release `0.0.5-Alpha`, 2023-04-11 | `@types/node` | | [`whatsapp-cloud-api`](https://www.npmjs.com/package/whatsapp-cloud-api) | Cloud API wrapper | GitHub repository archived; last npm release `0.3.1`, 2023-04-11 | `axios`, `express`, `dotenv` and others | | [`whatsapp-api-js`](https://www.npmjs.com/package/whatsapp-api-js) | Cloud API library | Last npm release `6.3.0`, 2026-09-21 | None | | [`@great-detail/whatsapp`](https://www.npmjs.com/package/@great-detail/whatsapp) | Cloud API SDK | Last npm release `9.2.0`, 2026-09-22 | `ky`, `openapi-fetch` | | [`@kapso/whatsapp-cloud-api`](https://www.npmjs.com/package/@kapso/whatsapp-cloud-api) | Cloud API SDK | Last npm release `0.4.0`, 2026-10-23 | `zod` | | [Baileys](https://github.com/WhiskeySockets/Baileys), [whatsapp-web.js](https://wwebjs.dev) | Unofficial clients that emulate WhatsApp Web | Not the Cloud API | See each project | Baileys and whatsapp-web.js drive a regular WhatsApp account through the WhatsApp Web protocol or browser automation, not through Meta's business API. WhatsApp's [terms of service](https://www.whatsapp.com/legal/terms-of-service) restrict automated or unauthorized access to its services, so check them before using these projects for a business integration. The Cloud API, through this package or one of the other SDKs above, is the supported route for business messaging. Pick this package when you want no runtime dependencies, strict TypeScript types and a small, testable surface. Pick another if it covers something you need that this one does not, for example a hosted platform or generated OpenAPI clients. For a longer comparison with dates, see [Choosing a WhatsApp Cloud API library for Node.js](https://solvejet.github.io/whatsapp-cloud-api/getting-started/choosing-a-library/). ## When to use this package Use it when: - You call the WhatsApp Cloud API from Node.js 20+, Bun, Deno or Cloudflare Workers and want typed requests and responses. - You want no runtime dependencies and a webhook handler that verifies `X-Hub-Signature-256` against the raw body. - You are replacing the archived `whatsapp-cloud-api` or Meta `whatsapp` package. Do not use it when: - You need a hosted inbox, a no-code builder or a managed platform. This is a client library only. - You want built-in Express, Next.js, Hono or Fastify webhook adapters. Here you pass the raw body (or a `Request`) yourself; see the [examples](https://github.com/SolveJet/whatsapp-cloud-api/blob/master/examples/README.md). - You need to drive a regular WhatsApp account rather than the business API. - You need Node.js 18 or older. --- # Send your first WhatsApp message from Node.js Source: https://solvejet.github.io/whatsapp-cloud-api/getting-started/send-first-message/ You need two values from the [WhatsApp section of the App Dashboard](https://developers.facebook.com/documentation/business-messaging/whatsapp/get-started): an access token and the ID of the business phone number you send from. A message to a number that is not in a [customer service window](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages#customer-service-windows) can only be a template message. See [Send a template message](/whatsapp-cloud-api/guides/send-template-message/). ```ts title="website/snippets/install-check.ts" const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); const res = await client.messages.sendText('15551234567', 'Hello from the SDK'); console.log(res.messages[0]?.id); // the WhatsApp message ID (WAMID) ``` `sendText` posts to `//messages` and returns the API response. The first entry in `messages` holds the WhatsApp message ID, which later appears in status webhooks. See [Configuration](/whatsapp-cloud-api/getting-started/configuration/) for timeouts, retries and the API version, and [Messaging](/whatsapp-cloud-api/guides/messaging/) for the other message types. --- # Block API Source: https://solvejet.github.io/whatsapp-cloud-api/guides/block-api/ Block and unblock the WhatsApp users who have messaged your business with `client.blocks`. The methods are phone-number-scoped: each accepts an optional trailing `phoneNumberId` and falls back to the configured `phoneNumberId`; when neither is set the call throws `WhatsAppValidationError`. You can block or unblock up to **1000 users per call** — an empty or over-limit list throws `WhatsAppValidationError` before any request is sent. ```ts // Block one or more users by WhatsApp phone number. const res = await client.blocks.block(['15551234567']); console.log(res.block_users.added_users?.map((u) => u.wa_id)); // Per-user failures are reported even when the overall call succeeds. for (const failure of res.block_users.failed_users ?? []) { console.error(`could not block ${failure.input}:`, failure.errors[0]?.message); } // Unblock users (issued as a DELETE with a JSON body) and list blocked users. await client.blocks.unblock(['15551234567']); const { data } = await client.blocks.list({ limit: 100 }); console.log(data.map((u) => u.wa_id)); ``` Only users who messaged your business in the **last 24 hours** can be blocked. --- # Calling Source: https://solvejet.github.io/whatsapp-cloud-api/guides/calling/ Manage the [WhatsApp Business Calling](https://developers.facebook.com/docs/whatsapp/cloud-api/calling) settings and call lifecycle with `client.calls`. The methods are phone-number-scoped: each accepts an optional trailing `phoneNumberId` and falls back to the configured `phoneNumberId`; when neither is set the call throws `WhatsAppValidationError`. > **Scope: this SDK handles the REST signaling + settings only.** The WhatsApp > Business Calling API also has a real-time **media plane** — the SDP > offer/answer exchange carried over **WebRTC (and SIP)**. Running that media > stack is **the caller's responsibility**: this SDK does not open, negotiate, > or terminate media sessions. It passes SDP strings through as **opaque > values** (never parsed or validated), so you produce and consume them with > your own WebRTC/SIP implementation. ```ts // Enable calling for the phone number and read the current settings. await client.calls.updateSettings({ calling: { status: 'ENABLED' } }); const settings = await client.calls.getSettings(); console.log(settings.calling?.status); // Call lifecycle. `sdp` is an opaque { sdpType, sdp } pair you produce/consume // with your own WebRTC/SIP stack — the SDK only relays it. const call = await client.calls.initiate({ to: '15551234567', sdp: { sdpType: 'offer', sdp: localOfferSdp }, }); const callId = call.calls[0]?.id; await client.calls.accept(callId, { sdpType: 'answer', sdp: localAnswerSdp }); await client.calls.terminate(callId); ``` Reject an inbound call with `reject(callId)` and send an early media answer with `preAccept(callId, sdp)` before accepting. --- # Error handling Source: https://solvejet.github.io/whatsapp-cloud-api/guides/errors/ Every API failure is a subclass of `WhatsAppApiError`, so `.code` (the Graph error code), `.httpStatus`, and related fields are always available. Branch on the specific classes to react: ```ts import { WhatsAppRateLimitError, WhatsAppReEngagementError, WhatsAppValidationError, } from '@solvejet/whatsapp-cloud-api'; try { await client.messages.sendText('15551234567', 'Hello from the SDK'); } catch (err) { if (err instanceof WhatsAppRateLimitError) { // Rate limited: back off before retrying. When the response carried a // Retry-After header, `retryAfterMs` holds the server-advised delay. const waitMs = err.retryAfterMs ?? 60_000; await new Promise((resolve) => setTimeout(resolve, waitMs)); } else if (err instanceof WhatsAppReEngagementError) { // Equivalent check: `err.code === WhatsAppErrorCode.RE_ENGAGEMENT_MESSAGE`. // Outside the 24-hour customer service window: fall back to a template. await client.messages.sendTemplate('15551234567', { name: 'hello_world', language: { code: 'en_US' }, }); } else if (err instanceof WhatsAppValidationError) { // Client-side limit or shape violation: fix the request before resending. console.error('Invalid request:', err.message); } else { throw err; } } ``` **Error class mapping.** `errorFromResponse` picks the error class from the HTTP status and Graph error `code`: - `429`, `130429`, `131056`, `133016` → `WhatsAppRateLimitError` - `131047` → `WhatsAppReEngagementError` - `401`, `403`, `0`, `190` → `WhatsAppAuthenticationError` - everything else → `WhatsAppApiError` (with `.code` set) All of the above extend `WhatsAppApiError`. Network, abort, and timeout failures raise `WhatsAppRequestError` (with an `isTimeout` flag). `WhatsAppValidationError` is raised locally before a request is sent and is not part of this mapping. For readable comparisons against `err.code`, the exported `WhatsAppErrorCode` constants map names the common Graph error codes (e.g. `WhatsAppErrorCode.ACCESS_TOKEN_EXPIRED`, `WhatsAppErrorCode.SPAM_RATE_LIMIT_HIT`, `WhatsAppErrorCode.TEMPLATE_NOT_EXIST`), so you can branch on a named constant instead of a magic number. Its value type is `WhatsAppErrorCodeValue`. ## Retries The client retries failed requests with jittered exponential backoff (300 ms, doubling per attempt) and waits for `Retry-After` when the response has it. `maxRetries` (default `2`, so three attempts) and `timeoutMs` (default 30 s per attempt) control it. | Request | Retried on | | --------------------------------------------------------------------------------------- | -------------------------------------- | | `GET`, `DELETE`, and `POST` other than messages | `429`, `5xx`, network errors, timeouts | | `POST {phoneNumberId}/messages`: every send, `sendRaw`, mark-as-read, typing indicators | `429` only | | Multipart media upload | never | Never retried, for any request: a call aborted through its `signal`, a `200` response whose body is not valid JSON, and any `4xx` other than `429`. A rate limit code that arrives with another HTTP status, such as a `400`, is not retried either. **Why sends retry on `429` only.** Meta documents no idempotency key or de-duplication for sends. A `5xx`, a timeout or a dropped connection can happen after Meta accepted the message, and a retry would then send it a second time. A `429` is a rejection, so retrying it is safe. A transient `5xx` on a send now reaches your code as `WhatsAppApiError`, and a network failure or timeout as `WhatsAppRequestError`. Check the `messages` and status webhooks before you resend, or de-duplicate on your side. To restore the older behaviour for sends, set `retryMessageSends: true`: ```ts const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, retryMessageSends: true, // 5xx, network errors and timeouts are retried; duplicates are possible }); ``` --- # Flows management Source: https://solvejet.github.io/whatsapp-cloud-api/guides/flows/ Build and manage [WhatsApp Flows](https://developers.facebook.com/docs/whatsapp/flows) with `client.flows`. The methods are WABA-scoped: each accepts an optional trailing `businessAccountId` and falls back to the configured `businessAccountId`; when neither is set the call throws `WhatsAppValidationError`. `create` validates a non-empty `name` and a non-empty `categories` array client-side before sending. ```ts // Create a draft flow, then upload its Flow JSON and publish it. const flow = await client.flows.create({ name: 'lead_capture', categories: ['LEAD_GENERATION'], }); // Upload the Flow JSON as a FLOW_JSON asset (string, Uint8Array, or Blob). await client.flows.updateJson(flow.id, JSON.stringify(flowJson), { name: 'flow.json' }); // Publish once the JSON validates. Only DRAFT flows can be deleted. await client.flows.publish(flow.id); // List flows, read one, and fetch a short-lived preview URL. const { data } = await client.flows.list({ fields: ['id', 'name', 'status'] }); const detail = await client.flows.get(flow.id); const preview = await client.flows.getPreview(flow.id, { invalidate: true }); console.log(preview.preview?.preview_url); ``` Update a flow's metadata with `update` (at least one editable field is required), inspect its uploaded assets with `listAssets`, retire it with `deprecate`, and remove a draft with `delete`. --- # Send WhatsApp interactive reply buttons and list messages in Node.js Source: https://solvejet.github.io/whatsapp-cloud-api/guides/interactive-buttons-and-lists/ Interactive messages let a user answer with a tap. They are service messages, so you can send them while the [customer service window](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages#customer-service-windows) is open. ## Reply buttons Meta's [reply buttons page](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/interactive-reply-buttons-messages) documents these limits: | Field | Limit | | ---------------------- | ---------------------------------------- | | Buttons | up to 3 | | Button label (`title`) | 20 characters, unique across the buttons | | Button `id` | 256 characters | | Body | 1024 characters | | Footer | 60 characters | | Header | optional: text, image, video or document | ```ts title="website/snippets/interactive-buttons.ts" await client.messages.sendInteractiveButtons('15551234567', { header: 'Workshop details', // optional, text up to 60 characters body: 'Your gardening workshop is tomorrow at 9am. Need to reschedule?', footer: 'Lucky Shrub', // optional buttons: [ { id: 'change-button', title: 'Change' }, { id: 'cancel-button', title: 'Cancel' }, ], }); ``` The SDK checks these limits before it sends anything. A fourth button, an empty or duplicate `id`, a title over 20 characters or an over-long body or footer throws `WhatsAppValidationError` with no network call: ```ts title="website/snippets/interactive-buttons.ts" try { await client.messages.sendInteractiveButtons('15551234567', { body: 'Pick one', buttons: [ { id: 'a', title: 'A' }, { id: 'b', title: 'B' }, { id: 'c', title: 'C' }, { id: 'd', title: 'D' }, // a fourth button ], }); } catch (error) { if (error instanceof WhatsAppValidationError) { // Thrown before any request is made. console.error(error.message); } } ``` ## List messages Meta's [list messages page](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/interactive-list-messages) documents these limits: | Field | Limit | | ----------------- | ------------------------------------------------- | | Sections | up to 10 | | Rows | up to 10 in total across all sections, at least 1 | | Button label | 20 characters | | Row `title` | 24 characters | | Row `description` | 72 characters | | Row `id` | 200 characters | | Section `title` | required by Meta, 24 characters | | Header | text only, 60 characters | | Footer | 60 characters | | Body | 4096 characters | ```ts title="website/snippets/interactive-list.ts" await client.messages.sendInteractiveList('15551234567', { header: 'Choose shipping option', body: 'Which shipping option do you prefer?', footer: 'Lucky Shrub', button: 'Shipping options', // label of the button that opens the list sections: [ { title: 'I want it ASAP', rows: [ { id: 'priority_express', title: 'Priority Mail Express', description: 'Next day to 2 days', }, { id: 'priority_mail', title: 'Priority Mail', description: '1 to 3 days' }, ], }, { title: 'I can wait a bit', rows: [{ id: 'media_mail', title: 'Media Mail', description: '2 to 8 days' }], }, ], }); ``` The SDK checks the section count, the total row count, the button label, row titles and row descriptions. Two differences from Meta's table are worth knowing: - The SDK applies a 1024-character limit to the body of every interactive message, including lists, which is stricter than the 4096 that Meta lists for lists. For a longer list body, use `client.messages.sendRaw` (see [Raw sends](/whatsapp-cloud-api/guides/raw-sends/)). - The SDK does not check row `id` length or section titles, and the API remains the authority on both. ## Read the user's choice When a user taps a button or picks a row, Meta sends a `messages` webhook with `interactive.button_reply` or `interactive.list_reply`. It contains the `id` you set, which is the value to branch on. ```ts title="website/snippets/interactive-buttons.ts" // The tap arrives as an inbound webhook message of type "interactive". declare const message: import('@solvejet/whatsapp-cloud-api').IncomingMessage; if (message.type === 'interactive') { const { button_reply: button, list_reply: row } = message.interactive; if (button) console.log('Button tapped:', button.id, button.title); if (row) console.log('List row chosen:', row.id, row.title); } ``` See [Handling events](/whatsapp-cloud-api/webhooks/handling-events/) for flattening a webhook delivery into messages, and [Messaging](/whatsapp-cloud-api/guides/messaging/) for the other message types. --- # Media Source: https://solvejet.github.io/whatsapp-cloud-api/guides/media/ Upload a file once to get a reusable media `id`, then send it with any of the media senders. `upload` accepts a `Blob`/`File`, or `{ file, type, filename }` wrapping `Blob`/`Uint8Array`/`ArrayBuffer` bytes. A content type is required: it comes from a `Blob`'s `type` or the explicit `type`, otherwise `upload` throws `WhatsAppValidationError`. ```ts import { readFile } from 'node:fs/promises'; const bytes = await readFile('./photo.jpg'); const { id } = await client.media.upload({ file: bytes, type: 'image/jpeg', filename: 'photo.jpg', }); // Reuse the id with any media sender. await client.messages.sendImage('15551234567', { id }); ``` Resolve a media id to its metadata, then download the bytes. The `url` returned by `getUrl` is short-lived and must be fetched with the access token — `download` handles that for you (it adds the bearer token and a `User-Agent`) and returns the raw bytes as a `Uint8Array`. ```ts const info = await client.media.getUrl(id); console.log(info.mimeType, info.fileSize); // e.g. "image/jpeg" 20481 // download() calls getUrl() internally, then fetches the short-lived url. const { data, mimeType } = await client.media.download(id); await writeFile('./downloaded.jpg', data); // data is a Uint8Array ``` Delete media you no longer need: ```ts const { success } = await client.media.delete(id); ``` Uploaded media is retained by Meta for **30 days**, after which the id stops resolving. Per-type upload size limits apply: images 5 MB, video 16 MB, audio 16 MB, documents 100 MB, and stickers 100 KB (static) / 500 KB (animated). --- # Messaging Source: https://solvejet.github.io/whatsapp-cloud-api/guides/messaging/ ```ts // Send a pre-approved template. await client.messages.sendTemplate('15551234567', { name: 'hello_world', language: { code: 'en_US' }, }); // Send an interactive message with up to three reply buttons. await client.messages.sendInteractiveButtons('15551234567', { body: 'Did this answer your question?', buttons: [ { id: 'yes', title: 'Yes' }, { id: 'no', title: 'No' }, ], }); ``` ## Replying to a message Pass `replyToMessageId` as the trailing `SendOptions` argument on any sender to thread the outbound message as a reply. The SDK injects a root-level `context: { message_id }` into the request body. ```ts // `incomingMessageId` is the WAMID of the message you are replying to. await client.messages.sendText('15551234567', 'Thanks, got it!', undefined, { replyToMessageId: incomingMessageId, }); ``` ## Interactive call-to-action URL ```ts await client.messages.sendInteractiveCtaUrl('15551234567', { body: 'Browse our latest collection.', displayText: 'Open store', url: 'https://example.com/store', }); ``` ## Address message (India and Singapore) Prompts the user for a delivery address. `country` is required (`IN` or `SG`), and camelCase fields are mapped to the API's snake_case shape for you. The submitted address arrives via webhook as an interactive `nfm_reply` whose `response_json` is a raw JSON string you parse yourself (see [Webhooks](/whatsapp-cloud-api/webhooks/overview/)). ```ts await client.messages.sendAddressMessage('15551234567', { body: 'Where should we deliver your order?', country: 'IN', values: { name: 'Ada Lovelace', phoneNumber: '15551234567', inPinCode: '560001' }, }); ``` ## Typing indicator Mark an inbound message as read and show a typing indicator. It is dismissed once you send a message or after about 25 seconds. ```ts await client.messages.sendTypingIndicator('wamid.HBgL...'); ``` --- # Phone numbers and WABA Source: https://solvejet.github.io/whatsapp-cloud-api/guides/phone-numbers-and-waba/ Manage the business account and its phone numbers directly from the client. `client.phoneNumbers` methods default to the configured `phoneNumberId`, and `client.waba` methods default to the configured `businessAccountId`; both accept an optional trailing id to override the default per call. When neither is set, the call throws `WhatsAppValidationError`. ```ts // List the phone numbers owned by the business account. const { data } = await client.waba.listPhoneNumbers(); console.log(data.map((n) => n.display_phone_number)); // Read the WhatsApp Business Profile for the configured phone number. const profile = await client.phoneNumbers.getBusinessProfile(); console.log(profile?.about); // Register a phone number for the Cloud API with its six-digit two-step PIN. await client.phoneNumbers.register({ pin: '123456' }); ``` The verification flow (`requestVerificationCode`/`verifyCode`), two-step PIN management (`setTwoStepPin` — there is no API to disable it), profile updates (`updateBusinessProfile`), and app webhook subscriptions (`client.waba.subscribeApp`/`unsubscribeApp`/`listSubscribedApps`) are all available. Phone-number deletion is intentionally out of scope. --- # WhatsApp Cloud API rate limits, error 131047 and the 24-hour window Source: https://solvejet.github.io/whatsapp-cloud-api/guides/rate-limits-and-24-hour-window/ Two separate things block a send: rate limits (you are sending too fast) and the customer service window (you are not allowed to send a free-form message right now). ## Rate limits in the Cloud API Meta's [throughput page](https://developers.facebook.com/documentation/business-messaging/whatsapp/throughput) states that each registered business phone number supports 80 messages per second by default, with an automatic upgrade to 1,000 messages per second for eligible numbers. Throughput counts inbound and outbound messages. When you exceed it, the API returns error `130429` until you are back within the limit. The [error codes page](https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes) lists related throttling errors: - `130429`: Cloud API message throughput reached. - `131056`: too many messages from your number to the same recipient in a short period. You can still send to other numbers. - `80007`: the WhatsApp Business Account reached its rate limit. - `131048`: sending is restricted because of quality or spam signals. ## The 24-hour customer service window When a user messages or calls you, a 24-hour [customer service window](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages#customer-service-windows) opens. Each new message or call from the user resets it to 24 hours. While it is open you can send any service message. After it closes you can only send approved template messages. If you send a free-form message with the window closed, the API returns error `131047`, described in the error table as more than 24 hours since the recipient last replied. Meta's remedy is to send a [template message](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/overview) instead. ## How the SDK behaves Reads and non-message requests retry on HTTP `429`, any `5xx`, and network or timeout failures. Message sends (`POST` to `/messages`) retry on `429` only, because a retry after a lost response could deliver the message twice; set `retryMessageSends: true` to retry them on `5xx` and network failures too. Defaults are `maxRetries: 2` (three attempts in total) and a 30-second timeout per attempt. When the response has a `Retry-After` header, the SDK waits that long. Otherwise it waits with exponential backoff and jitter, starting at 300 ms and doubling per attempt. Multipart uploads are never retried. The error classes help you branch: - `WhatsAppRateLimitError` is thrown for HTTP 429 and for the codes `130429`, `131056` and `133016`. Its `retryAfterMs` is set when the server sent `Retry-After`. The SDK retries only on the HTTP status, so a rate limit code returned with a status other than 429 (or 5xx, where retries apply) reaches you without a retry. - `WhatsAppReEngagementError` is thrown for code `131047`. ```ts title="website/snippets/rate-limits-and-window.ts" // Defaults: timeoutMs 30000 per attempt, maxRetries 2 (so up to 3 attempts). const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, maxRetries: 3, }); ``` ```ts title="website/snippets/rate-limits-and-window.ts" try { await client.messages.sendText('15551234567', 'Your order has shipped.'); } catch (error) { if (error instanceof WhatsAppReEngagementError) { // Code 131047: more than 24 hours since the user last replied. // Send an approved template instead. await client.messages.sendTemplate('15551234567', { name: 'order_update', language: { code: 'en_US' }, }); } else if (error instanceof WhatsAppRateLimitError) { // Retries are already exhausted when this reaches you. console.warn(error.code, error.retryAfterMs); } else { throw error; } } ``` `WhatsAppErrorCode` has named constants for the codes the SDK maps: ```ts title="website/snippets/rate-limits-and-window.ts" // Compare against a named constant instead of a number. const reEngagement: number = WhatsAppErrorCode.RE_ENGAGEMENT_MESSAGE; // 131047 const throughput: number = WhatsAppErrorCode.RATE_LIMIT_HIT; // 130429 ``` The SDK does not track the window or throttle for you. Record the time of each inbound message if you need to decide between a free-form message and a template before sending. See [Errors and retries](/whatsapp-cloud-api/guides/errors/) for the full hierarchy and [Send a template message](/whatsapp-cloud-api/guides/send-template-message/) for the fallback. --- # Raw sends Source: https://solvejet.github.io/whatsapp-cloud-api/guides/raw-sends/ `client.messages.sendRaw(body, options?)` posts any body to `{phoneNumberId}/messages` and adds `messaging_product: 'whatsapp'` if you leave it out. Use it for message shapes Meta has released before this SDK has a typed sender. The body is not validated client-side. Retries, timeouts and errors work as for the other senders, and you can declare the response type. ```ts const result = await client.messages.sendRaw<{ messages: { id: string }[] }>({ to: '15551234567', type: 'text', text: { body: 'Hello' }, }); ``` --- # Send a WhatsApp template message from Node.js / TypeScript Source: https://solvejet.github.io/whatsapp-cloud-api/guides/send-template-message/ Template messages are the only message type you can send to a WhatsApp user outside the 24-hour customer service window, and you can also send them inside it. Meta describes the mechanics in [Template fundamentals](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/overview). ## What the Cloud API expects A template message is a `POST` to `//messages` with `type` set to `template`. The `template` object carries the template `name`, a `language.code`, and `components` that fill the template's variables. Meta's examples for [positional and named parameters](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/overview#parameter-formats) show both shapes. Rules from Meta's docs that matter when you send: - The template must have the status `APPROVED`. A template in any other status cannot be sent ([template status](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/overview)). - Template names are not unique across languages, so `language.code` has to match the language the template was created in. - Parameter values go in `components`, in the order the placeholders appear in the template text (positional format). If the number of parameters is wrong, the API answers with error `132000`. A name and language pair that does not exist, or a template that is not approved, gives `132001`. See the [error code reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes). ## With the SDK ```ts title="website/snippets/send-template.ts" const response = await client.messages.sendTemplate('15551234567', { name: 'order_confirmation', // an APPROVED template in your account language: { code: 'en_US' }, // must match the language the template was created in components: [ { type: 'body', parameters: [ { type: 'text', text: 'Jessica' }, { type: 'text', text: 'SKBUP2-4CPIG9' }, ], }, ], }); console.log(response.messages[0]?.id); // the WhatsApp message ID (WAMID) ``` `sendTemplate` posts exactly this payload and returns the API response, so `response.messages[0]?.id` is the message ID you will see again in status webhooks. Components use the same field names as the API (`sub_type`, `index`, `parameters`). Header media and button parameters use the same `components` array: ```ts title="website/snippets/send-template.ts" await client.messages.sendTemplate('15551234567', { name: 'shipping_update', language: { code: 'en_US' }, components: [ { type: 'header', parameters: [{ type: 'image', image: { id: '2762702990552401' } }], }, { type: 'button', sub_type: 'url', index: '0', parameters: [{ type: 'text', text: 'track/12345' }], }, ], }); ``` ## Errors A wrong template name, language or parameter count comes back as a `WhatsAppApiError` carrying the Graph error code in `error.code`. The SDK does not check template parameters against the template before sending. See [Errors and retries](/whatsapp-cloud-api/guides/errors/) for the class hierarchy and [Templates](/whatsapp-cloud-api/guides/templates/) for creating and listing templates with `client.templates`. If you send a free-form message outside the 24-hour window, the API rejects it with code `131047`. See [Rate limits and the 24-hour window](/whatsapp-cloud-api/guides/rate-limits-and-24-hour-window/). --- # Template management Source: https://solvejet.github.io/whatsapp-cloud-api/guides/templates/ Create, list, read, edit, and delete message templates with `client.templates`. Last verified against Graph API v26.0 on 2026-11-21. Every method accepts an optional trailing `businessAccountId` (the id-scoped `get`/`edit` take a required template id instead), falling back to the configured `businessAccountId`; when neither is set the call throws `WhatsAppValidationError`. `create` validates the documented hard limits client-side before sending. ```ts // Create a template. Exactly one BODY component is required. const created = await client.templates.create({ name: 'order_confirmation', language: 'en_US', category: 'UTILITY', components: [ { type: 'BODY', text: 'Hi {{1}}, your order {{2}} is confirmed.', example: { body_text: [['Sam', '12345']] }, }, { type: 'FOOTER', text: 'Reply STOP to opt out.' }, ], }); console.log(created.id, created.status); // e.g. "123..." "PENDING" // List templates on the business account (filters and paging are optional). const { data } = await client.templates.list({ status: 'APPROVED', limit: 20 }); console.log(data.map((t) => t.name)); // Delete every version of a template by name. await client.templates.delete({ name: 'order_confirmation' }); ``` Editing an approved template resets it to `PENDING` for re-review, and a template's `name` and `language` are immutable. --- # Upload and download WhatsApp media with the Cloud API in Node.js Source: https://solvejet.github.io/whatsapp-cloud-api/guides/upload-download-media/ Meta's [media reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media) covers four operations: upload (`POST //media`), get a URL (`GET /`), download (`GET `), and delete (`DELETE /`). ## What the Cloud API does - An upload is multipart form data with `messaging_product=whatsapp`, the `file` and its `type`. It returns a media `id`. - Uploaded files persist for 30 days unless you delete them earlier. A media ID returned by the API expires after 30 days. A media ID received in a webhook expires after 7 days. - A media URL expires after 5 minutes. Query the ID again for a fresh one. - Downloading requires your access token in the `Authorization` header, and the request fails without it. If a download returns `404`, request a new URL and try again. - Meta's size limits per type: audio and video 16 MB, images 5 MB (JPEG, PNG, static WebP), documents 100 MB, static stickers 100 KB, animated stickers 500 KB. The [supported types table](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media#supported-media-types) lists the accepted MIME types. - A mismatched MIME type is a common cause of error `131053` ([error codes](https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes)). ## Upload and send ```ts title="website/snippets/media-upload-download.ts" // Raw bytes carry no content type, so pass one. A Blob or File with a type works as is. const bytes = await readFile('./invoice.pdf'); const { id } = await client.media.upload({ file: bytes, type: 'application/pdf', filename: 'invoice.pdf', }); // Send it by media ID. await client.messages.sendDocument('15551234567', { id, filename: 'invoice.pdf' }); ``` `upload` accepts a `Blob` or `File`, or an object `{ file, type, filename }` where `file` is a `Blob`, `Uint8Array` or `ArrayBuffer`. A content type is required: from the `Blob`'s `type` or the explicit `type`, otherwise it throws `WhatsAppValidationError`. A `phoneNumberId` must be configured on the client or passed per call. Uploads are sent as one attempt and are not retried, because a multipart body is not safely replayable. Retry an upload yourself if it fails with a network error or a 5xx response. ## Download received media ```ts title="website/snippets/media-upload-download.ts" // For a media ID taken from an inbound webhook message: const received = await client.media.download('1037543291543636'); await writeFile('./received-file', received.data); // a Uint8Array console.log(received.mimeType, received.sha256); ``` `download` looks up the URL and then fetches the bytes with your bearer token in one call, so the 5-minute URL lifetime is not an issue. It returns the bytes as a `Uint8Array` with the `mimeType` and, when Meta supplies one, the `sha256`. To fetch a URL you already have, use `client.media.downloadByUrl(url)`. Downloads follow the normal retry policy. ## Look up and delete ```ts title="website/snippets/media-upload-download.ts" const info = await client.media.getUrl(id); // url, mimeType, sha256, fileSize console.log(info.url, info.fileSize); await client.media.delete(id); // { success: true } ``` For sending media by link or by ID in messages, see [Messaging](/whatsapp-cloud-api/guides/messaging/) and [Media](/whatsapp-cloud-api/guides/media/). Meta recommends media IDs over URLs for [high throughput](https://developers.facebook.com/documentation/business-messaging/whatsapp/throughput#media-messages). --- # Usernames and BSUIDs Source: https://solvejet.github.io/whatsapp-cloud-api/guides/usernames-and-bsuids/ Users who enable WhatsApp usernames may not share a phone number. Meta then identifies them by a business-scoped user ID (BSUID, for example `US.13491208655302741918`) and may omit `wa_id`, `from` or `recipient_id`. `wa_id`, `from` and `recipient_id` are typed as `string` for backward compatibility but may be absent in webhooks for username-based users, so do not assume they are always present; check them at runtime. Webhook types expose these optional fields: | Where | Fields | | ------------------ | --------------------------------------------------------------------------------- | | `value.contacts[]` | `user_id`, `parent_user_id`, `profile.username` | | Incoming messages | `from_user_id`, `from_parent_user_id`, `group_id` | | Statuses | `recipient_user_id`, `recipient_parent_user_id` | | `system` messages | `system.user_id`, `parent_user_id`, `previous_user_id`, `previous_parent_user_id` | To send to a BSUID, pass `{ bsuid }` instead of a phone number to any sender. The SDK sends it as `recipient` and omits `to`. ```ts await client.messages.sendText({ bsuid: 'US.13491208655302741918' }, 'Hello'); ``` Details are in [Meta's business-scoped user ID documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids). When a send goes to a BSUID, `contacts[].wa_id` in the response can be absent; read `contacts[].user_id`. --- # Migrating from Meta's `whatsapp` package Source: https://solvejet.github.io/whatsapp-cloud-api/migration/from-meta-whatsapp-sdk/ This guide is for projects that use the npm package [`whatsapp`](https://www.npmjs.com/package/whatsapp) (GitHub: [WhatsApp/WhatsApp-Nodejs-SDK](https://github.com/WhatsApp/WhatsApp-Nodejs-SDK), version `0.0.5-Alpha`) and want to move to `@solvejet/whatsapp-cloud-api`. `@solvejet/whatsapp-cloud-api` is an independent open-source project. It is not affiliated with, endorsed by, or sponsored by Meta or WhatsApp. The "before" code below was checked against the published `whatsapp@0.0.5-Alpha` tarball, which includes its README, TypeScript source and build output. ## Why you might migrate You do not have to. These are the practical reasons: - **Archived upstream.** The GitHub repository is archived (read-only), and 0.0.5-Alpha, published April 2023, is the latest version on npm. It uses `CLOUD_API_VERSION` from your environment, so you pick the Graph version, but new Graph features are not added to the SDK. - **Coverage.** The package's `messages` API covers sending messages and marking them read. It has no method for reactions, media upload or download, or template, WABA, flow, block or calling management. See the [mapping](/whatsapp-cloud-api/migration/from-meta-whatsapp-sdk/#api-mapping) and [what it does that we do not](/whatsapp-cloud-api/migration/from-meta-whatsapp-sdk/#what-the-whatsapp-package-does-that-this-package-does-not). - **Configuration.** It reads settings from environment variables on construction. This package takes an explicit config object, which is easier to use with several phone numbers or tokens in one process. - **Types for webhooks and errors.** Parsed deliveries here are a discriminated union on `type`, and failures are typed error classes. - **Dependencies.** The package has one runtime dependency (`@types/node`). `@solvejet/whatsapp-cloud-api` has none. ## Install ```bash npm uninstall whatsapp npm install @solvejet/whatsapp-cloud-api ``` Requires Node.js 20 or newer. `whatsapp@0.0.5-Alpha` declares `node >= 16.19.1`, so check your runtime first. ## API mapping `wa` is `new WhatsApp(...)` from the `whatsapp` package; `client` is a `WhatsAppClient`. | Task | `whatsapp` 0.0.5-Alpha | `@solvejet/whatsapp-cloud-api` | | -------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | Create the client | `new WhatsApp(senderPhoneNumberId?)`, config from environment variables | `new WhatsAppClient({ accessToken, phoneNumberId, businessAccountId, apiVersion })` | | Send text | `wa.messages.text({ body, preview_url }, recipient)` | `client.messages.sendText(to, body, { previewUrl })` | | Send image | `wa.messages.image({ link } \| { id }, recipient)` | `client.messages.sendImage(to, { link } \| { id })` | | Video, audio, sticker | `wa.messages.video(...)`, `audio(...)`, `sticker(...)` | `client.messages.sendVideo`, `sendAudio`, `sendSticker` | | Document | `wa.messages.document(body, recipient)` | `client.messages.sendDocument(to, { link \| id, caption, filename })` | | Location | `wa.messages.location(body, recipient)` | `client.messages.sendLocation(to, { latitude, longitude, name, address })` | | Contacts | `wa.messages.contacts([contact], recipient)` | `client.messages.sendContacts(to, [contact])` | | Template | `wa.messages.template({ name, language: { policy, code }, components }, recipient)` | `client.messages.sendTemplate(to, { name, language: { code }, components })` | | Interactive | `wa.messages.interactive(interactiveObject, recipient)` | `sendInteractiveButtons`, `sendInteractiveList`, `sendInteractiveCtaUrl`, `sendInteractiveFlow`, `sendProduct`, `sendProductList` | | Reply to a message | third argument: `replyMessageId` | `client.messages.sendRaw({ ..., context: { message_id } })` (see [Reply context](/whatsapp-cloud-api/migration/from-meta-whatsapp-sdk/#reply-context)) | | Reaction | not available (see note) | `client.messages.sendReaction(to, { messageId, emoji })` | | Mark as read | `wa.messages.status({ status: 'read', message_id })` | `client.messages.markAsRead(messageId)` | | Upload media | not available | `client.media.upload(...)` | | Download media | not available | `client.media.download(mediaId)`, `getUrl`, `downloadByUrl` | | Two-step PIN | `wa.twoStepVerification.setPin(pin)` | `client.phoneNumbers.setTwoStepPin(pin)` | | Webhook verification (GET) | `wa.webhooks.start(cb)` handles `hub.mode` and `hub.verify_token` | `verifyWebhookQuery(query, token)` or `WebhookHandler.handleVerification(query)` | | Signature (POST) | `wa.webhooks.start(cb)` checks `x-hub-signature-256` with `M4D_APP_SECRET` | `verifySignature(rawBody, header, appSecret)` or `WebhookHandler.parse(rawBody, header)` | | Parse deliveries | `cb(statusCode, headers, body, response, error)`; `body` is the raw JSON object | `handler.parse(rawBody, header)` returns `{ messages, statuses, raw }` | | Stop the listener | `wa.webhooks.stop(cb)` | not needed: you own the HTTP server | | Update token | `wa.updateAccessToken(token)`, `updateSenderNumberId`, `updateTimeout` | construct another `WhatsAppClient` | Notes: - In the `whatsapp` source, `MessageTypesEnum` has `Reaction = 'sticker'` and `ReactionMessageRequestBody` exists as a type, but `MessagesAPI` has no `reaction` method. You would build the body yourself and pass it to `wa.messages.send`. - Recipients in `whatsapp` are `number`s (`recipient.toString()` is sent). Here `to` is a string, so keep leading country codes as text. - `whatsapp` methods return an object with `statusCode()`, `headers()`, and `responseBodyToJSON()`. They resolve for non-2xx responses too: check `statusCode()`. Here the returned promise resolves to the parsed Graph body and throws on API errors. ## Before and after ### 1. Create a client and send text Before (`whatsapp` 0.0.5-Alpha), with `CLOUD_API_ACCESS_TOKEN`, `CLOUD_API_VERSION`, and `WA_PHONE_NUMBER_ID` set in the environment: ```js import WhatsApp from 'whatsapp'; const wa = new WhatsApp(); // or new WhatsApp(Number(process.env.WA_PHONE_NUMBER_ID)) const response = await wa.messages.text({ body: 'Hello world', preview_url: true }, 15551234567); console.log(response.statusCode(), await response.responseBodyToJSON()); ``` After: ```ts import { WhatsAppClient } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, apiVersion: 'v26.0', // the default }); const res = await client.messages.sendText('15551234567', 'Hello world', { previewUrl: true, }); console.log(res.messages[0]?.id); ``` ### 2. Media and templates Before: ```js await wa.messages.image({ link: 'https://example.com/cat.jpg', caption: 'A cat' }, 15551234567); await wa.messages.template( { name: 'hello_world', language: { policy: 'deterministic', code: 'en_US' } }, 15551234567, ); ``` In TypeScript, `code` is typed as the package's `LanguagesEnum`, which the package entry point does not export. Plain JavaScript can pass the string. After: ```ts import { WhatsAppClient } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); const to = '15551234567'; await client.messages.sendImage(to, { link: 'https://example.com/cat.jpg', caption: 'A cat', }); await client.messages.sendTemplate(to, { name: 'hello_world', language: { code: 'en_US' }, }); ``` ### 3. Interactive messages Before, you build the Graph `interactive` object yourself: ```js await wa.messages.interactive( { type: 'button', body: { text: 'Pick one' }, action: { buttons: [ { type: 'reply', reply: { id: 'yes', title: 'Yes' } }, { type: 'reply', reply: { id: 'no', title: 'No' } }, ], }, }, 15551234567, ); ``` After, there is one method per interactive type, and limits such as the three-button maximum are checked before sending: ```ts import { WhatsAppClient } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); await client.messages.sendInteractiveButtons('15551234567', { body: 'Pick one', buttons: [ { id: 'yes', title: 'Yes' }, { id: 'no', title: 'No' }, ], }); ``` ### 4. Mark as read, react, and handle media Before, only mark-as-read exists: ```js await wa.messages.status({ status: 'read', message_id: 'wamid.XXX' }); ``` After: ```ts import { WhatsAppClient } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); await client.messages.markAsRead('wamid.XXX'); await client.messages.sendReaction('15551234567', { messageId: 'wamid.XXX', emoji: '👍' }); // Upload bytes, then send by id. const { id } = await client.media.upload({ file: new TextEncoder().encode('hello'), filename: 'hello.txt', type: 'text/plain', }); await client.messages.sendDocument('15551234567', { id, filename: 'hello.txt' }); // Download media that a user sent you. const { data, mimeType } = await client.media.download(id); console.log(mimeType, data.byteLength); ``` ### 5. Receive webhooks Before, `wa.webhooks.start(cb)` opens a plain `http` server (it calls `http.createServer`, so TLS has to come from your proxy) on `LISTENER_PORT`, serving `/${WEBHOOK_ENDPOINT}`. The callback receives the status code, headers, parsed body, the response object, and an error. In the success path the callback is passed the response and must end it: ```js wa.webhooks.start((statusCode, headers, body, response, error) => { if (error) { console.error(error); return; } console.log(JSON.stringify(body)); response.end(); // the callback is handed the response; it must be ended }); ``` After, you own the server and pass the raw body to the SDK. This version uses standard `Request` and `Response` types, so it works in Next.js route handlers, Hono and Cloudflare Workers. Express and Fastify versions are in [`examples/`](https://github.com/SolveJet/whatsapp-cloud-api/blob/master/examples/README.md). ```ts import { WebhookHandler, WhatsAppWebhookError } from '@solvejet/whatsapp-cloud-api'; const handler = new WebhookHandler({ verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, appSecret: process.env.WHATSAPP_APP_SECRET!, }); export function verify(request: Request): Response { const query: Record = {}; for (const [key, value] of new URL(request.url).searchParams) query[key] = value; const { statusCode, body } = handler.handleVerification(query); return new Response(body, { status: statusCode }); } export async function receive(request: Request): Promise { const rawBody = await request.text(); // not request.json() try { const { messages, statuses } = handler.parse( rawBody, request.headers.get('x-hub-signature-256') ?? '', ); console.log(messages.length, 'messages', statuses.length, 'statuses'); return new Response('OK'); } catch (error) { if (error instanceof WhatsAppWebhookError) return new Response('Unauthorized', { status: 401 }); throw error; } } ``` ### Reply context `whatsapp` accepts a `replyMessageId` as the last argument of each send method and adds `context: { message_id }` to the body. This package does not have a typed option for it on the senders. Use `sendRaw`, which posts any body and is not validated on the client: ```ts import { WhatsAppClient } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); await client.messages.sendRaw({ to: '15551234567', type: 'text', text: { body: 'Replying to you' }, context: { message_id: 'wamid.XXX' }, }); ``` ## Things that behave differently - **Configuration.** `whatsapp` reads environment variables when you construct it. Here nothing is read from the environment; pass values explicitly. `CLOUD_API_VERSION` is required there. Here the default is `v26.0`. - **Errors.** `whatsapp` throws plain `Error`s for missing configuration, and for HTTP responses it gives you a response object whose `statusCode()` you check. Here you get `WhatsAppApiError` and subclasses (`WhatsAppRateLimitError`, `WhatsAppReEngagementError`, `WhatsAppAuthenticationError`), `WhatsAppRequestError` for network and timeout failures, and `WhatsAppValidationError` for local checks. See [Error handling](/whatsapp-cloud-api/guides/errors/). - **Retries.** The `whatsapp` README lists `MAX_RETRIES_AFTER_WAIT` (default 30). In the 0.0.5-Alpha source that value is read into the config, and we did not find code that uses it to retry. Here, `429`, `5xx`, and network errors are retried (`maxRetries`, default 2) with backoff, and `Retry-After` is honored. Message sends are the exception: they retry on `429` only, because a send that failed after Meta accepted it could be repeated. Set `retryMessageSends: true` to retry sends on `5xx` and network errors too, or `maxRetries: 0` to handle retries yourself. Multipart media uploads are not retried. - **Timeouts.** `whatsapp` defaults to 20,000 ms (`REQUEST_TIMEOUT`). Here it is 30,000 ms per attempt (`timeoutMs`). - **Webhook signature.** Both check the `X-Hub-Signature-256` HMAC-SHA256 of the body with your App Secret. Differences: here the check is a constant-time comparison against the raw bytes you pass in, a missing or malformed header fails, and it runs on every parse. In the `whatsapp` source the POST branch only handles requests that carry the header and compares the hex digests with `==`. - **Raw body is required.** Whatever web framework you use, give `WebhookHandler.parse` the exact bytes Meta sent. If your framework parses JSON first and you re-serialize it, the signature will not match. Pass the raw body as a string, `Buffer`, `Uint8Array` or `ArrayBuffer`. In Express, use `express.raw({ type: 'application/json' })` or `express.json({ verify })` to keep the buffer on that route. In Next.js route handlers use `await request.text()`. - **Unset secrets throw at construction.** `new WebhookHandler({ verifyToken, appSecret })` throws `WhatsAppWebhookError` when either value is present but `undefined`, empty or not a string. An unset environment variable therefore fails at startup instead of silently turning verification off, and the `!` non-null assertion in the examples does not change that at runtime. Omitting the `appSecret` key entirely still means no signature enforcement (`handler.parse(...)` skips the check), so set it in production. `verifySignature(rawBody, header, secret)` returns `false`, and does not throw, for an empty or non-string secret, a bad header or an unsupported body type. - **Only the `messages` field is read.** `extractMessages`, `extractStatuses` and `handler.parse` return data from changes whose `field` is `messages`. Other fields, such as call events from the `calls` field, are not returned as messages or statuses; read them from `parsed.raw`. - **Body size and errors.** String and byte bodies over 3 MiB (Meta's documented maximum) are rejected before parsing. Change this with `maxBodyBytes` on the handler or `parseWebhook` options, or pass `false` to turn the check off. "Not valid JSON" errors do not carry the parser error as `cause`, because its message can include a fragment of the request body. - **No server.** This package does not start an HTTP listener, so there is no port, path or `stop()` to configure. - **Recipient type.** `to` is a string, not a number. It can also be `{ bsuid }` for business-scoped user IDs. For message bodies that this SDK does not wrap yet, `client.messages.sendRaw(body)` posts any body and skips the client-side checks. - **Module formats.** Both ESM and CommonJS work. Node 20 or newer is required. ## What the `whatsapp` package does that this package does not - **A built-in webhook listener.** `wa.webhooks.start(cb)` creates an HTTP server with a configurable port and endpoint, and reports signature failures through the callback. This package has no server; see the examples for Express, Next.js, Hono and Fastify. - **A typed `replyMessageId` argument** on each sender. Use `sendRaw` with `context` here, as shown above. - **Environment-driven setup.** If you rely on the `WA_*`, `M4D_*` and `CLOUD_API_*` variables, you will need to map them to constructor options. - **Node 16.19.1 to 19.** The old package declares `node >= 16.19.1`. This package needs Node 20+. - **A debug logger.** `DEBUG=true` switches on logging in `whatsapp`. This package has no logging switch. - **Meta authorship and license.** `whatsapp` is published by Meta Platforms under its own license text (see its `LICENSE` file). This package is a third-party MIT-licensed project. If your organization requires vendor-authored SDKs, that is a reason to stay. ## Checklist 1. Check Node is 20 or newer. 2. Replace the dependency (`npm uninstall whatsapp`, then install `@solvejet/whatsapp-cloud-api`). 3. Map your environment variables to `new WhatsAppClient({ accessToken, phoneNumberId, businessAccountId, apiVersion })`. 4. Rename each `wa.messages.*` call using the table. Recipients become strings. 5. Replace `wa.messages.status(...)` with `client.messages.markAsRead(...)`. 6. Replace `wa.webhooks.start(cb)` with your own routes. Keep the raw body bytes and pass them to `handler.parse` unchanged. Create a `WebhookHandler` with both the verify token and the App Secret; an empty value for either throws at construction, so check your environment variables. The callback's parsed `body` becomes `parsed.raw`, and messages and statuses come from the `messages` field only. Bodies over 3 MiB are rejected unless you set `maxBodyBytes`. 7. Replace status-code checks on response objects with `try`/`catch` on the error classes. 8. Decide on `maxRetries` and message de-duplication. 9. Replace any `replyMessageId` use with `sendRaw` and `context`. 10. Remove the `whatsapp` environment variables you no longer use. 11. Optional: use reactions, media upload and download, templates, and the other resources. --- # Migrating from `whatsapp-cloud-api` (tawn33y) Source: https://solvejet.github.io/whatsapp-cloud-api/migration/from-whatsapp-cloud-api/ This guide is for projects that use the npm package [`whatsapp-cloud-api`](https://www.npmjs.com/package/whatsapp-cloud-api) (GitHub: [tawn33y/whatsapp-cloud-api](https://github.com/tawn33y/whatsapp-cloud-api)) and want to move to `@solvejet/whatsapp-cloud-api`. `@solvejet/whatsapp-cloud-api` is an independent open-source project. It is not affiliated with Meta, WhatsApp, or the authors of `whatsapp-cloud-api`. The "before" code below was checked against the published `whatsapp-cloud-api@0.3.1` tarball (its README and compiled `dist/`). Its `API.md` is not included in the npm package, so nothing here relies on it. ## Why you might migrate You do not have to. `whatsapp-cloud-api` still works for what it covers. These are the reasons people have to move: - **Archived upstream.** The GitHub repository is archived (read-only). The last release is 0.3.1 (April 2023), and it defaults to Graph API `v14.0` unless you pass `version`. Fixes and new Meta features will not land there. - **Dependencies.** 0.3.1 declares six runtime dependencies (`axios`, `dotenv`, `express`, `pubsub-js`, `type-fest`, `validator`). `@solvejet/whatsapp-cloud-api` has none and uses the built-in `fetch`. - **Coverage.** The old package sends messages and receives them through a built-in Express server. It has no reactions, mark-as-read, media upload or download, template management, or webhook signature check (see [what it does that we do not](/whatsapp-cloud-api/migration/from-whatsapp-cloud-api/#what-whatsapp-cloud-api-does-that-this-package-does-not) for the other direction). - **Types.** Incoming messages in 0.3.1 are typed as `data: FreeFormObject`. Here they are a discriminated union on `type`. - **License.** 0.3.1 is GPL-3.0. This package is MIT. Check what that means for your own project; this is not legal advice. ## Install ```bash npm uninstall whatsapp-cloud-api npm install @solvejet/whatsapp-cloud-api ``` Requires Node.js 20 or newer. `whatsapp-cloud-api@0.3.1` declares `node >= 12`, so check your runtime first. ## API mapping `bot` is the value from `createBot(...)`; `client` is a `WhatsAppClient`. | Task | `whatsapp-cloud-api` 0.3.1 | `@solvejet/whatsapp-cloud-api` | | -------------------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | Create the client | `createBot(phoneNumberId, accessToken, { version })` | `new WhatsAppClient({ accessToken, phoneNumberId, apiVersion })` | | Send text | `bot.sendText(to, text, { preview_url })` | `client.messages.sendText(to, text, { previewUrl })` | | Send image | `bot.sendImage(to, urlOrId, { caption })` | `client.messages.sendImage(to, { link, caption } \| { id, caption })` | | Send video | `bot.sendVideo(to, urlOrId, { caption })` | `client.messages.sendVideo(to, { link } \| { id, caption })` | | Send audio / sticker | `bot.sendAudio(to, urlOrId)`, `bot.sendSticker(to, urlOrId)` | `client.messages.sendAudio(to, { link } \| { id })`, `sendSticker(...)` | | Send document | `bot.sendDocument(to, urlOrId, { caption, filename })` | `client.messages.sendDocument(to, { link, caption, filename })` (`id` instead of `link` for uploaded media) | | Send location | `bot.sendLocation(to, lat, lng, { name, address })` | `client.messages.sendLocation(to, { latitude, longitude, name, address })` | | Send contacts | `bot.sendContacts(to, contacts)` | `client.messages.sendContacts(to, contacts)` | | Send template | `bot.sendTemplate(to, name, languageCode, components)` | `client.messages.sendTemplate(to, { name, language: { code }, components })` | | Reply buttons | `bot.sendReplyButtons(to, body, { id: title }, { footerText })` | `client.messages.sendInteractiveButtons(to, { body, buttons: [{ id, title }], footer })` | | List message | `bot.sendList(to, buttonName, body, { sectionTitle: rows })` | `client.messages.sendInteractiveList(to, { body, button, sections: [{ title, rows }] })` | | Reaction | not available | `client.messages.sendReaction(to, { messageId, emoji })` | | Mark as read | not available | `client.messages.markAsRead(messageId)` | | Upload media | not available | `client.media.upload(blobOrFile)` | | Download media | not available | `client.media.download(mediaId)` | | Verify webhook (GET) | `bot.startExpressServer({ webhookVerifyToken })` handles it | `verifyWebhookQuery(query, token)` or `new WebhookHandler({ verifyToken }).handleVerification(query)` | | Verify signature | not available | `verifySignature(rawBody, header, appSecret)`, or `WebhookHandler({ appSecret })` | | Parse incoming | `bot.on('text' \| 'image' \| ... \| 'message', cb)` | `handler.parse(rawBody, signature)` returns `{ messages, statuses, raw }`; or `parseWebhook` + `extractMessages` | | Reply to a sender | `bot.sendText(msg.from, ...)` | `client.messages.sendText(message.from, ...)` | | Unsubscribe listener | `bot.unsubscribe(token)` | not needed: you loop over parsed messages yourself | | Custom Graph version | `createBot(id, token, { version: 'v17.0' })` | `apiVersion: 'v26.0'` (default is `v26.0`) | Notes on the table: - Every sender returns the Graph response. In 0.3.1 you got `{ messageId, phoneNumber, whatsappId }`. Here you get Meta's body: `res.messages[0]?.id` is the message id and `res.contacts[0]?.wa_id` the WhatsApp id. - In 0.3.1, `sendMessage` is an alias of `sendText`. Use `sendText`. - 0.3.1 decides between a URL and a media id with a URL check (`validator`'s `isURL`). Here you say which one you mean: `{ link }` or `{ id }`. - The old `sendReplyButtons` took an object of `{ [id]: title }`. Here the buttons are an array of `{ id, title }`, and at most three are allowed. ## Before and after ### 1. Create a client and send text Before (`whatsapp-cloud-api` 0.3.1): ```js import { createBot } from 'whatsapp-cloud-api'; const bot = createBot(process.env.FROM_PHONE_NUMBER_ID, process.env.ACCESS_TOKEN); const result = await bot.sendText('15551234567', 'Hello world', { preview_url: true }); console.log(result.messageId); ``` After: ```ts import { WhatsAppClient } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); const res = await client.messages.sendText('15551234567', 'Hello world', { previewUrl: true, }); console.log(res.messages[0]?.id); ``` ### 2. Images, templates and buttons Before: ```js await bot.sendImage(to, 'https://example.com/cat.jpg', { caption: 'A cat' }); await bot.sendTemplate(to, 'hello_world', 'en_US'); await bot.sendReplyButtons(to, 'Pick one', { yes: 'Yes', no: 'No' }, { footerText: 'Thanks' }); ``` After: ```ts import { WhatsAppClient } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); const to = '15551234567'; await client.messages.sendImage(to, { link: 'https://example.com/cat.jpg', caption: 'A cat', }); await client.messages.sendTemplate(to, { name: 'hello_world', language: { code: 'en_US' }, }); await client.messages.sendInteractiveButtons(to, { body: 'Pick one', buttons: [ { id: 'yes', title: 'Yes' }, { id: 'no', title: 'No' }, ], footer: 'Thanks', }); ``` ### 3. Receive messages Before, the library starts an Express server and publishes events in the process (`pubsub-js`): ```js await bot.startExpressServer({ webhookVerifyToken: 'my-verification-token', port: 3000, webhookPath: '/webhook/whatsapp', }); bot.on('text', async (msg) => { await bot.sendText(msg.from, `You said: ${msg.data.text}`); }); ``` After, you keep your own HTTP server and give the SDK the raw body. This version uses the standard `Request`/`Response` types, so it fits Next.js route handlers, Hono, and Cloudflare Workers. Express and Fastify versions are in the repository's [`examples/`](https://github.com/SolveJet/whatsapp-cloud-api/blob/master/examples/README.md). ```ts import { WebhookHandler, WhatsAppClient, WhatsAppWebhookError } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); const handler = new WebhookHandler({ verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, appSecret: process.env.WHATSAPP_APP_SECRET!, }); // GET: Meta's one-time verification handshake. export function verify(request: Request): Response { const query: Record = {}; for (const [key, value] of new URL(request.url).searchParams) query[key] = value; const { statusCode, body } = handler.handleVerification(query); return new Response(body, { status: statusCode }); } // POST: deliveries. Read the raw body, not request.json(). export async function receive(request: Request): Promise { const rawBody = await request.text(); try { const { messages } = handler.parse(rawBody, request.headers.get('x-hub-signature-256') ?? ''); for (const message of messages) { if (message.type === 'text') { await client.messages.sendText(message.from, `You said: ${message.text.body}`); } } return new Response('OK'); } catch (error) { if (error instanceof WhatsAppWebhookError) return new Response('Unauthorized', { status: 401 }); throw error; } } ``` In a real service, return `200` first and do the work afterwards, and deduplicate on the message id. Meta retries deliveries that are not acknowledged quickly. ### 4. Interactive replies Before, button and list taps arrived as `button_reply` and `list_reply` events whose `data` was the reply object: ```js bot.on('button_reply', async (msg) => { console.log(msg.data.id, msg.data.title); }); ``` After, they are `interactive` messages: ```ts import { extractMessages, parseWebhook } from '@solvejet/whatsapp-cloud-api'; export function handleDelivery(rawBody: string): void { const payload = parseWebhook(rawBody); // verify the signature before this for (const message of extractMessages(payload)) { if (message.type === 'interactive') { const reply = message.interactive.button_reply ?? message.interactive.list_reply; if (reply) console.log(reply.id, reply.title); } } } ``` ### 5. Handle errors Before, the helper threw the Graph response body (or a message string), not an `Error`: ```js try { await bot.sendText(to, 'hi'); } catch (err) { console.error(err); // the parsed Graph error body, or a string } ``` After: ```ts import { WhatsAppClient, WhatsAppRateLimitError, WhatsAppReEngagementError, WhatsAppValidationError, } from '@solvejet/whatsapp-cloud-api'; const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!, phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!, }); try { await client.messages.sendText('15551234567', 'hi'); } catch (err) { if (err instanceof WhatsAppRateLimitError) { console.warn('rate limited, retry after ms:', err.retryAfterMs); } else if (err instanceof WhatsAppReEngagementError) { console.warn('outside the 24-hour window: send a template instead'); } else if (err instanceof WhatsAppValidationError) { console.error('invalid request:', err.message); } else { throw err; } } ``` See [Error handling](/whatsapp-cloud-api/guides/errors/) for the full class list. ## Things that behave differently - **No built-in server.** `startExpressServer` and `bot.on(...)` do not exist. You route HTTP yourself and loop over `messages` from the parsed delivery. The old events were in-process only (its README notes they do not work across multiple instances); a parsed delivery has no such limit, because you decide where to queue the work. - **Raw body is required.** Signature verification hashes the exact bytes Meta sent. If a JSON parser runs first and you re-serialize, the bytes change and valid requests fail. Pass the raw body as a string, `Buffer`, `Uint8Array` or `ArrayBuffer`. In Express, use `express.raw({ type: 'application/json' })` or `express.json({ verify })` to keep the buffer on that route. In Next.js route handlers use `await request.text()`. - **Signature verification is new for you.** 0.3.1 only checks the verify token on the GET handshake. It does not read `X-Hub-Signature-256` on POST. Here, `verifySignature` computes the HMAC-SHA256 of the raw body with your App Secret and compares it in constant time. You need the **App Secret** (Meta app dashboard), which is separate from the verify token. - **Unset secrets throw at construction.** `new WebhookHandler({ verifyToken, appSecret })` throws `WhatsAppWebhookError` when either value is present but `undefined`, empty or not a string. An unset environment variable therefore fails at startup instead of silently turning verification off, and the `!` non-null assertion in the examples does not change that at runtime. Omitting the `appSecret` key entirely still means no signature enforcement (`handler.parse(...)` skips the check), so set it in production. `verifySignature(rawBody, header, secret)` returns `false`, and does not throw, for an empty or non-string secret, a bad header or an unsupported body type. - **Only the `messages` field is read.** `extractMessages`, `extractStatuses` and `handler.parse` return data from changes whose `field` is `messages`. Other fields, such as call events from the `calls` field, are not returned as messages or statuses; read them from `parsed.raw`. - **Body size and errors.** String and byte bodies over 3 MiB (Meta's documented maximum) are rejected before parsing. Change this with `maxBodyBytes` on the handler or `parseWebhook` options, or pass `false` to turn the check off. "Not valid JSON" errors do not carry the parser error as `cause`, because its message can include a fragment of the request body. - **Errors are classes.** `WhatsAppApiError` and subclasses carry `.code`, `.httpStatus`, and (for rate limits) `.retryAfterMs`. Network and timeout failures are `WhatsAppRequestError`. Local limit checks throw `WhatsAppValidationError` before any request. - **Retries and timeouts.** The HTTP core retries `429`, `5xx` and network errors (default `maxRetries: 2`, timeout 30 seconds per attempt), with backoff, and honors `Retry-After`. Message sends retry on `429` only, since a send that failed after Meta accepted it could be repeated. Set `retryMessageSends: true` to retry sends on `5xx` and network errors too, or `maxRetries: 0` to handle retries yourself. Multipart media uploads are not retried. 0.3.1 has no retries. - **Validation.** Documented limits (body and footer length, number of buttons, list rows, reaction emoji) are checked before sending. 0.3.1 sends what you give it and lets Meta reject it. - **Configuration.** 0.3.1 loads `.env` on import (`dotenv/config`). This package never reads the environment; pass values to the constructor. - **Recipients.** `to` is a string. It can also be `{ bsuid }` for business-scoped user IDs. Incoming `from` can be missing when a sender uses a username and shares no phone number; check `from_user_id` as well. - **Message shapes without a typed sender.** If you sent a message body that this SDK does not wrap yet, `client.messages.sendRaw(body)` posts any body to the messages endpoint. It is not validated on the client, so the local limit checks do not apply. - **Graph version.** Default is `v26.0` (0.3.1 defaulted to `v14.0`). Set `apiVersion` if you need to pin another one. - **Module formats.** ESM and CommonJS both work. Node 20 or newer is required. ## What `whatsapp-cloud-api` does that this package does not - **A ready-made Express webhook server.** `bot.startExpressServer({...})` gives you a listening server in one call, with `port`, `webhookPath`, `useMiddleware`, and your own `app` as options. This package deliberately imports no web framework; you wire up the route (the examples show Express, Next.js, Hono and Fastify). - **An event emitter.** `bot.on('text' | 'image' | ... | 'message', cb)` with a per-event name and `unsubscribe`. Here you iterate `messages` and `switch` on `type`. If you want an emitter, a few lines of your own `EventEmitter` around `handler.parse` will do. - **Telegram-style API.** The 0.3.1 README says its API was inspired by `node-telegram-bot-api`. This package follows the Graph API's resource shape (`client.messages`, `client.media`, ...). - **Node 12 to 18.** 0.3.1 declares `node >= 12`. This package needs Node 20+. ## Checklist 1. Check Node is 20 or newer. 2. Replace the dependency (`npm uninstall whatsapp-cloud-api`, then install `@solvejet/whatsapp-cloud-api`). 3. Replace `createBot(...)` with `new WhatsAppClient({ accessToken, phoneNumberId })`. 4. Rename each send call using the table. Media and template arguments become objects. 5. Replace `startExpressServer` with your own routes. Keep the raw body bytes on the webhook route and pass them to `handler.parse` unchanged. 6. Get your **App Secret** and the **verify token**, and create a `WebhookHandler` with both. Make sure both environment variables are set, because an empty value throws at construction. Test with a real delivery from Meta. 7. Replace `bot.on(...)` listeners with a loop over `handler.parse(...).messages`. Read statuses from `.statuses`, and anything from other webhook fields from `.raw`. Raise `maxBodyBytes` only if you expect bodies over 3 MiB. 8. Replace `catch (err)` code that expected a plain object or string with `instanceof` checks on the error classes. 9. Decide on `maxRetries` and message de-duplication. 10. Remove `dotenv` imports you only had for the old package, and load your own configuration. 11. Optional: use `markAsRead`, `sendReaction`, and `client.media`. --- # Changelog Source: https://solvejet.github.io/whatsapp-cloud-api/reference/changelog/ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.4.1] - 2026-11-22 ### Added - `retryMessageSends` option on `WhatsAppClientConfig` (default `false`). Set it to `true` to retry message sends on `5xx`, network and timeout failures as well as `429`. Meta documents no idempotency for sends, so a retry can deliver a message twice. - `AGENTS-CONSUMER.md` is included in the npm package. - CI check of the packed package with Are the Types Wrong for the `.`, `./web` and `./testing` entry points. ### Changed - Message sends (`POST {phoneNumberId}/messages`: every sender, `sendRaw`, mark-as-read and typing indicators) now retry on HTTP `429` only. A transient `5xx` on a send now surfaces as an error by default, as do network failures and timeouts. Previously these were retried, which could send the same message twice. Set `retryMessageSends: true` to get the old behaviour. `GET`, `DELETE` and other `POST` requests keep the existing retry policy. - The Cloudflare Workers example now uses `@cloudflare/vitest-plugin`, the renamed successor of the deprecated `@cloudflare/vitest-pool-workers`. ### Fixed - TypeScript projects using `moduleResolution: node10` could not resolve types for `@solvejet/whatsapp-cloud-api/web` and `/testing`. `package.json` now has `typesVersions` for both. Runtime resolution is unchanged. - A request aborted through its `signal` is no longer retried. - A `200` response with a body that is not valid JSON is no longer retried. ## [1.4.0] - 2026-11-21 ### Added - `createWebhookHandler`: an event-driven webhook handler. `handleVerification` answers the handshake, `handleDelivery(rawBody, signature)` and `handleRequest(request)` verify `X-Hub-Signature-256` over the raw bytes, parse the delivery and call handlers registered with `on`. Options: `appSecrets` (one secret or an array for rotation), `verifyToken`, `resolveTenant`, `allowUnsigned`, `maxBodyBytes`, `maxEventAgeSeconds`, `dedupe`, `dedupeKey`, `ackMode`, `waitUntil`, `retryOnHandlerError`, `concurrency` and `onError`. - Typed events and `parseWebhookEvents`: `message`, `status`, `error`, `call`, `flow`, `template`, `account`, `group` and `unknown`, each with a `ctx` (WABA ID, field, time, metadata, matching contact). Fields the SDK does not model arrive as `unknown` with the untouched `value`. - `createMemoryDedupe` and the `WebhookDedupe` interface, with default keys `message:` and `status::`. - `@solvejet/whatsapp-cloud-api/web` entry point with the handler, parsers, dedupe and `verifySignatureAsync`. It uses Web Crypto and imports nothing from `node:*`, so it runs on Cloudflare Workers, Deno, Bun and Node 20+ (all run in CI). Vercel Edge is documented but not run in CI. - `@solvejet/whatsapp-cloud-api/testing` entry point: `signWebhookBody`, `buildWebhookPayload` and `createTestRequest` for testing handlers in-process. - Incoming message types `order`, `unsupported`, `edit` and `revoke`, and `interactive.type` values `product` and `call_permission_reply`. - Helpers `isKnownMessage`, `getUserKey` and `isStale`. - `verifySignature` and `WebhookHandler` accept an array of app secrets, so an old and a new secret can both be valid during rotation. - `allowUnsigned` option for `WebhookHandler` and `createWebhookHandler`. - CI jobs that run the built web entry on Deno, Bun and Cloudflare workerd, and a Node 20 smoke test of every entry point as ESM and CJS. - Examples rewritten on `createWebhookHandler`, an edge-runtime example for Cloudflare Workers, a lower-level example, and documentation pages for the handler, edge runtimes and testing. ### Changed - The `IncomingMessage` union has new members (`order`, `unsupported`, `edit`, `revoke`), and `interactive.type` is wider. Code that checks a `switch` on `message.type` for exhaustiveness with a `never` assignment no longer compiles until it handles the new cases or has a `default` branch. - Accepting a webhook body without an `appSecret` now emits a one-time process warning (`WHATSAPP_WEBHOOK_UNSIGNED`, or `console.warn` where `process.emitWarning` is missing). Behaviour is otherwise unchanged. Set `allowUnsigned: true` to silence it. - `verifySignature` and `WebhookHandler` now accept an array for the app secret (a widening). Version 1.3.x returned `false` or threw for an array. An empty array, an array with an empty string and an array with no matching secret still fail closed. - `package.json` `exports` uses separate `types` conditions for `import` and `require` for every entry point, and adds `./web` and `./testing`. ### Deprecated - Accepting unsigned deliveries without `allowUnsigned: true`. Version 2.0 will require an explicit opt-out; set `appSecret` (or `appSecrets`) now. ## [1.3.2] - 2026-11-21 ### Added - Documentation site at https://solvejet.github.io/whatsapp-cloud-api/, built from the README and `docs/`, with how-to guides for webhook signature verification, the `hub.challenge` handshake, templates, media and rate limits, framework recipes, and a generated API reference. It is deployed to GitHub Pages from `master`. ### Changed - The package `homepage` now points to the documentation site, so the npm page links to it. ## [1.3.1] - 2026-11-20 ### Security - Webhook verification now fails closed on a bad secret. `verifySignature` returns `false` (it never throws) when the app secret is not a non-empty string, so an empty key can no longer validate a signature. `verifyWebhook` and `verifyWebhookQuery` return `403` when the expected verify token is empty or not a string. - The `WebhookHandler` constructor throws `WhatsAppWebhookError` when `appSecret` or `verifyToken` is present but `undefined`, empty or not a string, so an unset environment variable no longer silently disables verification. Omitting the `appSecret` key entirely still means no signature enforcement, as documented. - The JSON `SyntaxError` is no longer attached as `cause` on "not valid JSON" errors, because its message embeds a fragment of the request body. - `WebhookHandler.parse` and `parseWebhook` reject string and byte bodies larger than 3 MiB (Meta's documented maximum) before parsing. Configure it with the new `maxBodyBytes` option (`WebhookHandlerConfig.maxBodyBytes`, `ParseWebhookOptions.maxBodyBytes`); `false` disables the check. ### Fixed - Trailing slashes of `baseUrl` are now trimmed in linear time instead of with a backtracking regular expression. - `extractMessages` and `extractStatuses` no longer throw `RangeError` on arrays of about 125,000 or more elements, skip non-object elements of `messages` and `statuses`, and treat non-array `changes` and non-object `entry` items as empty instead of throwing a `TypeError`. - Byte bodies are decoded with `TextDecoder` (`ignoreBOM`). A plain `Uint8Array` body previously decoded to a comma-separated list of numbers and failed with "not valid JSON". - `verifySignature` returns `false` instead of throwing for an unsupported body type such as `null`, a number or an `ArrayBuffer`, which used to throw a `TypeError` (an `ArrayBuffer` is now supported). - The README and the Express, Next.js, Hono and Fastify examples now parse before responding, send `text/plain` for the verification challenge, return `401` only for a bad signature and `200` (logged) for a signed payload that cannot be parsed, and the Next.js example no longer blocks on awaiting every message in turn. - `InteractiveNfmReply.name` documents `flow` for Flows responses and `address_message` for address messages. ### Changed - **Behavior change:** `extractMessages` and `extractStatuses` (and so `WebhookHandler.parse`) now only read changes whose `field` is `messages`, or whose `field` is not a string. Call status events from the `calls` field (`RINGING`, `ACCEPTED`, `REJECTED`) are no longer returned as `MessageStatus`, and a `messages` array under another field is ignored. Read those payloads from `parsed.raw`. - `WebhookHandler.isValid`, `verifyOrThrow`, `parse`, `verifySignature` and `parseWebhook` accept `Uint8Array` (including `Buffer`) and `ArrayBuffer` raw bodies in addition to strings. New exported types `WebhookRawBody`, `ParseWebhookOptions` and `WebhookMessageReferral`. - Webhook types gain optional fields only: the `played` status, `recipient_type`, `recipient_participant_id`, `recipient_identity_key_hash` and `biz_opaque_callback_data` on statuses, `pricing.type` and `pricing.subtype`, `href` on webhook errors, `time` on entries, `identity_key_hash` on contacts, `forwarded`, `frequently_forwarded` and `referred_product` on message context, a Click to WhatsApp `referral` and `errors` on incoming messages, media `url`, sticker `animated` and `location.url`. `reaction.emoji` stays typed `string` although Meta omits it when a reaction is removed; check it at runtime. ## [1.3.0] - 2026-11-21 ### Added - Business-scoped user ID (BSUID) and username support. Webhook types gain optional `user_id`, `parent_user_id` and `profile.username` on contacts, `from_user_id`, `from_parent_user_id` and `group_id` on incoming messages, `recipient_user_id` and `recipient_parent_user_id` on statuses, and a `system` message type (`SystemIncomingMessage`) for phone number and BSUID changes. - Every message sender accepts a `{ bsuid }` recipient (`BsuidRecipient`, `MessageRecipient`). It is sent as `recipient` with `to` omitted. Phone-number strings work as before. `SendMessageResponse.contacts[]` gains optional `user_id` and `parent_user_id`. - `client.messages.sendRaw(body, options?)` posts an arbitrary body to `{phoneNumberId}/messages`, adds `messaging_product: 'whatsapp'` when absent, and takes an optional `phoneNumberId` (`SendRawOptions`) and a response type parameter. - `examples/` with Express, Next.js App Router, Hono and Fastify webhook servers and a send script. Each answers the verify-token handshake and verifies the signature against the raw body. - README sections for the quickstart, comparison with alternatives, raw-body webhook troubleshooting, BSUIDs, `sendRaw` and runtime support. Template, Flows, Block, Calling and error-handling reference moved to `docs/`. ### Changed - The default Graph API version is now `v26.0` (was `v23.0`). `apiVersion` is still configurable. - `wa_id`, `from` and `recipient_id` stay typed `string` even though Meta may omit them in some username-based events. A future major version may make them optional. ### Removed - The Python and Rust ports line from the README roadmap. ## [1.2.1] - 2026-10-09 ### Changed - Documentation: added the Calling media plane (WebRTC/SIP) to the README roadmap — optional future helpers for the real-time media layer that is currently the caller's responsibility (the Calling REST signaling and settings are implemented in `client.calls`). ## [1.2.0] - 2026-10-09 ### Added - Flows management via `client.flows` (WABA-scoped, defaults to the configured `businessAccountId`): `create`, `list`, `get`, `update`, `updateJson`, `publish`, `deprecate`, `delete`, `listAssets`, and `getPreview`. `create` validates a non-empty `name` and a non-empty `categories` array client-side before sending, and every flow-id method validates a non-empty `flowId`; `update` requires at least one editable field. `updateJson` uploads the Flow JSON as a multipart `FLOW_JSON` asset (a `Blob`, `Uint8Array`, or string wrapped as an `application/json` Blob) with no manual `Content-Type`. `getPreview` requests `fields=preview.invalidate()`. Note: only `DRAFT` flows are deletable. New exported types `Flow`, `FlowList`, `FlowCategory`, `FlowStatus`, `FlowValidationError`, `CreateFlowPayload`, `CreateFlowResponse`, `UpdateFlowPayload`, `UpdateFlowJsonOptions`, `UpdateFlowJsonResponse`, `FlowAsset`, `FlowAssetList`, `FlowPreview`, `FlowJsonInput`, `ListFlowsOptions`, and `GetPreviewOptions`, plus the `FlowsResource` class. - Block API via `client.blocks` (phone-number-scoped, defaults to the configured `phoneNumberId`): `block`, `unblock`, and `list`. `block`/`unblock` accept up to 1000 users per call and reject an empty or over-limit array with `WhatsAppValidationError` before any request. Note: `unblock` is a `DELETE` with a JSON body (sent correctly by the HTTP core), only users who messaged the business in the last 24 hours can be blocked, and per-user failures surface in `block_users.failed_users` even when the overall call succeeds. New exported types `BlockedUser`, `FailedBlockUser`, `BlockUsersResponse`, `BlockedUserList`, and `ListBlockedUsersOptions`, plus the `BlocksResource` class. - Calling settings and lifecycle via `client.calls` (phone-number-scoped, defaults to the configured `phoneNumberId`): `getSettings`, `updateSettings`, `initiate`, `preAccept`, `accept`, `reject`, and `terminate`. `updateSettings` sends `{ calling: {...} }` with camelCase→snake_case mapping and passes `callHours`/`sip` through unchanged; the lifecycle methods POST to `{id}/calls` with the matching `action`. **Scope note: the WhatsApp Business Calling API SDP/WebRTC (and SIP) media plane is OUT OF SCOPE.** This SDK wraps the REST signaling + settings endpoints only — the caller owns the WebRTC/SIP media stack, and SDP offers/answers are passed through as opaque strings (never parsed or validated). New exported types `CallSdp`, `CallingSettings`, `PhoneNumberSettings`, `CallingSettingsUpdate`, `UpdateCallSettingsPayload`, `InitiateCallOptions`, and `CallResponse`, plus the `CallsResource` class. ## [1.1.0] - 2026-10-09 ### Changed - Expanded the npm package `description` and `keywords` to improve discoverability on npm and in search/LLM results — the metadata now names the concrete capabilities (send messages, media, templates, interactive messages; verify webhooks; manage phone numbers, WABAs, and templates) and the runtime (zero dependencies, native fetch, Node.js 20+). No code or API changes. - Documentation (`README`): added a "Why this library" positioning section, a "What you can do" capability table, and an FAQ answering common questions (how to send a message/template, how to verify webhooks, dependencies, supported Node.js versions, official-SDK clarification). Existing usage sections are unchanged. First stable release. The public API is now considered stable and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html): breaking changes will only ship in a new major version. > Version `1.0.0` is skipped: a `1.0.0` was published to npm long before this > SDK's current line and later unpublished, and npm permanently reserves > unpublished version numbers. `1.0.1` is therefore the first stable (`1.x`) > release on npm. ### Stable surface No functional changes from `0.5.0` — this release marks the existing feature set as stable: - **Outbound messaging** — text, media (image/video/audio/document/sticker), location, contacts, templates, interactive (buttons, lists, CTA URL, flow, location request, product, product list, address message), reactions, mark-as-read, and typing indicator; every sender supports reply threading via `replyToMessageId`. - **Inbound webhooks** — GET verification handshake, constant-time `X-Hub-Signature-256` validation, and typed parsing of incoming messages (including `nfm_reply`) and status updates. - **Media lifecycle** — upload, URL resolution, download, and delete. - **Phone number & WABA management** — `client.phoneNumbers` and `client.waba`. - **Message-template management** — `client.templates` (list/get/create/edit/delete). - **Typed errors** — the full error hierarchy plus the `WhatsAppErrorCode` constants map. - **Client-side validation** of documented API limits, raised before the request. ### Changed - Documentation updated to reflect stable `1.x` status (README status note and SECURITY supported-versions table). ## [0.5.0] - 2026-10-09 ### Added - Message-template management via `client.templates`: `list` (`GET {WABA_ID}/message_templates` with optional `fields`, `limit`, `name`, `status`, `category`, `language`, and `after`/`before` paging cursors), `get` (`GET {TEMPLATE_ID}` with optional field selection), `create` (`POST {WABA_ID}/message_templates`), `edit` (`POST {TEMPLATE_ID}` for the editable `category`/`components`/`messageSendTtlSeconds` fields; `name` and `language` are immutable and editing an approved template resets it to `PENDING`), and `delete` (`DELETE {WABA_ID}/message_templates?name=...`, optionally scoped to one version via `hsm_id`). The list/create/delete methods accept an optional trailing `businessAccountId` and fall back to the configured `businessAccountId`; `get`/`edit` are scoped by a required template id. `create` validates the documented hard limits client-side before sending: name is lowercase alphanumeric plus underscores and at most 512 chars, a non-empty language and a valid category are required, components must be non-empty with exactly one BODY and at most one each of HEADER/BODY/FOOTER, BODY text ≤ 1024, HEADER/FOOTER text ≤ 60, and a BUTTONS component holds at most 10 buttons. - New exported types for template management: `TemplateCategory`, `TemplateStatus`, `TemplateParameterFormat`, `MessageTemplateComponent` (the management-side component union, aliased to avoid colliding with the send-side `TemplateComponent`), `TemplateButton`, `TemplateNamedParamExample`, `MessageTemplate`, `CreateTemplatePayload`, `EditTemplatePayload`, `TemplateList`, `CreateTemplateResponse`, plus the `TemplatesResource` class and its `ListTemplatesOptions`/`DeleteTemplateOptions` option types. ## [0.4.0] - 2026-10-08 ### Added - Ergonomic Graph error-code constants via the exported `WhatsAppErrorCode` map and its `WhatsAppErrorCodeValue` type, so callers can compare `err.code` against named constants (e.g. `WhatsAppErrorCode.RE_ENGAGEMENT_MESSAGE`) instead of magic numbers. The map covers the common auth, permission, rate-limit, re-engagement, template, media, and phone-number codes, and is now the single source of truth for the auth/rate-limit/re-engagement code sets used by `errorFromResponse` — error-class mapping behavior is unchanged. - Phone-number management via `client.phoneNumbers`: `get` (phone number details with optional field selection), `requestVerificationCode` and `verifyCode` (the SMS/voice verification flow), `register` and `deregister` (Cloud API registration with a six-digit PIN and optional data-localization region), `setTwoStepPin` (set/change the two-step PIN; there is no API to disable it), and `getBusinessProfile`/`updateBusinessProfile` for the WhatsApp Business Profile. Each method accepts an optional trailing `phoneNumberId` override and falls back to the configured `phoneNumberId`. New exported types `PhoneNumber`, `BusinessProfile`, `BusinessProfileUpdate`, `BusinessProfileVertical`, `RequestVerificationCodeOptions`, and `RegisterOptions`. - WhatsApp Business Account (WABA) management via `client.waba`: `get` (account details), `listPhoneNumbers` (the numbers owned by the account, with paging), `listSubscribedApps`, `subscribeApp`, and `unsubscribeApp`. Each method accepts an optional trailing `businessAccountId` override and falls back to the configured `businessAccountId`. New exported types `Waba`, `SubscribedApp`, `SubscribedAppList`, `PhoneNumberList`, `Paging`, `PagingCursors`, `ListPhoneNumbersOptions`, and the shared `SuccessResponse`. ## [0.3.1] - 2026-10-08 ### Fixed - npm publish failed provenance validation with `E422` because `package.json` URLs used the lowercase owner `solvejet` while the signed provenance (from the GitHub OIDC claim) uses the canonical `SolveJet`; npm requires `repository.url` to match the provenance exactly, case-sensitively. Corrected `repository.url`, `homepage`, `bugs.url`, and the contributor URL to `SolveJet`. This is the first version actually published to npm with provenance; `0.3.0` was tagged and released on GitHub but never reached npm due to this error. ## [0.3.0] - 2026-10-08 > Note: `0.3.0` was tagged and released on GitHub but never published to npm — its publish failed provenance validation (see `0.3.1`). The features below ship in `0.3.1`. ### Added - Typing indicator via `client.messages.sendTypingIndicator(messageId, phoneNumberId?)`: marks an inbound message as read and shows a `typing_indicator` of type `text` to the user (dismissed when you send a message or after about 25 seconds). The existing `markAsRead` signature is unchanged. - Interactive address message via `client.messages.sendAddressMessage` (supported in India and Singapore): a typed `AddressMessagePayload` (body, required `country` of `IN`/`SG`, optional pre-filled `values`, `savedAddresses`, `validationErrors`, plus the shared header/footer) whose camelCase fields map to the snake_case API shape and are serialized into the JSON-encoded `action.parameters` string the API requires. Client-side validation rejects a missing/unsupported country, an `in_pin_code`/`sg_post_code` longer than 6 characters, and over-limit body/footer/header lengths. New exported types `AddressMessagePayload`, `AddressMessageValues`, and `AddressMessageSavedAddress`. - Inbound parsing for address submissions: the interactive webhook union now carries `nfm_reply` (Native Flow Message reply) with `name`, the RAW `response_json` string (left unparsed so a malformed payload never throws — callers `JSON.parse` it), and an optional `body`. New exported type `InteractiveNfmReply`. ### Fixed - Release workflow: npm OIDC trusted publishing now works end to end. The publish was failing with a misleading `ENEEDAUTH`; the actual cause was a case mismatch in the npm trusted-publisher config (`solvejet` vs the canonical GitHub owner `SolveJet`), which made npm's token exchange return `404 package not found`. The workflow now uses Node 24's bundled npm, keeps `registry-url` while stripping the empty `_authToken` line setup-node writes, never sets `NODE_AUTH_TOKEN`, and gained a `workflow_dispatch` trigger for manual re-runs. Trusted-publisher field names are case-sensitive and must match the GitHub OIDC claims exactly. ## [0.2.0] - 2026-10-07 ### Added - Media API via `client.media`: `upload` (multipart upload of a `Blob`/`File` or raw bytes with an explicit content type, returning a reusable media `id`), `getUrl` (typed `MediaInfo` with a short-lived download URL), `download`/`downloadByUrl` (fetch the bytes as a `Uint8Array` with the bearer token and a `User-Agent`), and `delete`. Each method accepts an optional `phoneNumberId` override. - HTTP core support for the media lifecycle: multipart `FormData` request bodies (no manual `Content-Type`, so `fetch` sets the boundary), binary responses (`responseType: 'binary'` returning a `Uint8Array`), absolute `http(s)` download targets used verbatim instead of the base URL, and an optional `User-Agent` header. Non-idempotent multipart uploads run as a single attempt (an unreplayable body is never retried); idempotent `GET`/`DELETE` and downloads still follow the retry policy. Error responses always parse the Graph envelope and throw a typed error — binary callers never receive partial bytes on failure. - A dependency-audit CI job that runs `pnpm audit --audit-level high`, failing the build only on high/critical advisories. ### Changed - Upgraded `vitest` and `@vitest/coverage-v8` to v5, resolving the transitive `tinypool` critical advisories (GHSA-85c8-ppgw-ccpr, GHSA-5gmw-xhrv-c9v3); vitest 5 no longer depends on the affected `tinypool`. - CI dev-tooling checks (lint, typecheck, test, build) now run on Node 22 and 24, since vitest 5 requires Node >= 22.12. The published package continues to support Node 20 (`engines.node` stays `>=20`), verified by a dedicated job that imports the built ESM and CJS artifacts on Node 20. ## [0.1.0] - 2026-10-07 ### Added - Project foundation: TypeScript 6 toolchain, tsup dual ESM/CJS build, vitest, ESLint 10 flat config, and Prettier. - Minimal `WhatsAppClient` skeleton pinned to Graph API `v23.0`. - HTTP core built on native `fetch`/`AbortController` with per-attempt timeout, retries on 429/5xx/network errors using jittered exponential backoff (honoring `Retry-After`), and a typed error hierarchy (`WhatsAppApiError`, `WhatsAppAuthenticationError`, `WhatsAppRequestError`, `WhatsAppValidationError`). - Typed outbound Messages API via `client.messages`: `sendText`, `sendImage`, `sendVideo`, `sendAudio`, `sendDocument`, `sendSticker`, `sendLocation`, `sendContacts`, `sendTemplate`, `sendInteractiveButtons`, `sendInteractiveList`, `sendReaction`, and `markAsRead`. - Reply/context support: every sender accepts a trailing `SendOptions` with `replyToMessageId`, injecting a root-level `context: { message_id }` into the request body. - Five new interactive senders: `sendInteractiveCtaUrl`, `sendInteractiveFlow`, `sendLocationRequest`, `sendProduct`, and `sendProductList`. - Rich interactive headers for buttons and lists: a plain string, a structured text header, or an image/video/document media header (`InteractiveHeader`, `InteractiveMediaHeader`). - Full contacts object: `ContactName` middle name/suffix/prefix plus `ContactAddress`, `ContactOrg`, `ContactUrl`, and `Contact` `addresses`/`org`/`urls`/`birthday`. - Client-side validation of documented Messages API limits (text/interactive body, footer, header, button counts and ids, list sections/rows, reaction emoji, flow CTA, product-list items), raising `WhatsAppValidationError` with a field + limit message; nothing is truncated. - Typed errors `WhatsAppRateLimitError` (exposing `retryAfterMs` when a `Retry-After` header is present) and `WhatsAppReEngagementError`, both subclasses of `WhatsAppApiError`; `errorFromResponse` maps `429`/`130429`/`131056`/`133016` to rate-limit and `131047` to re-engagement. - Framework-agnostic webhooks module: GET verification handshake (`verifyWebhook`, `verifyWebhookQuery`) echoing the raw `hub.challenge` with a constant-time token check; constant-time `X-Hub-Signature-256` validation over the raw request body (`verifySignature`); typed inbound parsing (`parseWebhook`, `extractMessages`, `extractStatuses`, `isMessageEvent`/`isStatusEvent`) with a discriminated `IncomingMessage` union (text, image, video, audio, document, sticker, location, contacts, interactive, button, reaction, plus an unknown fallback) and `MessageStatus`; a `WebhookHandler` that binds the verify token and App Secret; and a new `WhatsAppWebhookError`. - CI (Node 20 and 22) and release-on-tag workflows. - OSS docs: README, LICENSE, CONTRIBUTING, CODE_OF_CONDUCT, SECURITY, CODEOWNERS. ### Changed - Interactive button and list headers now accept the structured `InteractiveHeader` type in addition to a plain string (backward compatible). - Removed stale "omitted" notes from the contact types now that the full contacts object is modeled. [Unreleased]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.4.0...HEAD [1.4.0]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.3.2...v1.4.0 [1.3.2]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.3.1...v1.3.2 [1.3.1]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.3.0...v1.3.1 [1.3.0]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.2.1...v1.3.0 [1.2.1]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.2.0...v1.2.1 [1.2.0]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.1.0...v1.2.0 [1.1.0]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v1.0.1...v1.1.0 [1.0.1]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v0.5.0...v1.0.1 [0.5.0]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v0.3.1...v0.4.0 [0.3.1]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v0.3.0...v0.3.1 [0.3.0]: https://github.com/SolveJet/whatsapp-cloud-api/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/solvejet/whatsapp-cloud-api/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/solvejet/whatsapp-cloud-api/releases/tag/v0.1.0 --- # WhatsApp Cloud API webhooks on Cloudflare Workers, Bun, Deno and Vercel Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/edge-runtimes/ The `@solvejet/whatsapp-cloud-api/web` entry point has the same `createWebhookHandler`, parsers and dedupe as the main entry, but it imports nothing from `node:*` and verifies signatures with Web Crypto. Use it wherever `node:crypto` is not available or you want one code path for every runtime. ```ts title="website/snippets/edge-runtimes.ts" interface Env { WHATSAPP_APP_SECRET: string; WHATSAPP_VERIFY_TOKEN: string; } export default { async fetch( request: Request, env: Env, ctx: { waitUntil(promise: Promise): void }, ): Promise { const webhook = createWebhookHandler({ appSecrets: env.WHATSAPP_APP_SECRET, verifyToken: env.WHATSAPP_VERIFY_TOKEN, ackMode: 'before', // answer first, run handlers after the response }); webhook.on('message', ({ message }) => { console.log('message', message.id, message.type); }); return webhook.handleRequest(request, { waitUntil: (promise) => ctx.waitUntil(promise) }); }, }; ``` You can also call the verifier directly: ```ts title="website/snippets/edge-runtimes.ts" // Web Crypto only, no node:crypto. Resolves to a boolean and never throws. const valid = await verifySignatureAsync(body, header, process.env.WHATSAPP_APP_SECRET!); ``` ## What is tested | Runtime | Status | | ------------------ | ----------------------------------------------------------- | | Node.js 20, 22, 24 | Verified in CI | | Bun | Verified in CI (the built web entry runs under Bun) | | Deno | Verified in CI only (the built web entry runs under Deno) | | Cloudflare Workers | Verified in CI in workerd, without the `nodejs_compat` flag | | Vercel, Next.js | Documented, not run in CI | ## Keeping background work alive With `ackMode: 'before'` the handler answers first and runs your handlers afterwards. Serverless platforms may stop the invocation after the response unless you tell them to wait. - **Cloudflare Workers:** pass `ctx.waitUntil` as in the example above. - **Vercel:** pass `waitUntil` from `@vercel/functions` as the `waitUntil` option, or call `after()` from `next/server`. - **Node.js, Bun and Deno servers that keep running:** nothing is needed. Without `waitUntil`, the background work runs as a detached promise and its failures go to `onError`. If you do not need to answer early, leave `ackMode` at its default. The handlers then finish before the response is sent. --- # WhatsApp Cloud API webhook in Express with signature verification Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/express/ In Express, the signature must be checked against the bytes Meta sent. Mount `express.raw({ type: 'application/json' })` on the POST route so `req.body` is a `Buffer`, and do not put `express.json()` in front of it. Pass that buffer to `handleDelivery` and answer with the status it returns. The GET route reads `req.query` for the verification request. ```ts title="examples/express/server.ts" import express from 'express'; import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api'; import { echoText, requireEnv } from '../shared/reply.js'; const webhook = createWebhookHandler({ appSecrets: requireEnv('WHATSAPP_APP_SECRET'), verifyToken: requireEnv('WHATSAPP_VERIFY_TOKEN'), }); // One handler per event. A throw in one handler is passed to onError and does not // stop the other events of the delivery. webhook.on('message', ({ message }) => echoText(message)); webhook.on('status', ({ status }) => { console.log(`message ${status.id} -> ${status.status}`); }); const app = express(); // Verify-token handshake: Meta calls this once when you save the webhook URL. app.get('/webhook', (req, res) => { const query: Record = {}; for (const [key, value] of Object.entries(req.query)) { if (typeof value === 'string') query[key] = value; } const { statusCode, body } = webhook.handleVerification(query); res.status(statusCode).type('text/plain').send(body); }); // The signature is computed over the exact bytes Meta sent. express.raw keeps // them as a Buffer; do NOT put express.json() in front of this route. app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => { const rawBody = req.body as Buffer; const result = await webhook.handleDelivery(rawBody, req.get('x-hub-signature-256')); res.sendStatus(result.httpStatus); }); app.listen(3000, () => console.log('Listening on http://localhost:3000/webhook')); ``` The full runnable project is in [examples/express](https://github.com/SolveJet/whatsapp-cloud-api/tree/master/examples/express). Each step is explained in [verify the signature](/whatsapp-cloud-api/webhooks/verify-signature/) and [the hub.challenge handshake](/whatsapp-cloud-api/webhooks/verification-request/). Meta's own description of the two request types is in the [webhook endpoint guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint). --- # WhatsApp Cloud API webhook in Fastify with signature verification Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/fastify/ Fastify parses JSON before your handler runs, so replace the `application/json` parser with one that uses `parseAs: 'buffer'`. The route then receives the raw `Buffer`, which you pass to `handleDelivery` together with the `x-hub-signature-256` header. The route answers with the status it returns. ```ts title="examples/fastify/server.ts" import Fastify from 'fastify'; import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api'; import { echoText, requireEnv } from '../shared/reply.js'; const webhook = createWebhookHandler({ appSecrets: requireEnv('WHATSAPP_APP_SECRET'), verifyToken: requireEnv('WHATSAPP_VERIFY_TOKEN'), }); webhook.on('message', ({ message }) => echoText(message)); const app = Fastify(); // Keep the JSON body as a raw Buffer so the signature can be checked against // the exact bytes Meta sent. The handler parses it after verification. app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (_request, body, done) => { done(null, body); }); // Verify-token handshake. app.get<{ Querystring: Record }>('/webhook', async (request, reply) => { const { statusCode, body } = webhook.handleVerification(request.query); return reply.code(statusCode).type('text/plain').send(body); }); app.post('/webhook', async (request, reply) => { const signature = request.headers['x-hub-signature-256']; const result = await webhook.handleDelivery( request.body as Buffer, typeof signature === 'string' ? signature : undefined, ); return reply.code(result.httpStatus).type('text/plain').send(''); }); await app.listen({ port: 3000 }); ``` The full runnable project is in [examples/fastify](https://github.com/SolveJet/whatsapp-cloud-api/tree/master/examples/fastify). Each step is explained in [verify the signature](/whatsapp-cloud-api/webhooks/verify-signature/) and [the hub.challenge handshake](/whatsapp-cloud-api/webhooks/verification-request/). Meta's own description of the two request types is in the [webhook endpoint guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint). --- # Handling events Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/handling-events/ `extractMessages` and `extractStatuses` flatten a payload. Message types the SDK does not model still parse; handle them in the `default` branch. ```ts import { extractMessages, extractStatuses, parseWebhook } from '@solvejet/whatsapp-cloud-api'; const payload = parseWebhook(rawBody); // after verifying the signature for (const message of extractMessages(payload)) { switch (message.type) { case 'text': console.log(`text from ${message.from_user_id ?? message.from}: ${message.text.body}`); break; case 'interactive': console.log(message.interactive.button_reply?.id ?? message.interactive.list_reply?.id); break; default: console.log(`unhandled message type: ${message.type}`); } } for (const status of extractStatuses(payload)) { console.log(`message ${status.id} -> ${status.status}`); } ``` Return `200` fast and do the work afterwards. Meta retries deliveries, so deduplicate on the message id (`wamid`). `extractMessages`, `extractStatuses` and `parse` read the `messages` webhook field only. Other fields, such as `calls`, `message_template_status_update` or `account_update`, are not parsed into `messages` or `statuses`. Their payload is still available in `parsed.raw`. To get typed events for those fields (`call`, `flow`, `template`, `account`, `group`, plus `unknown` for the rest), use `parseWebhookEvents(rawBody)` or [`createWebhookHandler`](/whatsapp-cloud-api/webhooks/handling-events/#webhook-handler). ## Webhook handler `createWebhookHandler` answers the handshake, verifies `X-Hub-Signature-256` over the raw body, parses the delivery, skips duplicates and calls your handlers. ```ts import { createMemoryDedupe, createWebhookHandler } from '@solvejet/whatsapp-cloud-api'; const webhook = createWebhookHandler({ appSecrets: process.env.WHATSAPP_APP_SECRET!, // a string or an array (secret rotation) verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, dedupe: createMemoryDedupe(), }); webhook.on('message', async ({ message, ctx }) => { console.log(ctx.wabaId, message.id, message.type); }); webhook.on('status', ({ status }) => console.log(status.id, status.status)); ``` Pass the raw body to `handleDelivery(rawBody, signatureHeader)` (Express, Fastify) or the whole `Request` to `handleRequest(request)` (Next.js, Hono, Workers, Bun, Deno). `handleVerification(query)` answers the GET handshake. Both delivery methods return the status to send. Events: `message`, `status`, `error`, `call`, `flow`, `template`, `account`, `group` and `unknown`. Every event has a `ctx` with `wabaId`, `field`, `time`, `metadata` and the matching `contact`. Fields the SDK does not model arrive as `unknown` with the untouched `value`. `parseWebhookEvents(body)` gives the same events without a handler. | Situation | Status | | ------------------------------------------------- | ----------------------------- | | Missing or wrong signature, or no tenant resolved | `401` | | Body over `maxBodyBytes` (3 MiB by default) | `413` | | Valid signature, body that is not a webhook | `200`, reported to `onError` | | Valid delivery | `200` | | A handler threw, `retryOnHandlerError: true` | `500` | | Other method on `handleRequest` | `405` with `Allow: GET, POST` | Options: - `ackMode`: `'after'` (default) runs the handlers before answering. `'before'` answers once the delivery is verified and parsed and runs the handlers in the background. Pass `waitUntil` (option or second argument of `handleRequest`) so serverless platforms keep the invocation alive. - `dedupe`: skips events Meta delivered twice. Default keys are `message:` and `status::`; override with `dedupeKey`. `createMemoryDedupe` is per process, so use your own `WebhookDedupe` when several instances share traffic. - `maxEventAgeSeconds`: skips old message and status events. - `concurrency` (default 8): events handled at the same time within one delivery. - `retryOnHandlerError`: answer `500` when a handler throws so Meta redelivers. - `resolveTenant(request)`: pick secrets and verify token per request for several apps. - `onError(error, info)`: receives handler errors and invalid envelopes. Defaults to `console.error`. - `allowUnsigned`: with no secret configured, accepting unsigned deliveries logs a one-time warning (`WHATSAPP_WEBHOOK_UNSIGNED`). Set `true` to silence it. When secrets are set, the signature is always required. The `IncomingMessage` union now includes `order`, `unsupported`, `edit` and `revoke` messages. If you check a `switch` on `message.type` for exhaustiveness with a `never` assignment, add the new cases or a `default` branch. `isKnownMessage(message)` narrows a message to the modelled types. ## Edge runtimes `@solvejet/whatsapp-cloud-api/web` exports the handler, parsers, dedupe and `verifySignatureAsync` without any `node:` import. It verifies signatures with Web Crypto. ```ts import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api/web'; export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { const webhook = createWebhookHandler({ appSecrets: env.WHATSAPP_APP_SECRET, verifyToken: env.WHATSAPP_VERIFY_TOKEN, ackMode: 'before', }); webhook.on('message', ({ message }) => console.log(message.id)); return webhook.handleRequest(request, { waitUntil: (promise) => ctx.waitUntil(promise) }); }, }; ``` For `waitUntil`, use `ctx.waitUntil` on Cloudflare, `waitUntil` from `@vercel/functions` or `after()` from `next/server` on Vercel. Long-running servers on Node, Bun and Deno do not need it. [Runtime support](/whatsapp-cloud-api/getting-started/install/#runtime-support) lists what CI runs. ## Testing your webhook handler `@solvejet/whatsapp-cloud-api/testing` builds deliveries and signed requests, so you can test handlers in-process. ```ts import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api/web'; import { buildWebhookPayload, createTestRequest } from '@solvejet/whatsapp-cloud-api/testing'; const webhook = createWebhookHandler({ appSecrets: 'test-secret' }); webhook.on('message', ({ message }) => console.log(message.id)); const request = await createTestRequest({ payload: buildWebhookPayload('text'), secret: 'test-secret', }); const response = await webhook.handleRequest(request); // 200 ``` `buildWebhookPayload` kinds: `text`, `status`, `call`, `template_status`, `flow`, `account_update`, `group`. `signWebhookBody(body, secret)` returns the `sha256=` header value. Both are async-signing helpers that run on Node 20+, Bun, Deno and workerd. --- # WhatsApp Cloud API webhook in Hono with signature verification Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/hono/ In Hono, hand the underlying fetch `Request` (`c.req.raw`) to `handleRequest`. It answers the GET handshake and the signed POST, and reads the raw bytes itself, so do not call `c.req.json()` first. ```ts title="examples/hono/server.ts" import { serve } from '@hono/node-server'; import { Hono } from 'hono'; import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api'; import { echoText, requireEnv } from '../shared/reply.js'; const webhook = createWebhookHandler({ appSecrets: requireEnv('WHATSAPP_APP_SECRET'), verifyToken: requireEnv('WHATSAPP_VERIFY_TOKEN'), }); webhook.on('message', ({ message }) => echoText(message)); const app = new Hono(); // handleRequest takes a fetch Request and answers both the GET handshake and the // signed POST. It reads the raw bytes itself, so do not parse the body first. app.all('/webhook', (c) => webhook.handleRequest(c.req.raw)); serve({ fetch: app.fetch, port: 3000 }); console.log('Listening on http://localhost:3000/webhook'); ``` The full runnable project is in [examples/hono](https://github.com/SolveJet/whatsapp-cloud-api/tree/master/examples/hono). Each step is explained in [verify the signature](/whatsapp-cloud-api/webhooks/verify-signature/) and [the hub.challenge handshake](/whatsapp-cloud-api/webhooks/verification-request/). Meta's own description of the two request types is in the [webhook endpoint guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint). --- # WhatsApp Cloud API webhook in a Next.js App Router route handler Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/nextjs/ In a Next.js App Router route handler, pass the `Request` to `handleRequest` from `createWebhookHandler`. It reads the raw bytes itself, so do not call `request.json()` first. The example imports from the `/web` entry point and keeps the default `ackMode`, so the handlers finish before the response. To answer first, set `ackMode: 'before'` and pass `waitUntil`; see [Edge runtimes](/whatsapp-cloud-api/webhooks/edge-runtimes/). ```ts title="examples/nextjs/app/api/webhook/route.ts" // Next.js App Router route handler: app/api/webhook/route.ts import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api/web'; import { echoText, requireEnv } from '../../../../shared/reply.js'; // The default ackMode ('after') runs the handlers before answering, so the work // finishes inside the invocation. To answer first, set ackMode: 'before' and // pass waitUntil from @vercel/functions (or use after() from next/server). const webhook = createWebhookHandler({ appSecrets: requireEnv('WHATSAPP_APP_SECRET'), verifyToken: requireEnv('WHATSAPP_VERIFY_TOKEN'), }); webhook.on('message', ({ message }) => echoText(message)); // Verify-token handshake and signed deliveries both go through handleRequest. export const GET = (request: Request): Promise => webhook.handleRequest(request); export const POST = (request: Request): Promise => webhook.handleRequest(request); ``` The full runnable project is in [examples/nextjs](https://github.com/SolveJet/whatsapp-cloud-api/tree/master/examples/nextjs). Each step is explained in [verify the signature](/whatsapp-cloud-api/webhooks/verify-signature/) and [the hub.challenge handshake](/whatsapp-cloud-api/webhooks/verification-request/). Meta's own description of the two request types is in the [webhook endpoint guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint). --- # Webhooks Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/overview/ Last verified against Graph API v26.0 on 2026-11-21. Receiving inbound messages and delivery statuses is a two-step model: 1. **GET verification.** When you configure the webhook, Meta sends a GET request with `hub.mode`, `hub.verify_token`, and `hub.challenge`. Echo the raw `hub.challenge` back with a `200` when the token matches your verify token; otherwise return `403`. The challenge must be the raw response body, not JSON. 2. **POST deliveries.** Meta POSTs event payloads signed with `X-Hub-Signature-256`. Verify the signature against the **raw request body** using your App Secret, return `200` quickly, then process. Three secrets are involved, and they are not interchangeable: - **Verify token:** a string you define, used only for the GET handshake. - **App Secret:** from your Meta app settings, used to verify `X-Hub-Signature-256`. - **Access token:** used to _send_ messages, never for webhooks. `createWebhookHandler` is the quickest way to receive webhooks: it does both steps and calls the handlers you register. See [Webhook handler](/whatsapp-cloud-api/webhooks/handling-events/#webhook-handler). The rest of this section covers the lower-level `WebhookHandler`, which binds the secrets once. `handler.handleVerification(query)` answers the handshake, and `handler.parse(rawBody, signature)` verifies the signature and parses the payload, throwing `WhatsAppWebhookError` when the signature is missing or invalid. Signature checking is on only when you pass `appSecret`. If you leave the `appSecret` key out, `parse` accepts unsigned bodies, so only do that when something else authenticates the request. If you pass `appSecret` or `verifyToken` with an `undefined` or empty value (for example an unset environment variable), the constructor throws a `WhatsAppWebhookError` instead of quietly turning verification off. `verifySignature` returns `false`, and the verify-token handshake returns `403`, whenever the configured secret is empty. `handler.parse` rejects bodies over 3 MiB (Meta's documented maximum) before hashing or parsing them. Raise the limit with `new WebhookHandler({ maxBodyBytes })`, or pass `false` to turn it off. --- # Webhooks: raw body Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/raw-body/ The signature is computed over the exact bytes Meta sent. Pass the **raw body bytes** to `parse`, `isValid` and `verifySignature`: a `Buffer`, `Uint8Array`, `ArrayBuffer` or the unmodified body string. Never pass a re-serialized `req.body` (for example `JSON.stringify(req.body)`), because the bytes change and a valid signature fails. Respond only after the payload parsed. Return `401` for a bad signature, and `200` for a signed payload that cannot be parsed (log it), so Meta does not retry a permanently bad payload for days. Express: ```ts import express from 'express'; import { WebhookHandler, WhatsAppWebhookError } from '@solvejet/whatsapp-cloud-api'; const handler = new WebhookHandler({ appSecret: process.env.WHATSAPP_APP_SECRET!, verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, }); const app = express(); app.get('/webhook', (req, res) => { const query: Record = {}; for (const [key, value] of Object.entries(req.query)) { if (typeof value === 'string') query[key] = value; } const { statusCode, body } = handler.handleVerification(query); res.status(statusCode).type('text/plain').send(body); }); // express.raw keeps the body as a Buffer. Do not put express.json() before this route. app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => { const rawBody = req.body as Buffer; const signature = req.get('x-hub-signature-256'); if (!handler.isValid(rawBody, signature)) { res.sendStatus(401); // bad signature return; } try { const { messages, statuses } = handler.parse(rawBody, signature); res.sendStatus(200); // handle messages and statuses here, without letting one failure drop the rest } catch (error) { if (error instanceof WhatsAppWebhookError) { console.error('Ignoring malformed webhook payload:', error.message); res.sendStatus(200); // signed but unparseable: do not make Meta retry it return; } console.error(error); res.sendStatus(500); } }); ``` Next.js App Router (`app/api/webhook/route.ts`): ```ts import { WebhookHandler, WhatsAppWebhookError } from '@solvejet/whatsapp-cloud-api'; const handler = new WebhookHandler({ appSecret: process.env.WHATSAPP_APP_SECRET!, verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, }); export async function GET(request: Request) { const query: Record = {}; for (const [key, value] of new URL(request.url).searchParams) query[key] = value; const { statusCode, body } = handler.handleVerification(query); return new Response(body, { status: statusCode, headers: { 'content-type': 'text/plain' } }); } export async function POST(request: Request) { const rawBody = await request.arrayBuffer(); // not request.json() const signature = request.headers.get('x-hub-signature-256') ?? undefined; if (!handler.isValid(rawBody, signature)) { return new Response('Unauthorized', { status: 401 }); } try { const { messages } = handler.parse(rawBody, signature); // Serverless functions can stop after the response, so await the work. Settle // every message on its own so one failure does not drop the batch. const results = await Promise.allSettled(messages.map((message) => handleMessage(message))); for (const result of results) { if (result.status === 'rejected') console.error(result.reason); } return new Response('OK'); } catch (error) { if (error instanceof WhatsAppWebhookError) { console.error('Ignoring malformed webhook payload:', error.message); return new Response('OK'); // signed but unparseable: do not make Meta retry it } console.error(error); return new Response('Internal Server Error', { status: 500 }); } } ``` Hono and Fastify versions are in [`examples/`](https://github.com/SolveJet/whatsapp-cloud-api/blob/master/examples/README.md). --- # Test a WhatsApp webhook handler without Meta (signed requests in TypeScript) Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/testing-your-webhook-handler/ The `@solvejet/whatsapp-cloud-api/testing` entry point builds valid deliveries and signs them the way Meta does, so you can test a handler in-process with no tunnel. It only uses Web Crypto and works on Node 20 and later, Bun, Deno and workerd. The main entry does not import it. ## Send a signed delivery to your handler ```ts title="website/snippets/testing-handler.ts" const webhook = createWebhookHandler({ appSecrets: secret, verifyToken: 'test-token' }); const texts: string[] = []; webhook.on('message', ({ message }) => { if (message.type === 'text') texts.push(message.text.body); }); // A signed POST shaped like a Meta delivery. const request = await createTestRequest({ payload: buildWebhookPayload('text', { entry: [ { id: '102290129340398', changes: [ { field: 'messages', value: { messaging_product: 'whatsapp', metadata: { display_phone_number: '15550783881', phone_number_id: '106540352242922' }, messages: [ { from: '15551234567', id: 'wamid.TEST', timestamp: '1700000000', type: 'text', text: { body: 'hi' }, }, ], }, }, ], }, ], }), secret, }); const response = await webhook.handleRequest(request); // response.status is 200 and texts is ['hi']. ``` `buildWebhookPayload(kind, overrides?)` builds a complete delivery. The kinds are `text`, `status`, `call`, `template_status`, `flow`, `account_update` and `group`. Plain objects in `overrides` merge key by key. Arrays replace the default. Keys named `__proto__`, `constructor` or `prototype` throw `WhatsAppWebhookError`. `createTestRequest` takes a `payload` or an exact `body`, plus an optional `secret`, `signature`, `url` and `headers`, and returns a `POST` `Request`. It is async because signing is. ## Check that bad requests are rejected ```ts title="website/snippets/testing-handler.ts" // A request with a wrong signature gets 401 and runs no handler. const forged = await createTestRequest({ payload: buildWebhookPayload('status'), signature: 'sha256=' + '0'.repeat(64), }); const rejected = await webhook.handleRequest(forged); // rejected.status is 401. ``` ## Sign a body yourself ```ts title="website/snippets/testing-handler.ts" // Sign a body yourself, for example to call a running server with fetch. const signature = await signWebhookBody('{"object":"whatsapp_business_account"}', secret); ``` `signWebhookBody` returns `sha256=`, the value of the `X-Hub-Signature-256` header. Related: [the webhook handler](/whatsapp-cloud-api/webhooks/webhook-handler/) and [edge runtimes](/whatsapp-cloud-api/webhooks/edge-runtimes/). --- # Handle the WhatsApp webhook verification request (hub.challenge) Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/verification-request/ ## What Meta sends When you set or edit the **Callback URL** or **Verify token** in the App Dashboard, Meta sends a `GET` request to your endpoint. Per Meta's [webhook endpoint guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint), the query string has three parameters: - `hub.mode`, always `subscribe`. - `hub.challenge`, a string Meta generates. - `hub.verify_token`, the verify token you typed into the dashboard. To pass, compare `hub.verify_token` with the string stored on your server. If it matches, respond with HTTP `200` and the `hub.challenge` value. Otherwise respond with a 400-level status or anything other than `200`. If your endpoint answers anything else, Meta treats it as unverified and sends no webhooks. The [Graph API webhooks guide](https://developers.facebook.com/docs/graph-api/webhooks/getting-started) adds that PHP rewrites dots in query names to underscores, which matters only if you run PHP. The verify token is a string you choose. It is separate from your app secret and your access token. ## With the SDK ```ts title="website/snippets/hub-challenge.ts" const handler = new WebhookHandler({ verifyToken: process.env.WHATSAPP_VERIFY_TOKEN! }); // Returns { statusCode: 200, body: } when hub.mode is "subscribe" and the // token matches. Otherwise returns { statusCode: 403, body: 'Forbidden' }. const { statusCode, body } = handler.handleVerification(query); // Send `body` as plain text with status `statusCode`. Do not wrap it in JSON. ``` On success, `handleVerification` returns `{ statusCode: 200, body: }`. On any mismatch it returns `{ statusCode: 403, body: 'Forbidden' }`. Return `body` as the raw response body with a text content type. Do not wrap it in JSON. Behavior, as covered in the SDK's tests: - The token comparison is constant-time. - `hub.mode` must be `subscribe`. - An empty or missing expected token always gives `403`, so an unset environment variable can never accept a request. - The `WebhookHandler` constructor throws `WhatsAppWebhookError` when `verifyToken` is present but empty. `handleVerification` throws the same error when the handler was built without a `verifyToken`. ```ts title="website/snippets/hub-challenge.ts" // The same check without a handler. Keys are the literal hub.* names. const fromQuery = verifyWebhookQuery(query, process.env.WHATSAPP_VERIFY_TOKEN!); // Or with the three values already extracted from hub.mode, hub.verify_token and hub.challenge. declare const mode: string; declare const token: string; declare const challenge: string; const fromParts = verifyWebhook({ mode, token, challenge }, process.env.WHATSAPP_VERIFY_TOKEN!); ``` `verifyWebhookQuery` takes the query map with the literal `hub.*` keys, and `verifyWebhook` takes the three values. Both return the same `{ statusCode, body }` result. Next, [verify the signature of each delivery](/whatsapp-cloud-api/webhooks/verify-signature/). Framework recipes: [Express](/whatsapp-cloud-api/webhooks/express/), [Next.js](/whatsapp-cloud-api/webhooks/nextjs/), [Hono](/whatsapp-cloud-api/webhooks/hono/), [Fastify](/whatsapp-cloud-api/webhooks/fastify/). --- # Verify WhatsApp Cloud API webhook signatures in Node.js (X-Hub-Signature-256) Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/verify-signature/ ## What Meta sends Every webhook `POST` carries an `X-Hub-Signature-256` header of the form `sha256=`. Per Meta's [webhook endpoint guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint), the hash is an HMAC-SHA256 of the JSON payload using your app secret as the key. To validate, compute that HMAC over the payload, compare it with the part of the header after `sha256=`, and treat the request as invalid if they differ. Meta says to answer a valid request with `200` and an invalid one with a 400-level status or anything other than `200`. Verifying is optional on Meta's side. Do it anyway: without it, anyone who finds your URL can post fake events. The HMAC is computed over the exact bytes Meta sent. If your framework parses the JSON first and you hash `JSON.stringify(body)`, the bytes can differ and valid signatures fail. Keep the raw body. See [Webhooks: raw body](/whatsapp-cloud-api/webhooks/raw-body/) and the recipes for [Express](/whatsapp-cloud-api/webhooks/express/), [Next.js](/whatsapp-cloud-api/webhooks/nextjs/), [Hono](/whatsapp-cloud-api/webhooks/hono/) and [Fastify](/whatsapp-cloud-api/webhooks/fastify/). ## With the SDK ```ts title="website/snippets/verify-signature.ts" // The function form: returns true only when the header is present, starts with // "sha256=" and matches the HMAC-SHA256 of the raw body keyed with the app secret. const ok = verifySignature(rawBody, signatureHeader, process.env.WHATSAPP_APP_SECRET!); if (!ok) { // Respond 401 and stop. Do not parse the body. } ``` `verifySignature(rawBody, signatureHeader, appSecret)` returns a boolean and never throws on bad input. It accepts a `string`, `Uint8Array` (including `Buffer`) or `ArrayBuffer`. The comparison is constant-time. It returns `false` when the header is missing, does not start with `sha256=`, or does not match, and always `false` when `appSecret` is empty or not a string, so an unset environment variable cannot validate anything. ```ts title="website/snippets/verify-signature.ts" // The handler form: binds the secret once. The constructor throws // WhatsAppWebhookError when appSecret is present but empty or not a string. const handler = new WebhookHandler({ appSecret: process.env.WHATSAPP_APP_SECRET! }); handler.isValid(rawBody, signatureHeader); // boolean, never throws handler.verifyOrThrow(rawBody, signatureHeader); // throws WhatsAppWebhookError when invalid const { messages, statuses } = handler.parse(rawBody, signatureHeader); // verify, then parse ``` `WebhookHandler` binds the secret once: - `isValid` returns a boolean. - `verifyOrThrow` throws `WhatsAppWebhookError` when the signature is wrong. - `parse` verifies and then parses, so a bad signature throws before any parsing happens. - The constructor throws `WhatsAppWebhookError` when `appSecret` or `verifyToken` is present but empty or not a string. Omitting the `appSecret` key disables signature enforcement, so `parse` accepts unsigned bodies. Only do that when something else authenticates the request. ## Body size Meta states that webhook payloads can be up to 3 MB. `WebhookHandler.parse` and `parseWebhook` reject a string or byte body above `maxBodyBytes`, which defaults to 3 MiB (3,145,728 bytes), before hashing or parsing. Pass `maxBodyBytes` to change the limit or `false` to turn it off: ```ts title="website/snippets/verify-signature.ts" // Default 3 MiB. Pass a number to lower it, or false to turn the check off. new WebhookHandler({ appSecret: process.env.WHATSAPP_APP_SECRET!, maxBodyBytes: 1024 * 1024 }); ``` An oversized body throws `WhatsAppWebhookError`. ## Which status code to return The recipes answer a bad signature with `401`. They answer a validly signed but malformed payload with `200`, because Meta retries non-`200` deliveries for up to 7 days and a payload that cannot parse will never succeed. Meta can deliver the same event more than once, so deduplicate by message ID. For the verification request that Meta sends when you save the webhook URL, see [the hub.challenge handshake](/whatsapp-cloud-api/webhooks/verification-request/). --- # WhatsApp Cloud API webhook handler with typed events in TypeScript Source: https://solvejet.github.io/whatsapp-cloud-api/webhooks/webhook-handler/ `createWebhookHandler` wraps the whole receiving side: it answers the verify-token handshake, checks `X-Hub-Signature-256` against the raw body, parses the delivery, skips duplicates and calls the handlers you register. The lower-level `WebhookHandler`, `verifySignature` and `parseWebhook` stay available and behave as before. ## Create a handler ```ts title="website/snippets/webhook-handler.ts" const webhook = createWebhookHandler({ appSecrets: process.env.WHATSAPP_APP_SECRET!, // or an array while you rotate the secret verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, }); ``` `appSecrets` takes one secret or an array, so you can accept the old and the new App Secret while you rotate. The signature check always runs when a secret is set. ## Register event handlers ```ts title="website/snippets/webhook-handler.ts" webhook.on('message', async ({ message, ctx }) => { if (message.type === 'text') { console.log(`text from ${message.from_user_id ?? message.from}: ${message.text.body}`); } console.log(`received on WABA ${ctx.wabaId}`); }); webhook.on('status', ({ status }) => { console.log(`message ${status.id} -> ${status.status}`); }); webhook.on('call', ({ event }) => { if (event.kind === 'terminate') console.log(`call ended after ${event.value.duration ?? 0}s`); }); webhook.on('template', ({ event }) => { console.log(`template event: ${event.kind}`); }); webhook.on('unknown', ({ field, value }) => { console.log(`field ${field} is not modelled yet`, value); }); // on() returns a function that removes the handler again. const stop = webhook.on('error', ({ error }) => console.error(error)); stop(); ``` | Event | Payload | Meta webhook fields | | ---------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `message` | `message`, `ctx` | `messages` (one event per message) | | `status` | `status`, `ctx` | `messages` (one event per status) | | `error` | `error`, `ctx` | `messages` (one event per `errors[]` entry) | | `call` | `event` (`connect`, `terminate`, `status`) | `calls` | | `flow` | `event` (`kind` is the flow event name) | `flows` | | `template` | `event` | `message_template_status_update`, `message_template_quality_update`, `template_category_update` | | `account` | `event` | `phone_number_quality_update`, `account_update`, `account_alerts`, `user_preferences`, `business_username_updates` | | `group` | `event` | `group_lifecycle_update`, `group_participants_update`, `group_settings_update`, `group_status_update` | | `unknown` | `field`, `value`, `ctx` | every other field, with the untouched `value` | `ctx` carries `wabaId`, `field`, `time`, the phone number `metadata` and the matching `contact` when the delivery has one. Handlers for one event run one after another. Events of one delivery run at the same time, up to `concurrency`. A handler that throws is reported to `onError` and does not stop the others. ## Answer Meta ```ts title="website/snippets/webhook-handler.ts" // Node frameworks: pass the raw bytes and answer with the status it returns. const verification = webhook.handleVerification(query); // { statusCode, body } const result = await webhook.handleDelivery(rawBody, signatureHeader); // result.httpStatus is 200, 401, 413 or 500. ``` ```ts title="website/snippets/webhook-handler.ts" // Fetch-style runtimes: one call answers both the GET handshake and the POST delivery. const response: Response = await webhook.handleRequest(request); ``` | Situation | Status | | ------------------------------------------------------- | ---------------------------- | | Missing or wrong signature, or no tenant resolved | `401` | | Body over `maxBodyBytes` (3 MiB by default) | `413` | | Valid signature, body that is not JSON or not a webhook | `200`, reported to `onError` | | Valid delivery | `200` | | A handler threw and `retryOnHandlerError` is `true` | `500` | | Method other than `GET` or `POST` on `handleRequest` | `405` | A valid signature with an unreadable body gets `200` so Meta does not retry a payload that can never parse. The size limit is checked from `content-length` and again while the body streams in. By default the handlers run before the answer (`ackMode: 'after'`). With `ackMode: 'before'` the handler answers once the delivery is verified and parsed, and runs the handlers in the background. Pass `waitUntil` so serverless platforms keep the invocation alive; see [Edge runtimes](/whatsapp-cloud-api/webhooks/edge-runtimes/). ## Options ```ts title="website/snippets/webhook-handler.ts" const configured = createWebhookHandler({ appSecrets: [process.env.WHATSAPP_APP_SECRET!, process.env.WHATSAPP_APP_SECRET_OLD!], verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, dedupe: createMemoryDedupe({ ttlMs: 60 * 60 * 1000, maxEntries: 10_000 }), maxEventAgeSeconds: 15 * 60, // skip message and status events older than 15 minutes concurrency: 8, // events handled at the same time within one delivery retryOnHandlerError: true, // answer 500 when a handler throws so Meta redelivers onError: (error, info) => console.error('handler failed', info.event?.name, error), }); ``` Meta can deliver the same event more than once. The default dedupe keys are `message:` and `status::`; other events are not deduplicated. `createMemoryDedupe` keeps keys in memory for one process, so serverless instances do not share it. Pass your own `WebhookDedupe` backed by Redis or a database for that. With `retryOnHandlerError`, keys of failed events are released so Meta's retry is not skipped. Set `allowUnsigned: true` only when no secret is configured on purpose. Without any secret, the handler accepts unsigned deliveries and emits a one-time warning (`WHATSAPP_WEBHOOK_UNSIGNED`) unless you set it. ## Serve several apps ```ts title="website/snippets/webhook-handler.ts" const multiTenant = createWebhookHandler({ // Pick the secrets and verify token from the request, for example from the URL path. resolveTenant: (incoming) => { const tenantId = new URL(incoming.url).pathname.split('/').pop(); return tenantId === 'acme' ? { appSecrets: process.env.ACME_APP_SECRET!, verifyToken: process.env.ACME_VERIFY_TOKEN! } : undefined; // unknown tenant: 401 on POST, 403 on GET }, }); ``` Related: [verify the signature](/whatsapp-cloud-api/webhooks/verify-signature/), [handling events](/whatsapp-cloud-api/webhooks/handling-events/) and [testing your webhook handler](/whatsapp-cloud-api/webhooks/testing-your-webhook-handler/).