WhatsApp Cloud API in TypeScript: Typed Messages and Webhooks
Use the WhatsApp Cloud API from TypeScript: typed message payloads as discriminated unions, a typed send helper, webhook types and a signature check.

To use the WhatsApp Cloud API from TypeScript, describe each message you send as a member of a discriminated union keyed on type, send it with one typed fetch helper, and type the webhook payload so your handler can narrow on message.type. You don’t need an SDK: Meta’s Cloud API is HTTPS and JSON, and a few hundred characters of types catch most mistakes before Meta does.
This guide builds on our Node.js guide, which covers setup, .env settings and an Express webhook in plain JavaScript. Here you get what TypeScript adds: payload types for text, image, reply-button and template messages, a send helper with a typed error, webhook types that match Meta’s reference, and a signature check in a standard Request handler. It uses Graph API v27.0, the latest version in Meta’s changelog (released 4 November 2026).
Key takeaways
- Type outgoing messages as a union keyed on
type, so a text body can’t end up on an image message. - Use
{ id } | { link }withneveron the other key, and TypeScript rejects media that has both or neither. - Webhook types are only a promise: Meta can add message types, so keep a branch for types you don’t know.
- In webhooks,
timestampis a string andfromcan be missing for users with a username; usefrom_user_idas the fallback. - Check
X-Hub-Signature-256against the raw bytes of the body before you parse it.
What TypeScript adds to a Cloud API integration
Most WhatsApp API bugs are shape bugs: a field in the wrong object, an image with both an id and a link, a handler that reads text.body from a button tap, or a timestamp treated as a number. Meta reports them at run time, if at all. The types below move them to your editor, and a WhatsAppError class keeps Meta’s error code instead of a bare message.
Setup is the same as in the Node.js guide: a phone number ID, a permanent system-user token, your app secret and a verify token in environment variables. If you haven’t got those yet, start with the Cloud API setup guide and how to find your phone number ID. Install typescript and @types/node as dev dependencies and turn on "strict": true in tsconfig.json; the code below compiles under strict mode. The imports leave out file extensions, which suits Next.js and other bundlers; if you compile with "module": "NodeNext" instead, write them as ./whatsapp.js. Save the modules in a lib/ folder; only the webhook route goes under app/.
Type your outgoing messages as a discriminated union
Every Cloud API message shares four fields: messaging_product, recipient_type, to and type. The value of type decides which object comes next. That is exactly what TypeScript calls a discriminated union: members that share a literal property, which the compiler uses to narrow the type. Save these lines as whatsapp-types.ts:
| Line | whatsapp-types.ts |
|---|---|
| 1 | type Base = { messaging_product: "whatsapp"; recipient_type: "individual"; to: string }; |
| 2 | type Media = { id: string; link?: never } | { link: string; id?: never }; |
| 3 | export type TextMessage = Base & { type: "text"; text: { body: string; preview_url?: boolean } }; |
| 4 | export type ImageMessage = Base & { type: "image"; image: Media & { caption?: string } }; |
| 5 | export type ReplyButton = { type: "reply"; reply: { id: string; title: string } }; |
| 6 | export type ButtonsMessage = Base & { type: "interactive"; interactive: { type: "button"; body: { text: string }; action: { buttons: ReplyButton[] } } }; |
| 7 | export type TemplateParam = { type: "text"; text: string; parameter_name?: string }; |
| 8 | export type TemplateMessage = Base & { type: "template"; template: { name: string; language: { code: string }; components?: { type: "body"; parameters: TemplateParam[] }[] } }; |
| 9 | export type OutgoingMessage = TextMessage | ImageMessage | ButtonsMessage | TemplateMessage; |
| 10 | export const base = (to: string): Base => ({ messaging_product: "whatsapp", recipient_type: "individual", to }); |
- Line 2 is the useful trick. Meta’s image object takes either
id(uploaded media) orlink(a hosted URL). Marking the other keynevermakes TypeScript reject an object with both, and the union rejects one with neither. - Line 7 covers both template styles. Positional templates use the order of
{{1}},{{2}}; templates created with named parameters addparameter_name, such asfirst_name. - Add members as you need them, copying field names from Meta’s page for each type.
A typed send helper
One function sends every member of the union. It returns Meta’s response as a typed object and throws a WhatsAppError that carries Meta’s numeric code. Save it as whatsapp.ts:
| Line | whatsapp.ts |
|---|---|
| 1 | import type { OutgoingMessage } from "./whatsapp-types"; |
| 2 | const API_VERSION = "v27.0"; |
| 3 | export type SendResult = { messaging_product: "whatsapp"; contacts: { input: string; wa_id: string }[]; messages: { id: string; message_status?: string }[] }; |
| 4 | export class WhatsAppError extends Error { |
| 5 | constructor(message: string, public code?: number, public status?: number, public fbtraceId?: string) { super(message); } |
| 6 | } |
| 7 | export async function send(msg: OutgoingMessage): Promise<SendResult> { |
| 8 | const url = "https://graph.facebook.com/" + API_VERSION + "/" + process.env.PHONE_NUMBER_ID + "/messages"; |
| 9 | const res = await fetch(url, { method: "POST", headers: { Authorization: "Bearer " + process.env.WHATSAPP_TOKEN, "Content-Type": "application/json" }, body: JSON.stringify(msg), signal: AbortSignal.timeout(10_000) }); |
| 10 | const data = (await res.json().catch(() => ({}))) as Partial<SendResult> & { error?: { message?: string; code?: number; fbtrace_id?: string } }; |
| 11 | if (!res.ok) throw new WhatsAppError(data.error?.message ?? "HTTP " + res.status, data.error?.code, res.status, data.error?.fbtrace_id); |
| 12 | return data as SendResult; |
| 13 | } |
Now each call is checked as you type. A booking confirmation with two reply buttons looks like this:
| Line | send-buttons.ts |
|---|---|
| 1 | import { send } from "./whatsapp"; |
| 2 | import { base } from "./whatsapp-types"; |
| 3 | const r = await send({ ...base("919800000000"), type: "interactive", interactive: { type: "button", body: { text: "Hi Priya, confirm your table for 4 at 8 pm?" }, action: { buttons: [{ type: "reply", reply: { id: "confirm-1042", title: "Confirm" } }, { type: "reply", reply: { id: "change-1042", title: "Change time" } }] } } }); |
| 4 | console.log(r.messages[0].id); |
messages[0].idis thewamid…that later status webhooks refer to. Save it with your own record, here booking 1042.contacts[0].wa_idcan differ frominput, the number you sent.message_statusonly appears for template sends that Meta is pacing, which is why it’s optional inSendResult.- A successful response means Meta accepted the request, not that the message was delivered. Delivery comes later, by webhook.
Free-form messages like this one only work inside the 24-hour customer service window, which opens when the customer messages or calls you. Outside it, send an approved template; the JSON for media headers and buttons is in how to send a WhatsApp template message with the API, and it fits TemplateMessage once you add those component types.
Type the webhook payload
Meta’s webhook reference shows one envelope for everything: object, then entry[], each with changes[], each with a field and a value. Incoming messages arrive in value.messages and your delivery updates in value.statuses. Save webhook-types.ts:
| Line | webhook-types.ts |
|---|---|
| 1 | type InboundBase = { id: string; from?: string; from_user_id?: string; timestamp: string; context?: { from?: string; id?: string; forwarded?: boolean; frequently_forwarded?: boolean } }; |
| 2 | export type InboundText = InboundBase & { type: "text"; text: { body: string } }; |
| 3 | export type InboundImage = InboundBase & { type: "image"; image: { id: string; mime_type: string; sha256: string; caption?: string; url?: string } }; |
| 4 | export type InboundInteractive = InboundBase & { type: "interactive"; interactive: { type: "button_reply"; button_reply: { id: string; title: string } } | { type: "list_reply"; list_reply: { id: string; title: string; description?: string } } }; |
| 5 | export type InboundMessage = InboundText | InboundImage | InboundInteractive; |
| 6 | export type StatusError = { code: number; title: string; message?: string; error_data?: { details: string }; href?: string }; |
| 7 | export type Status = { id: string; status: "sent" | "delivered" | "read" | "played" | "failed"; timestamp: string; recipient_id?: string; recipient_user_id?: string; errors?: StatusError[] }; |
| 8 | export type ChangeValue = { messaging_product: "whatsapp"; metadata: { display_phone_number: string; phone_number_id: string }; contacts?: { profile?: { name: string }; wa_id?: string; user_id?: string }[]; messages?: InboundMessage[]; statuses?: Status[] }; |
| 9 | export type WebhookBody = { object: "whatsapp_business_account"; entry: { id: string; changes: { field: string; value: ChangeValue }[] }[] }; |
timestampis a string holding Unix seconds, in both messages and statuses. Convert it withnew Date(Number(m.timestamp) * 1000).fromis optional on purpose. Meta has added business-scoped user IDs (BSUIDs). If a user turns on the username feature, their phone number is generally left out of webhooks unless you’ve been in touch in the last 30 days or they’re in your contact book. Thenfrom_user_ididentifies them, and you can reply by putting it in arecipientfield in place ofto.contextis optional and its fields are too. On a button or list reply,context.idis the message that held the button, which is how you match a tap to the booking you asked about. A forwarded message has acontextwith onlyforwardedorfrequently_forwarded.image.urlis optional because Meta says it’s still rolling out. Theidis always there, and downloading WhatsApp media with the API shows what to do with it.
Narrow incoming messages without trusting the types too much
TypeScript types disappear when the code runs. The JSON that arrives is whatever Meta sends, and Meta adds message types over time; its own reference has an “unsupported” payload, with error 131051, for types the Cloud API can’t pass on. So don’t claim that messages only ever holds your three types. Check the type at run time first, then let the compiler narrow:
| Line | handle.ts |
|---|---|
| 1 | import type { InboundMessage, WebhookBody } from "./webhook-types"; |
| 2 | function isKnown(m: { type: string }): m is InboundMessage { return m.type === "text" || m.type === "image" || m.type === "interactive"; } |
| 3 | export function handleMessage(m: InboundMessage) { |
| 4 | const who = m.from ?? m.from_user_id ?? "unknown"; |
| 5 | switch (m.type) { |
| 6 | case "text": console.log(who, "wrote", m.text.body); break; |
| 7 | case "image": console.log(who, "sent image", m.image.id, m.image.caption ?? ""); break; |
| 8 | case "interactive": { |
| 9 | const it = m.interactive; |
| 10 | if (it.type === "button_reply") console.log(who, "tapped", it.button_reply.id); |
| 11 | else if (it.type === "list_reply") console.log(who, "picked", it.list_reply.id); |
| 12 | else console.log("skipped interactive type", (it as { type: string }).type); |
| 13 | break; |
| 14 | } |
| 15 | } |
| 16 | } |
| 17 | export function handleBody(body: WebhookBody) { |
| 18 | for (const entry of body.entry ?? []) for (const change of entry.changes ?? []) { |
| 19 | if (change.field !== "messages") continue; |
| 20 | for (const m of (change.value.messages ?? []) as { type: string }[]) { if (isKnown(m)) handleMessage(m); else console.log("skipped type", m.type); } |
| 21 | for (const s of change.value.statuses ?? []) if (s.status === "failed") console.error(s.id, s.errors?.[0]?.code, s.errors?.[0]?.error_data?.details); |
| 22 | } |
| 23 | } |
- The type guard (line 2) decides what reaches
handleMessage. - Inside the switch (lines 6 to 14),
m.textonly exists in the"text"branch. Try to read it elsewhere and the compiler stops you. - Interactive replies (lines 10 to 12) check
button_replyandlist_replyby name. Meta’s reference has other interactive types, such asproduct, so anything else is logged, not read as a list reply. - Unknown types (line 20) are logged and skipped, not thrown. A crash here would make your endpoint return an error, and Meta would keep retrying the same payload.
- Failed statuses (line 21) carry an
errorsarray withcode,titleanderror_data.details. Log the code and details; they say why the message didn’t go out.
Check the X-Hub-Signature-256 signature
Each POST from Meta carries an X-Hub-Signature-256 header: sha256= followed by an HMAC-SHA256 of the payload, made with your app secret. You must hash the bytes exactly as they arrived, so read the body as bytes, check it, and only then parse JSON. Put the check in its own module, lib/signature.ts, so any route can import it:
| Line | lib/signature.ts |
|---|---|
| 1 | import crypto from "node:crypto"; |
| 2 | export function verifySignature(raw: Buffer, header: string | null, secret: string): boolean { |
| 3 | if (!secret) throw new Error("App secret is not set"); |
| 4 | if (!header?.startsWith("sha256=")) return false; |
| 5 | const expected = Buffer.from(crypto.createHmac("sha256", secret).update(raw).digest("hex"), "hex"); |
| 6 | const given = Buffer.from(header.slice("sha256=".length), "hex"); |
| 7 | return given.length === expected.length && crypto.timingSafeEqual(given, expected); |
| 8 | } |
The route uses the standard Request and Response objects, so it works as a Next.js App Router route at app/api/whatsapp/route.ts, and in other frameworks built on the same objects. A Next.js route.ts may only export its HTTP handlers and route settings, which is why the check lives in lib/:
| Line | app/api/whatsapp/route.ts |
|---|---|
| 1 | import type { WebhookBody } from "../../../lib/webhook-types"; |
| 2 | import { handleBody } from "../../../lib/handle"; |
| 3 | import { verifySignature } from "../../../lib/signature"; |
| 4 | export async function GET(req: Request) { |
| 5 | const q = new URL(req.url).searchParams; |
| 6 | if (q.get("hub.mode") === "subscribe" && q.get("hub.verify_token") === process.env.VERIFY_TOKEN) return new Response(q.get("hub.challenge") ?? "", { status: 200 }); |
| 7 | return new Response("Forbidden", { status: 403 }); |
| 8 | } |
| 9 | export async function POST(req: Request) { |
| 10 | const secret = process.env.APP_SECRET; |
| 11 | if (!secret) return new Response("Server not configured", { status: 500 }); |
| 12 | const raw = Buffer.from(await req.arrayBuffer()); |
| 13 | if (!verifySignature(raw, req.headers.get("x-hub-signature-256"), secret)) return new Response("Bad signature", { status: 401 }); |
| 14 | let body: WebhookBody; |
| 15 | try { body = JSON.parse(raw.toString("utf8")) as WebhookBody; } catch { return new Response("Bad JSON", { status: 400 }); } |
| 16 | if (body.object === "whatsapp_business_account") handleBody(body); |
| 17 | return new Response("OK", { status: 200 }); |
| 18 | } |
- A missing secret is an error, not an empty key (route lines 10 and 11, signature line 3). An HMAC with an empty key is one anyone can compute, so the route refuses to run instead.
arrayBuffer(), notjson(), on route line 12. Parsing first and re-serialising later changes the bytes and breaks the check.- Hex to bytes (signature lines 5 and 6) gives two 32-byte buffers.
timingSafeEqualthrows if lengths differ, so the length check runs first, and a header with bad hex simply fails it. - The handshake (route lines 4 to 8) runs once, when you save the callback URL in your Meta app: return
hub.challengewith 200 if the verify token matches. - Return 200 quickly. Meta retries failed deliveries for up to 7 days and can batch up to 1,000 updates in one POST, so the same message can arrive twice. De-duplicate on the message
id, and push slow work such as AI replies or database writes to a queue.
Meta only calls a public HTTPS URL with a valid certificate; self-signed certificates aren’t supported. Payloads and retries are explained in WhatsApp Cloud API webhooks, and if nothing arrives, work through WhatsApp webhook not receiving messages.
Errors worth typing
Because send() throws a WhatsAppError, you can branch on the code with instanceof and keep the compiler happy:
| Line | Inside your sending code |
|---|---|
| 1 | import { send, WhatsAppError } from "./whatsapp"; |
| 2 | try { await send(msg); } |
| 3 | catch (err) { if (err instanceof WhatsAppError && err.code === 131047) { /* window closed: send a template */ } else throw err; } |
The codes you’ll meet first are the same as in any language: 190 (token expired or invalid), 131047 (more than 24 hours since the customer last messaged, so send a template), 132001 (template name or language not found or not approved) and 130429 (throughput limit, so queue and retry). In incoming webhooks, 131051 marks a message type the Cloud API doesn’t support: log it and move on.
A template can only be sent while its status is APPROVED; a paused or disabled one fails. The full list of codes is in WhatsApp API error codes. Keep fbtraceId in your logs, because Meta’s support asks for it.
TypeScript with Automate AI
If you’d rather not host Meta’s webhooks, Automate AI connects your number and gives your team a shared inbox, campaigns that send approved templates, and chatbots built without code. Your TypeScript code can still drive it through Automate AI’s REST API, with endpoints for contacts, messages, templates, campaigns and automations, and SDKs for PHP, Node.js, Python, Java and Ruby.
Automate AI’s own webhooks (events such as message.received, message.sent and message.status.update) are signed too, so a copy of lib/signature.ts needs only two changes: read the X-Webhook-Signature header, and drop the sha256= prefix check, because it holds the plain hex HMAC-SHA256 of the JSON body. The secret is shown once, when you create the webhook. The API, SDKs and webhooks are included on the AI + Automation Plan and Series 4; see the WhatsApp Business API page and pricing.
Frequently asked questions
Is there an official WhatsApp API TypeScript SDK?
Meta did publish a Cloud API SDK for Node.js written in TypeScript (WhatsApp-Nodejs-SDK on GitHub), but it was archived on 7 June 2023 and is now read-only. You don’t need one: the Cloud API is HTTPS and JSON, so a typed fetch helper and your own payload types, like the ones in this guide, cover sending and receiving.
How do I type WhatsApp webhook payloads in TypeScript?
Type the envelope (object, entry, changes, value), then make incoming messages a union keyed on type. Mark from optional, type timestamp as a string, and check type at run time before narrowing, because Meta can send types you haven’t modelled.
Why does my TypeScript webhook fail the signature check?
Usually because the body was parsed as JSON before hashing. Read it as bytes (await req.arrayBuffer()), compute the HMAC-SHA256 with your app secret, compare it with the value after sha256= in X-Hub-Signature-256, and only then parse.
Why is the sender missing from some webhooks?
Meta now includes business-scoped user IDs. When a user has turned on the username feature, the phone number is generally left out unless you’ve been in touch in the last 30 days or they’re in your contact book. Use from_user_id when from isn’t there.
Which Graph API version should I use?
The latest in Meta’s changelog. On 1 December 2026 that is v27.0, released on 4 November 2026. Keep it in one constant.
Can I use these types in a React or React Native app?
The types, yes. The send() helper, no: it needs the access token, which must stay on a server. See WhatsApp API in React and React Native apps.
Sources
- Meta: Send messages
- Meta: Interactive reply buttons messages
- Meta: Create a webhook endpoint
- Meta: Messages webhook reference
- Meta: Business-scoped user IDs
- Meta: Graph API changelog
- TypeScript handbook: Narrowing
- WhatsApp-Nodejs-SDK on GitHub (archived)
WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.


