Updated on November 10, 2026
In Next.js with the App Router, an integration with the official WhatsApp Business API fits in two route handlers: a route.ts with GET and POST for the webhook (the GET returns the hub.challenge, the POST validates x-hub-signature-256 over the raw body) and a server-only function that sends messages with fetch. The token lives in an environment variable without the NEXT_PUBLIC_ prefix, and event processing runs after the response with after().
Below is the full TypeScript code, with the details that break most often in production: reading the body as bytes before validating, keeping your auth middleware from blocking Meta, and not losing work on serverless platforms.
Project structure
app/
api/
whatsapp/
webhook/route.ts # GET (verification) + POST (events)
send/route.ts # internal endpoint for sending messages
lib/
whatsapp.ts # send client (server only)
process-event.ts # webhook business logic
Environment variables (.env.local in development, your hosting dashboard in production):
WA_SEND_URL="https://graph.facebook.com/v27.0/YOUR_PHONE_NUMBER_ID/messages"
WA_TOKEN="your_token"
WA_VERIFY_TOKEN="a-string-you-made-up"
META_APP_SECRET="app_secret_from_the_meta_dashboard"
INTERNAL_API_KEY="key-for-calling-the-send-endpoint"
None of them has NEXT_PUBLIC_. According to the Next.js environment variables guide, variables with that prefix are inlined into the browser bundle, and a WhatsApp token in the browser is a leaked token.
The send client
Sending is a POST to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with Authorization: Bearer and JSON, according to Meta’s send messages documentation:
// lib/whatsapp.ts
import "server-only";
type SendResult = { wamid: string };
async function send(payload: Record<string, unknown>): Promise<SendResult> {
const res = await fetch(process.env.WA_SEND_URL!, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.WA_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ messaging_product: "whatsapp", ...payload }),
cache: "no-store",
signal: AbortSignal.timeout(15_000),
});
const data = await res.json();
if (!res.ok) {
throw new Error(`WhatsApp ${res.status}: ${data?.error?.message ?? "error"}`);
}
return { wamid: data.messages[0].id };
}
export function sendText(to: string, body: string) {
return send({ to, type: "text", text: { body } });
}
export function sendTemplate(to: string, name: string, params: string[], lang = "en_US") {
return send({
to,
type: "template",
template: {
name,
language: { code: lang },
components: [
{ type: "body", parameters: params.map((text) => ({ type: "text", text })) },
],
},
});
}
import "server-only" makes the build fail if a Client Component imports this file by mistake, as described in the Server and Client Components docs. It’s a cheap safety net for the token.
Outside the 24-hour window, only approved templates are accepted. Header fields with media and buttons are covered in how to send a template through the API, and send examples in other languages in send a WhatsApp message through the API.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
Internal send endpoint
If your dashboard needs to send messages, expose a protected route handler. Never accept free-form to and body from any visitor: that turns your number into a spam channel and tanks its quality.
// app/api/whatsapp/send/route.ts
import { NextRequest } from "next/server";
import { sendTemplate } from "@/lib/whatsapp";
export async function POST(req: NextRequest) {
if (req.headers.get("x-internal-key") !== process.env.INTERNAL_API_KEY) {
return new Response("unauthorized", { status: 401 });
}
const { to, orderId } = await req.json();
const { wamid } = await sendTemplate(to, "order_confirmed", [orderId]);
return Response.json({ wamid });
}
In an app with login, replace the fixed key with a check of the user session and limit which templates each role can send.
The webhook: GET verification
Meta’s webhook endpoint documentation says verification arrives as a GET with hub.mode=subscribe, hub.verify_token and hub.challenge. If the token matches, respond 200 with the bare challenge in the body. Any other response leaves the endpoint unverified.
// app/api/whatsapp/webhook/route.ts (part 1)
import { NextRequest, after } from "next/server";
import crypto from "node:crypto";
import { processEvent } from "@/lib/process-event";
export const runtime = "nodejs";
export async function GET(req: NextRequest) {
const p = req.nextUrl.searchParams;
if (p.get("hub.mode") === "subscribe" && p.get("hub.verify_token") === process.env.WA_VERIFY_TOKEN) {
return new Response(p.get("hub.challenge") ?? "", {
status: 200,
headers: { "Content-Type": "text/plain" },
});
}
return new Response("forbidden", { status: 403 });
}
Since Next.js 15, GET handlers are no longer static by default, according to the version history in the route.js reference. Since this GET reads searchParams, it’s dynamic anyway. If you’re on an older version, make sure the response wasn’t cached at build time.
The webhook: POST with x-hub-signature-256
Every event comes with the X-Hub-Signature-256: sha256=<hash> header, an HMAC-SHA256 of the body using the app secret. The golden rule: compute the hash over the bytes you received, before any JSON.parse.
// app/api/whatsapp/webhook/route.ts (part 2)
function isValidSignature(raw: Buffer, header: string | null): boolean {
if (!header) return false;
const expected =
"sha256=" + crypto.createHmac("sha256", process.env.META_APP_SECRET!).update(raw).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(header);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
export async function POST(req: NextRequest) {
const raw = Buffer.from(await req.arrayBuffer());
if (!isValidSignature(raw, req.headers.get("x-hub-signature-256"))) {
return new Response("invalid signature", { status: 401 });
}
const payload = JSON.parse(raw.toString("utf8"));
after(async () => {
try {
await processEvent(payload);
} catch (err) {
console.error("webhook processing failed", err);
}
});
return new Response("ok", { status: 200 });
}
Points worth noting:
- No body parser. Unlike Pages Router API Routes, route handlers don’t need any
bodyParserconfiguration for webhooks; the reference itself shows an example withrequest.text(). Here we usearrayBuffer()to get the exact bytes. timingSafeEqualwith equal lengths. The function throws if the buffers have different lengths, which is why thelengthcheck comes first.runtime = "nodejs". The code usesnode:crypto. On the Edge runtime you’d have to rewrite the HMAC with the Web Crypto API.
The signature walkthrough in plain Node.js, Python and PHP is in how to validate the WhatsApp webhook signature.
Processing after the response with after()
According to the after reference, the function schedules work to run after the response is finished, works in route handlers and became stable in Next.js 15.1. It respects the route’s configured maximum duration (maxDuration, if the platform supports it). It’s supported on a Node.js server and in Docker; on serverless platforms it depends on a waitUntil mechanism, which Vercel provides.
That solves the common case: return 200 to Meta quickly and only then call AI, a CRM or the database. But it isn’t a queue. If the function dies midway, the event is lost, because Meta already got 200 and won’t redeliver. For work that can’t be lost, write the raw payload to a table before responding and process it from there.
And make processEvent ready for duplicates. The webhooks overview warns that deliveries without a 200 are retried for up to 7 days and may arrive duplicated:
// lib/process-event.ts
import "server-only";
import { sendText } from "./whatsapp";
import { db } from "./db"; // your database client
export async function processEvent(payload: any) {
for (const entry of payload.entry ?? []) {
for (const change of entry.changes ?? []) {
const value = change.value ?? {};
for (const msg of value.messages ?? []) {
const inserted = await db.inboundInsertIgnore({ wamid: msg.id, from: msg.from, type: msg.type });
if (!inserted) continue; // already processed
if (msg.type === "text") {
await sendText(msg.from, "We got your message. We'll reply shortly.");
}
}
for (const st of value.statuses ?? []) {
await db.updateOutboundStatus(st.id, st.status, st.timestamp);
}
}
}
}
inboundInsertIgnore stands for an INSERT ... ON CONFLICT DO NOTHING (or your ORM’s equivalent) with a unique index on wamid. The format of each message type is in webhook payload examples.
Auth middleware and other blockers
If your app uses middleware (proxy in newer versions) to require login, the webhook route will answer with a redirect to the login page and Meta will never see a 200. Remove /api/whatsapp/webhook from the matcher. The same goes for password protection on previews and firewalls that block bots.
Other frequent causes of a silent webhook are in the webhook not working checklist.
Where to host
| Hosting | after() | Note |
|---|---|---|
Node.js server (next start) | Supported | Long-running process; the simplest option for webhooks |
| Docker | Supported | Same as Node.js |
| Serverless adapters (e.g. Vercel) | Platform-specific | Requires a waitUntil primitive, which Vercel provides; respect maxDuration |
| Static export | Not supported | No server, no webhook |
Source: support table in the after reference. Lambda and Cloudflare Workers comparisons are in serverless WhatsApp webhook. Meta requires HTTPS with a valid certificate, and preview domains with protection enabled won’t work as a callback.
How to do this with Vectalk
Vectalk is a proxy for the official Cloud API: the code above stays the same, only the variables change. For sending, use WA_SEND_URL="https://apis.vectalk.com.br/api/messages" with Authorization: Bearer and the same JSON body, as in the Vectalk quickstart. With an instance token, the phone_number_id is resolved from the token; with an organization token (the global token from Settings (Configurações) → API Tokens), include phone_number_id in the body, according to the authentication page.
For the webhook, register the route handler URL with POST https://apis.vectalk.com.br/api/webhooks (instance_id, url, name). The webhooks documentation says the Hub forwards the same payload Meta sends and expects 200 within 20 seconds, so processEvent doesn’t change. Since the documentation doesn’t describe a signature header on the forwarded request, replace the x-hub-signature-256 check with a secret in the registered URL (for example, ?key=...) and confirm through the contact page. To get started, create your account.
Running a separate backend in Rails or Python? See WhatsApp API with Ruby on Rails and webhook with FastAPI. The same flow in Express is in WhatsApp bot with Node.js. For the platform overview, start with the official WhatsApp API guide.
Frequently asked questions
Can I call the WhatsApp API directly from a Client Component?
No. The token would have to go to the browser, and anyone could send messages on behalf of your number. Make the call in a route handler, a Server Action or other server-only code.
Why does the signature fail if I use await req.json()?
Because you lose the original bytes. Read with arrayBuffer() (or text()), validate, and only then JSON.parse.
Server Action or route handler for sending messages?
For buttons in your own dashboard, a Server Action works well. For calls from other systems (ERP, n8n, cron), an authenticated route handler is simpler to integrate. Both run on the server.
Does the webhook work on the Edge runtime?
It does, but the example uses node:crypto. On Edge, rewrite the HMAC with crypto.subtle and compare the hashes carefully. In most cases, the Node.js runtime is the shortest path.
What happens if processEvent throws inside after()?
Meta already received 200 and won’t redeliver. Log the error and, for critical events, store the payload before responding so you can reprocess it.
Official sources consulted on November 10, 2026: Meta: send messages, Meta: create a webhook endpoint, Meta: webhooks overview, Next.js: route.js, Next.js: after, Next.js: environment variables, Next.js: Server and Client Components (server-only), Vectalk: quickstart, Vectalk: authentication, Vectalk: webhooks.
Put your business on the official WhatsApp
Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.
