package
WhatsApp adapter for Chat SDK — Business Cloud API webhooks, interactive messages, and templates
npm install @chat-adapter/whatsappGitHub-flavored package documentation.
Across all versions, last 30 days.
1,610,498 in 30 days
Runtime metadata.
Tagged topics.
vercel-release-bot
infra+release@vercel.com
WhatsApp Business Cloud adapter for Chat SDK, using the WhatsApp Business Cloud API.
Documentation: chat-sdk.dev/adapters/official/whatsapp · Guides: vercel.com/kb/chat-sdk
pnpm add @chat-adapter/whatsappTo scaffold a new WhatsApp bot with this adapter preselected:
npx create-chat-sdk@latest my-bot --adapter whatsapp memoryVisit the adapters directory to see other available official and vendor-official adapters.
import { Chat } from "chat";
import { createWhatsAppAdapter } from "@chat-adapter/whatsapp";
const bot = new Chat({
userName: "mybot",
adapters: {
whatsapp: createWhatsAppAdapter(),
},
});
bot.onNewMention(async (thread, message) => {
await thread.post("Hello from WhatsApp!");
});When using createWhatsAppAdapter() without arguments, credentials are auto-detected from environment variables.
https://your-domain.com/api/webhooks/whatsappWHATSAPP_VERIFY_TOKEN)messages webhook fieldFrom your Meta app dashboard, copy:
WHATSAPP_APP_SECRETWHATSAPP_ACCESS_TOKENWHATSAPP_PHONE_NUMBER_IDFor production, generate a permanent System User Token instead of the temporary access token.
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.
All options are auto-detected from environment variables when not provided. You can call createWhatsAppAdapter() with no arguments if the env vars are set.
| Option | Required | Description |
|---|---|---|
accessToken | No* | Meta access token. Auto-detected from WHATSAPP_ACCESS_TOKEN |
appSecret | No* | App secret for webhook verification. Auto-detected from WHATSAPP_APP_SECRET |
phoneNumberId | No* | Bot's phone number ID. Auto-detected from WHATSAPP_PHONE_NUMBER_ID |
verifyToken | No* | Webhook verification secret. Auto-detected from WHATSAPP_VERIFY_TOKEN |
apiVersion | No | Graph API version (defaults to v25.0) |
userName | No | Bot username for self-message detection. Auto-detected from WHATSAPP_BOT_USERNAME (defaults to whatsapp-bot) |
apiUrl | No | Override the Meta Graph API base URL. Auto-detected from WHATSAPP_API_URL |
logger | No | Logger instance (defaults to ConsoleLogger("info")) |
*Required at runtime — either via config or environment variable.
WHATSAPP_ACCESS_TOKEN=... # Meta access token (permanent or system user token)
WHATSAPP_APP_SECRET=... # App secret for X-Hub-Signature-256 verification
WHATSAPP_PHONE_NUMBER_ID=... # Bot's phone number ID from Meta dashboard
WHATSAPP_VERIFY_TOKEN=... # User-defined secret for webhook verification
WHATSAPP_BOT_USERNAME=... # Optional, defaults to "whatsapp-bot"
WHATSAPP_API_URL=... # Optional, override the Meta Graph API base URLWhatsApp uses two webhook mechanisms:
hub.verify_token challenge that must match your WHATSAPP_VERIFY_TOKEN.X-Hub-Signature-256.// Next.js App Router example
import { bot } from "@/lib/bot";
export async function GET(request: Request) {
return bot.webhooks.whatsapp(request);
}
export async function POST(request: Request) {
return bot.webhooks.whatsapp(request);
}| Feature | Supported |
|---|---|
| Post message | Yes |
| Edit message | No (WhatsApp limitation) |
| Delete message | No (WhatsApp limitation) |
| Streaming | Buffered (accumulates then sends) |
| Mark as read | Yes |
| Auto-chunking | Yes (splits at 4096 chars) |
| Template messages | Yes (via sendTemplate) |
| Feature | Supported |
|---|---|
| Interactive buttons | Yes (up to 3) |
| Link buttons | Partial (single link button becomes a native CTA URL message) |
| Button title limit | 20 characters (longer titles are truncated) |
| List messages | No (list replies are received) |
| Text fallback | Yes (for cards without reply buttons or a single link button) |
| Feature | Supported |
|---|---|
| Reactions | Yes (add and remove) |
| Typing indicator | Yes (requires a recent inbound message, marks it as read, and displays for up to 25 seconds) |
| DMs | Yes |
| Open DM | Yes |
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 uses the most recent inbound message ID from thread history, so startTyping() only works after the bot has received a message.
await thread.startTyping();
await thread.post({
markdown: "Thanks, I am checking that now.",
});WhatsApp-specific behavior:
startTyping() no-ops.Use thread.markAsRead() in a message handler to acknowledge the current inbound message:
await thread.markAsRead();You can also pass an inbound Message or its ID. 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.
| Type | Supported |
|---|---|
| Text | Yes |
| Images | Yes (with captions) |
| Documents | Yes (with captions) |
| Audio / Voice | Yes |
| Video | Yes (with captions) |
| Stickers | Yes |
| Locations | Yes (converted to map URL) |
| Interactive replies | Yes (button and list) |
| Reactions | Yes |
| Feature | Supported |
|---|---|
| Fetch messages | Persisted history only (the Cloud API has no history endpoint, so Chat SDK keeps thread history in the state adapter) |
| Fetch thread info | Yes |
Card elements are automatically converted to WhatsApp interactive messages:
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, since WhatsApp reply buttons cannot open URLs.
A card whose only interactive element is a single link button is sent as a native CTA URL message with a tappable link button. The card is promoted only when all of these hold:
http:// or https:// and the label is non-empty. Other schemes (mailto:, tel:, relative paths) keep the text fallback because the Cloud API rejects them.Label: url line for each link button.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.
Outside the 24-hour customer service window, WhatsApp only accepts pre-approved template messages. Use sendTemplate to start business-initiated conversations:
const threadId = await adapter.openDM("15551234567");
await adapter.sendTemplate(threadId, {
name: "appointment_reminder",
language: "en",
components: [
{
type: "body",
parameters: [{ type: "text", text: "Tomorrow at 2pm" }],
},
],
});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.
A non-2xx Graph API response throws WhatsAppApiError, exported from @chat-adapter/whatsapp. It extends AdapterError, so existing instanceof AdapterError checks continue to work.
import { WhatsAppApiError } from "@chat-adapter/whatsapp";
try {
await thread.post("Hello");
} catch (error) {
if (error instanceof WhatsAppApiError) {
console.error(error.code, error.errorCode, error.details, error.status);
}
throw error;
}code: the shared AdapterError code when the failure maps onto one: RATE_LIMITED (HTTP 429, or Meta throttling codes such as 130429 and 80007), AUTH_FAILED (HTTP 401, or Meta codes 0 and 190), PERMISSION_DENIED (HTTP 403, or Meta codes 3, 10, and 200 to 299), NOT_FOUND (HTTP 404). Otherwise undefined.errorCode: Meta's numeric error code, such as 130429providerMessage and type: Meta's error.message and error.type, when presentdetails: Meta's error_data.details, when presentstatus: HTTP response statussubcode and traceId: Meta's error_subcode and fbtrace_id, when presentraw: the full parsed response body (see the WhatsAppGraphErrorBody type), or the original text if it is not valid JSONMeta 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.
WhatsApp messages include a business-scoped user ID 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.
whatsapp:{phoneNumberId}:{userWaId}Example: whatsapp:1234567890:15551234567
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.
WHATSAPP_VERIFY_TOKEN matches the value you entered in the Meta dashboardhub.challenge value for GET requestsmessages webhook field in Meta app settingsWHATSAPP_APP_SECRET is correct. A payload with an invalid signature gets a 401 response and isn't processedWHATSAPP_APP_SECRET matches the value under App Settings > BasicX-Hub-Signature-256 headerIf you use an AI coding agent such as OpenAI Codex, Claude Code, or Cursor, install the Chat SDK skill so it knows the SDK APIs, adapter patterns, and project conventions before writing code.
npx skills add vercel/chatThe skill references bundled documentation in node_modules/chat/docs, plus adapter guides and starter templates in the published package.
You can also install the Vercel Plugin for a broader agent toolkit — it includes the Chat SDK skill alongside specialist agents, agent slash commands, and more:
npx plugins add vercel/vercel-pluginThe plugin is optional; the skill alone is enough to build with Chat SDK.
For agent-readable documentation, see chat-sdk.dev/llms.txt (page index) or chat-sdk.dev/llms-full.txt (full text).
MIT
Estimated unpacked size across 24 packages.
2.4 MB
Includes dependencies.