WhatsApp official API in Next.js: Route Handlers
Integrate the official WhatsApp API into Next.js via CRPRO Hub: server-side fetch, a webhook Route Handler with request.text(), HMAC signatures and after().
In Next.js with the App Router, the CRPRO Hub webhook is a Route Handler and sending is a server-side fetch. The point to watch is that everything runs on the server: the API key cannot reach the browser, the body must be read as text before any parse, and slow work should happen after the response. The examples follow the route.js reference page (updated April 30, 2026) and the after function page (September 16, 2026); confirm on your installed version, because Next.js changes between versions. For plain Node.js without a framework, see the quickstart.
How to keep the key on the server
Short answer: put the key and secret in environment variables without the NEXT_PUBLIC_ prefix and use them only in Route Handlers, Server Actions or server code. Variables with that prefix are inlined into browser code.
Create the API key in the Hub dashboard with the messages:send and webhooks:write scopes (authentication) and store the value, which is shown only once. The webhook secret, whsec_..., is also shown once, in the POST /api/v1/webhooks response. Never call the Hub API from a client component: anyone opening the browser network panel would see the key.
# .env.local (nunca com o prefixo NEXT_PUBLIC_)
CRPRO_API_KEY=hub_pk_EXEMPLO_NAO_REAL
CRPRO_WEBHOOK_SECRET=whsec_EXEMPLO_NAO_REALHow to send a message with fetch
Short answer: a server function that POSTs to /api/v1/channels/{id}/messages with Authorization: Bearer, Idempotency-Key and JSON. The Hub answers 202 with status accepted.
- Use AbortSignal.timeout to cap the wait: with no limit, a slow Hub holds the function.
- The Idempotency-Key is mandatory and must be stable per logical message. The same key with the same body returns the original response; with a different body, the Hub answers 409 IDEMPOTENCY_KEY_REUSED.
- The recipient goes in to, with the country code and digits only.
- Limits: 60 messages per minute per channel and 120 requests per minute per organization and credential.
// lib/crprohub.ts
export async function enviarTexto(canal: string, para: string, texto: string, chave: string) {
const resposta = await fetch('https://crprohub.com/api/v1/channels/' + canal + '/messages', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + process.env.CRPRO_API_KEY,
'Content-Type': 'application/json',
'Idempotency-Key': chave,
},
body: JSON.stringify({ to: para, type: 'text', text: { body: texto } }),
signal: AbortSignal.timeout(10_000),
})
if (!resposta.ok) throw new Error('CRPRO Hub ' + resposta.status + ': ' + (await resposta.text()))
return (await resposta.json()).data.message_id as string // 202: aceita, nao entregue
}Call this function from a Route Handler or a Server Action. The 202 means the message was accepted and queued for Meta; the final state arrives through the message.status webhook. The quickstart explains the fields.
How to receive the webhook with a Route Handler
Short answer: create app/api/webhooks/crprohub/route.ts, export POST, read the body with request.text(), check the HMAC with timingSafeEqual and answer 200. The Next.js documentation shows exactly this pattern for webhooks and notes that, unlike Pages Router API Routes, no bodyParser configuration is needed.
Route Handlers use the Web Request and Response APIs. request.text() returns the body as a string, and that is what the signature requires: the Hub signs timestamp.delivery_id.body with HMAC SHA-256, so re-serializing already parsed JSON can change the result. Headers.get is case-insensitive: x-hub-timestamp, x-hub-delivery-id and x-hub-signature-256. Set runtime to nodejs to use node:crypto; the documentation lists nodejs as a runtime value.
// app/api/webhooks/crprohub/route.ts
import { createHmac, timingSafeEqual } from 'node:crypto'
import { after } from 'next/server'
import { enviarTexto } from '@/lib/crprohub'
export const runtime = 'nodejs'
function assinaturaValida(request: Request, corpo: string): boolean {
const h = request.headers
const assinado = h.get('x-hub-timestamp') + '.' + h.get('x-hub-delivery-id') + '.' + corpo
const esperado = createHmac('sha256', process.env.CRPRO_WEBHOOK_SECRET!).update(assinado).digest('hex')
const recebido = (h.get('x-hub-signature-256') ?? '').replace('sha256=', '')
return /^[0-9a-f]{64}$/.test(recebido) &&
timingSafeEqual(Buffer.from(recebido, 'hex'), Buffer.from(esperado, 'hex'))
}
export async function POST(request: Request) {
const corpo = await request.text() // texto cru, antes de qualquer JSON.parse
if (!assinaturaValida(request, corpo)) {
return new Response('assinatura invalida', { status: 401 })
}
const evento = JSON.parse(corpo)
after(async () => {
// roda depois da resposta; deduplique pelo evento.id antes de agir
if (evento.event !== 'message.received' || !evento.data.text) return
await enviarTexto(evento.channel_id, evento.data.from, 'Recebemos sua mensagem.', 'resp-' + evento.data.message_id)
})
return new Response(null, { status: 200 })
}curl -X POST https://crprohub.com/api/v1/webhooks \
-H "Authorization: Bearer hub_pk_EXEMPLO_NAO_REAL" \
-H "Content-Type: application/json" \
-d '{"name":"Recebimento","url":"https://your-domain.com/api/webhooks/crprohub","event_types":["message.received"]}'{
"id": "6f1f0f6a-3b2c-4d1e-9a8b-0c1d2e3f4a5b",
"event": "message.received",
"channel_id": "9f6a9c1e-2f3d-4a5b-8c7d-1e2f3a4b5c6d",
"occurred_at": "2026-08-21T12:00:00.000Z",
"data": {
"message_id": "wamid.EXEMPLO123",
"from": "5521999999999",
"type": "text",
"text": "Oi, ainda tem em estoque?"
}
}Work after the response with after()
Short answer: after() schedules a function to run after the response is sent. The Hub expects a 2xx within 10 seconds, so answer 200 and leave sending and slow calls to after.
According to the documentation, after can be used in Route Handlers, became stable in version 15.1.0, runs even if the response fails, and lives up to the platform's maximum duration, configurable with maxDuration where supported. It works on a Node.js server and in a Docker container; with static export, it does not. On serverless platforms it depends on a platform waitUntil, which the documentation describes as the mechanism that extends the invocation until promises settle. If you host elsewhere, confirm support before relying on it.
| Scenario | What to do |
|---|---|
| Invalid signature | Answer 401; the Hub counts a failure and retries |
| Repeated event | Answer 200 and ignore, deduplicating on the body id |
| Long work (AI model, database) | Do it inside after, with a stable Idempotency-Key |
| Consecutive failures | After 20, the Hub pauses the endpoint; reactivate with PATCH /api/v1/webhooks/{id} |
The Hub repeats a delivery up to nine times over about four days. Store the handled id in shared storage, not in memory, because serverless functions do not share state between invocations. To diagnose vanishing deliveries, see the webhooks page.
How to test the handler without starting the server
Short answer: since the Route Handler receives and returns standard Request and Response objects, you can call POST directly in a test, with a body signed by you. No network is needed.
// teste direto do handler, sem subir servidor
import { createHmac } from 'node:crypto'
import { POST } from '@/app/api/webhooks/crprohub/route'
const corpo = JSON.stringify({ id: 'e1', event: 'webhook.test', data: {} })
const ts = String(Math.floor(Date.now() / 1000))
const sig = createHmac('sha256', process.env.CRPRO_WEBHOOK_SECRET!)
.update(ts + '.d-1.' + corpo).digest('hex')
const resposta = await POST(new Request('http://localhost/api/webhooks/crprohub', {
method: 'POST',
headers: { 'x-hub-timestamp': ts, 'x-hub-delivery-id': 'd-1', 'x-hub-signature-256': 'sha256=' + sig },
body: corpo,
}))
console.log(resposta.status) // 200Also run the opposite case, with a swapped signature, and confirm the 401. For a real delivery, the POST /api/v1/webhooks/{id}/test endpoint sends an event to your domain, up to 10 times per hour per endpoint. The webhooks page lists the headers and the receiving rules.
Frequently asked questions
Do I need a body parser in the Route Handler?
No. The Next.js documentation notes that, unlike Pages Router API Routes, Route Handlers need no bodyParser. Read the body with request.text().
Why read the body as text and not with request.json()?
Because the signature covers the exact body bytes. Re-serializing the parsed JSON can change spacing and key order and invalidate the computation.
Can I use the edge runtime for the webhook?
The example uses node:crypto, which needs the nodejs runtime. An edge equivalent is not covered here, so test it before using it.
Does after() work on any host?
No. The documentation indicates support on a Node.js server and Docker, and a waitUntil dependency on serverless. It does not work with static export.
Fontes
Documentação oficial da Meta, conferida em 31 de outubro de 2026.