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.

Illustration: a TypeScript editor showing message types next to a phone receiving a WhatsApp booking confirmation (sample data)

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 } with never on 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, timestamp is a string and from can be missing for users with a username; use from_user_id as the fallback.
  • Check X-Hub-Signature-256 against 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:

Linewhatsapp-types.ts
1type Base = { messaging_product: "whatsapp"; recipient_type: "individual"; to: string };
2type Media = { id: string; link?: never } | { link: string; id?: never };
3export type TextMessage = Base & { type: "text"; text: { body: string; preview_url?: boolean } };
4export type ImageMessage = Base & { type: "image"; image: Media & { caption?: string } };
5export type ReplyButton = { type: "reply"; reply: { id: string; title: string } };
6export type ButtonsMessage = Base & { type: "interactive"; interactive: { type: "button"; body: { text: string }; action: { buttons: ReplyButton[] } } };
7export type TemplateParam = { type: "text"; text: string; parameter_name?: string };
8export type TemplateMessage = Base & { type: "template"; template: { name: string; language: { code: string }; components?: { type: "body"; parameters: TemplateParam[] }[] } };
9export type OutgoingMessage = TextMessage | ImageMessage | ButtonsMessage | TemplateMessage;
10export 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) or link (a hosted URL). Marking the other key never makes 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 add parameter_name, such as first_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:

Linewhatsapp.ts
1import type { OutgoingMessage } from "./whatsapp-types";
2const API_VERSION = "v27.0";
3export type SendResult = { messaging_product: "whatsapp"; contacts: { input: string; wa_id: string }[]; messages: { id: string; message_status?: string }[] };
4export class WhatsAppError extends Error {
5constructor(message: string, public code?: number, public status?: number, public fbtraceId?: string) { super(message); }
6}
7export async function send(msg: OutgoingMessage): Promise<SendResult> {
8const url = "https://graph.facebook.com/" + API_VERSION + "/" + process.env.PHONE_NUMBER_ID + "/messages";
9const 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) });
10const data = (await res.json().catch(() => ({}))) as Partial<SendResult> & { error?: { message?: string; code?: number; fbtrace_id?: string } };
11if (!res.ok) throw new WhatsAppError(data.error?.message ?? "HTTP " + res.status, data.error?.code, res.status, data.error?.fbtrace_id);
12return data as SendResult;
13}

Now each call is checked as you type. A booking confirmation with two reply buttons looks like this:

Linesend-buttons.ts
1import { send } from "./whatsapp";
2import { base } from "./whatsapp-types";
3const 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" } }] } } });
4console.log(r.messages[0].id);
  • messages[0].id is the wamid… that later status webhooks refer to. Save it with your own record, here booking 1042.
  • contacts[0].wa_id can differ from input, the number you sent.
  • message_status only appears for template sends that Meta is pacing, which is why it’s optional in SendResult.
  • 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:

Linewebhook-types.ts
1type InboundBase = { id: string; from?: string; from_user_id?: string; timestamp: string; context?: { from?: string; id?: string; forwarded?: boolean; frequently_forwarded?: boolean } };
2export type InboundText = InboundBase & { type: "text"; text: { body: string } };
3export type InboundImage = InboundBase & { type: "image"; image: { id: string; mime_type: string; sha256: string; caption?: string; url?: string } };
4export 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 } } };
5export type InboundMessage = InboundText | InboundImage | InboundInteractive;
6export type StatusError = { code: number; title: string; message?: string; error_data?: { details: string }; href?: string };
7export type Status = { id: string; status: "sent" | "delivered" | "read" | "played" | "failed"; timestamp: string; recipient_id?: string; recipient_user_id?: string; errors?: StatusError[] };
8export 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[] };
9export type WebhookBody = { object: "whatsapp_business_account"; entry: { id: string; changes: { field: string; value: ChangeValue }[] }[] };
  • timestamp is a string holding Unix seconds, in both messages and statuses. Convert it with new Date(Number(m.timestamp) * 1000).
  • from is 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. Then from_user_id identifies them, and you can reply by putting it in a recipient field in place of to.
  • context is optional and its fields are too. On a button or list reply, context.id is the message that held the button, which is how you match a tap to the booking you asked about. A forwarded message has a context with only forwarded or frequently_forwarded.
  • image.url is optional because Meta says it’s still rolling out. The id is 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:

