WhatsApp Business Cloud
Connect to WhatsApp Business Cloud for customer messaging and automated conversations.
Create a new bot
Scaffold a Next.js bot with the WhatsApp Business Cloud adapter using create-chat-sdk:
pnpm create chat-sdk@latest my-bot --adapter whatsapp memory -yThe generated app uses the Memory state adapter for local development. To add the adapter to an existing app, start at Install.
Install
pnpm add @chat-adapter/whatsapp @chat-adapter/state-memoryQuick start
The adapter auto-detects WHATSAPP_ACCESS_TOKEN, WHATSAPP_APP_SECRET, WHATSAPP_PHONE_NUMBER_ID, and WHATSAPP_VERIFY_TOKEN from the environment.
The memory state adapter keeps subscriptions and locks in process memory, which suits local development. Use Redis or PostgreSQL in production.
Platform setup
Create a Meta app
- Go to developers.facebook.com/apps and create a Business app.
- Add the WhatsApp product to your app.
Get credentials
From your Meta app dashboard, copy:
- App Secret (under App Settings then Basic) to
WHATSAPP_APP_SECRET. - Access Token (under WhatsApp then API Setup) to
WHATSAPP_ACCESS_TOKEN. The token shown there is temporary. For production, generate a permanent System User Token instead. - Phone Number ID (under WhatsApp then API Setup) to
WHATSAPP_PHONE_NUMBER_ID.
Choose your own random string for WHATSAPP_VERIFY_TOKEN. You enter the same value in the next step.
Configure webhooks
Deploy the GET and POST route shown above to a public HTTPS URL first, then:
- Open WhatsApp then Configuration.
- Set the callback URL to
https://your-domain.com/api/webhooks/whatsapp. - Set Verify Token to the same value as
WHATSAPP_VERIFY_TOKEN. - Subscribe to the
messageswebhook field. Also subscribe touser_id_updateso the adapter can follow user ID rotations.
Configuration
| Prop | Type | Default | Description |
|---|---|---|---|
accessToken? | string | Meta access token. Auto-detected from `WHATSAPP_ACCESS_TOKEN`. | |
appSecret? | string | App secret for webhook verification. Auto-detected from `WHATSAPP_APP_SECRET`. | |
phoneNumberId? | string | Bot's phone number ID. Auto-detected from `WHATSAPP_PHONE_NUMBER_ID`. | |
verifyToken? | string | Webhook verification secret. Auto-detected from `WHATSAPP_VERIFY_TOKEN`. | |
apiVersion? | string | "v25.0" | Graph API version. |
userName? | string | "whatsapp-bot" | Bot username for self-message detection. Auto-detected from `WHATSAPP_BOT_USERNAME`. |
apiUrl? | string | Override the Meta Graph API base URL. Auto-detected from `WHATSAPP_API_URL`. |
Environment variables
| Variable | Required | Description |
|---|---|---|
WHATSAPP_ACCESS_TOKEN | Yes | Meta access token, ideally a System User Token in production |
WHATSAPP_APP_SECRET | Yes | App secret used to verify webhook signatures |
WHATSAPP_PHONE_NUMBER_ID | Yes | Default phone number ID. Thread replies use the number in the thread id |
WHATSAPP_VERIFY_TOKEN | Yes | Your chosen secret for the webhook verification handshake |
WHATSAPP_BOT_USERNAME | No | Bot username. Defaults to whatsapp-bot |
WHATSAPP_API_URL | No | Meta Graph API base URL override |
Webhooks
The route handles two kinds of request from Meta:
- GET verification handshake: Meta sends a
hub.verify_tokenchallenge that must matchWHATSAPP_VERIFY_TOKEN. - POST event delivery: incoming messages, reactions, and interactive responses, signed with
X-Hub-Signature-256and verified againstWHATSAPP_APP_SECRET.
Message formatting
Pass { markdown: text } to convert standard Markdown to WhatsApp formatting:
**bold** becomes *bold*, _italic_ stays _italic_, and ~~strike~~ becomes
~strike~. Literal text such as (~80 % easy) is sent as written, and code
content and intentional backslashes are preserved. WhatsApp has no escape syntax,
so when escaped text like \_word\_ or a line starting with \> would otherwise
turn into formatting, the adapter keeps the backslash and it shows in the message.
Interactive messages
The adapter converts card elements to WhatsApp interactive messages:
- A card with buttons renders as WhatsApp reply buttons. Titles longer than 20 characters are truncated.
- Only the first 3 buttons are sent. Extra buttons are dropped.
- Body text is truncated to 1024 characters.
- A card without buttons is sent as formatted text, unless it qualifies as a CTA URL message.
WhatsApp reply buttons cannot open URLs, so when a card with reply buttons also contains link buttons, each link button is appended to the interactive message body as a Label: url line.
Link buttons (CTA URL)
A card whose only interactive element is a single LinkButton is sent as a native WhatsApp CTA URL message with a tappable link button. The card is promoted only when all of these hold:
- The
LinkButtonis the card's only action across every actions row, including rows nested in sections. Reply buttons, selects, radio selects, or a second populated actions row keep the text fallback. - The URL starts with
http://orhttps://and the label is non-empty. Other schemes (mailto:,tel:, relative paths) keep the text fallback because the Cloud API rejects them. - The card has no header
imageUrland no image, table, chart, or inline link children. The interactive body cannot carry those, so such cards keep the text fallback to avoid losing content. Text, fields, sections, and dividers are fine. - The post has no
filesorattachments. When media accompanies the card, the adapter keeps the single captioned media send.
The button label is truncated to 20 characters, the header (card title) to 60, and the body to 1024. Cards that do not match these rules fall back to formatted text, where link buttons render as Label: url.
Template messages
Outside the 24-hour customer service window, WhatsApp only accepts pre-approved template messages. Use sendTemplate to start business-initiated conversations:
Templates must be created and approved in WhatsApp Manager before they can be sent. Quick reply button taps on a template arrive as button responses and are dispatched to your onAction handlers.
Contextual replies
Use thread.reply() to quote a specific message in WhatsApp:
You can pass either a Message or a message ID as the target. Text, cards, files, and buffered streams are supported. When one logical reply produces multiple WhatsApp messages, only the first message includes the contextual reference.
Replies are outbound only. When a user quote-replies to one of your messages, the adapter does not yet surface what they quoted, so message.replyTo is undefined on inbound WhatsApp messages.
WhatsApp does not display the quoted bubble when the target was deleted or moved to long-term storage, when the reply is a template message, or for some media replies on KaiOS. Reaction messages cannot be contextual replies. See Meta's contextual replies documentation.
File uploads
postMessage accepts both files and attachments (typed media with optional data, fetchData, or a public URL). See the file uploads guide for the shared API.
WhatsApp allows one media item per message, which shapes how the adapter sends files:
- Multiple
filesorattachmentsin a singlepost()are sent as sequential messages, and the last message ID is returned. - Markdown, or card fallback text, is attached as a caption on the first media message when supported, up to 1024 characters. Text is sent as a separate message first when the caption is too long or when the first media is audio, because audio does not support captions.
- Buffers are uploaded through the Cloud API
/mediaendpoint.attachmentswith only aurluse HTTPS link passthrough without an upload. URLs must usehttps://. - When a card renders as reply buttons, media is sent first without a caption, and the interactive message that follows carries the title, body, and buttons. When the card falls back to plain text, the fallback text captions the first media, and the caption includes a
Label: urlline for each link button. A card with only a link button is not promoted to a CTA URL message when media is attached, so it takes this captioned path too. - To send a photo with buttons, pass the image through
filesorattachments. Card-embedded images (imageUrlor<Image>children) are not sent as native media.
Inbound attachments
Incoming media attachments expose a lazy fetchData(). Media is downloaded only from Meta's fbcdn.net and fbsbx.com hosts or the configured Graph origin. Downloads refuse private and internal addresses, are limited to 25 MB, and time out after 30 seconds, and the access token never follows a redirect off those hosts. Pass a custom transport to downloadMedia() to route downloads through a proxy.
Typing indicators
WhatsApp supports typing indicators through thread.startTyping() or adapter.startTyping(threadId). Use it when the bot is about to respond and may take a few seconds:
The adapter sends Meta's read-plus-typing payload for the most recent inbound message ID in the thread history, so the indicator only works after the bot has received a message. Without that inbound context, startTyping() does nothing. The indicator is dismissed when the bot sends its reply, or after the WhatsApp platform timeout.
Read receipts
Mark the current inbound message as read before starting work:
You can also pass an inbound Message or its ID to thread.markAsRead(). WhatsApp marks that message and earlier messages in the conversation as read. It does not allow outgoing message IDs to be marked as read and recommends acknowledging inbound messages within 30 days.
User identity
WhatsApp messages include a business-scoped user ID (BSUID) in from_user_id and contacts[].user_id. Users with a username may omit the phone-based from and wa_id fields.
The adapter accepts either identifier. When both are available, it preserves an existing phone-based thread ID and stores the BSUID as an alias. Replies include both to and recipient, with the phone number taking precedence according to Meta's API. BSUID-only threads send through recipient.
Meta does not support BSUID recipients for one-tap, zero-tap, or copy-code authentication templates. Those templates require the user's phone number.
Use a persistent state adapter in production so identity aliases survive restarts. The adapter preserves the canonical thread when Meta rotates a BSUID by consuming user_changed_number and user_changed_user_id system messages plus the user_id_update webhook, which carries the previous and current BSUID. Subscribe your Meta app to the user_id_update webhook field so rotations reach the adapter. Current phone, BSUID, parent BSUID, and username fields remain available through message.raw.
API errors
A non-2xx Graph API response throws WhatsAppApiError, exported from @chat-adapter/whatsapp. It extends AdapterError, so existing instanceof AdapterError checks continue to work.
code: the sharedAdapterErrorcode when the failure maps onto one:RATE_LIMITED(HTTP 429, or Meta throttling codes such as130429and80007),AUTH_FAILED(HTTP 401, or Meta codes0and190),PERMISSION_DENIED(HTTP 403, or Meta codes3,10, and200to299),NOT_FOUND(HTTP 404). Otherwiseundefined.errorCode: Meta's numeric error code, such as130429providerMessageandtype: Meta'serror.messageanderror.type, when presentdetails: Meta'serror_data.details, when presentstatus: HTTP response statussubcodeandtraceId: Meta'serror_subcodeandfbtrace_id, when presentraw: the full parsed response body (see theWhatsAppGraphErrorBodytype), or the original text if it is not valid JSON
Meta recommends using error codes and details for error handling. Subcodes are optional and deprecated in the Cloud API. Missing or malformed provider fields stay undefined, and numeric codes that a proxy serializes as strings are accepted. The error message combines the operation, the HTTP status, and Meta's error.message, or a bounded excerpt of a non-JSON body.
This covers non-2xx responses from message sends, templates, reactions, read receipts, typing requests, media uploads, and media metadata requests. Transport failures and unparseable response bodies throw NetworkError, as do binary media download failures. A 2xx response that reports success: false for a typing request or read receipt throws a plain AdapterError. A successful API response can still be followed by an asynchronous delivery failure; those webhook errors are not thrown as WhatsAppApiError.
Thread IDs
Example: whatsapp:1234567890:15551234567.
phoneNumberId is the bot's phone number ID. The final segment is the adapter's canonical user identifier. It may contain a phone number, a BSUID such as US.13491208655302741918, or a previously observed identifier retained for thread continuity.
Replies, reactions, read receipts, typing indicators, and media uploads for a thread go out from that phoneNumberId. openDM still uses the configured number, because that call has no inbound thread yet.
Limitations
- Outgoing messages longer than 4096 characters are split into multiple messages automatically.
- Outside the 24-hour customer service window, only approved template messages can be sent.
Feature support
Messaging
| Feature | Supported |
|---|---|
| Post message | |
| Message replies | Outbound only |
| Edit message | |
| Delete message | |
| File uploads | Images, audio, docs |
| Streaming | Buffered |
| Scheduled messages |
Rich content
| Feature | Supported |
|---|---|
| Card format | Interactive messages |
| Buttons | Interactive replies |
| Link buttons | Single CTA URL |
| Select menus | |
| Tables | |
| Charts | |
| Fields | Formatted text |
| Images in cards | |
| Modals |
Conversations
| Feature | Supported |
|---|---|
| Slash commands | |
| Mentions | |
| Add reactions | |
| Remove reactions | |
| Typing indicator | |
| Mark as read | |
| Message edit events | |
| Message delete events | |
| DMs | |
| Ephemeral messages | |
| User lookup | |
| Parent subject | |
| Native client | |
| Custom API endpoint |
Message history
| Feature | Supported |
|---|---|
| Fetch messages | Persisted history |
| Fetch single message | |
| Fetch thread info | |
| Fetch channel messages | |
| List threads | |
| Fetch channel info | |
| Post channel message |