Linehandle.ts
1import type { InboundMessage, WebhookBody } from "./webhook-types";
2function isKnown(m: { type: string }): m is InboundMessage { return m.type === "text" || m.type === "image" || m.type === "interactive"; }
3export function handleMessage(m: InboundMessage) {
4const who = m.from ?? m.from_user_id ?? "unknown";
5switch (m.type) {
6case "text": console.log(who, "wrote", m.text.body); break;
7case "image": console.log(who, "sent image", m.image.id, m.image.caption ?? ""); break;
8case "interactive": {
9const it = m.interactive;
10if (it.type === "button_reply") console.log(who, "tapped", it.button_reply.id);
11else if (it.type === "list_reply") console.log(who, "picked", it.list_reply.id);
12else console.log("skipped interactive type", (it as { type: string }).type);
13break;
14}
15}
16}
17export function handleBody(body: WebhookBody) {
18for (const entry of body.entry ?? []) for (const change of entry.changes ?? []) {
19if (change.field !== "messages") continue;
20for (const m of (change.value.messages ?? []) as { type: string }[]) { if (isKnown(m)) handleMessage(m); else console.log("skipped type", m.type); }
21for (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}
  1. The type guard (line 2) decides what reaches handleMessage.
  2. Inside the switch (lines 6 to 14), m.text only exists in the "text" branch. Try to read it elsewhere and the compiler stops you.
  3. Interactive replies (lines 10 to 12) check button_reply and list_reply by name. Meta’s reference has other interactive types, such as product, so anything else is logged, not read as a list reply.
  4. 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.
  5. Failed statuses (line 21) carry an errors array with code, title and error_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:

Linelib/signature.ts
1import crypto from "node:crypto";
2export function verifySignature(raw: Buffer, header: string | null, secret: string): boolean {
3if (!secret) throw new Error("App secret is not set");
4if (!header?.startsWith("sha256=")) return false;
5const expected = Buffer.from(crypto.createHmac("sha256", secret).update(raw).digest("hex"), "hex");
6const given = Buffer.from(header.slice("sha256=".length), "hex");
7return 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/:

Lineapp/api/whatsapp/route.ts
1import type { WebhookBody } from "../../../lib/webhook-types";
2import { handleBody } from "../../../lib/handle";
3import { verifySignature } from "../../../lib/signature";
4export async function GET(req: Request) {
5const q = new URL(req.url).searchParams;
6if (q.get("hub.mode") === "subscribe" && q.get("hub.verify_token") === process.env.VERIFY_TOKEN) return new Response(q.get("hub.challenge") ?? "", { status: 200 });
7return new Response("Forbidden", { status: 403 });
8}
9export async function POST(req: Request) {
10const secret = process.env.APP_SECRET;
11if (!secret) return new Response("Server not configured", { status: 500 });
12const raw = Buffer.from(await req.arrayBuffer());
13if (!verifySignature(raw, req.headers.get("x-hub-signature-256"), secret)) return new Response("Bad signature", { status: 401 });
14let body: WebhookBody;
15try { body = JSON.parse(raw.toString("utf8")) as WebhookBody; } catch { return new Response("Bad JSON", { status: 400 }); }
16if (body.object === "whatsapp_business_account") handleBody(body);
17return 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(), not json(), 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. timingSafeEqual throws 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.challenge with 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:

LineInside your sending code
1import { send, WhatsAppError } from "./whatsapp";
2try { await send(msg); }
3catch (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

  1. Meta: Send messages
  2. Meta: Interactive reply buttons messages
  3. Meta: Create a webhook endpoint
  4. Meta: Messages webhook reference
  5. Meta: Business-scoped user IDs
  6. Meta: Graph API changelog
  7. TypeScript handbook: Narrowing
  8. 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.