# Receive WhatsApp webhooks in a Next.js route handler

> Answer the WhatsApp webhook GET, check X-Hub-Signature-256 on the raw body and return 200 from a Next.js 16 route handler, then use after() for the work.

Published 2026-11-04. Z-API Omni team.

Create `app/api/whatsapp/route.ts` and export two functions. `GET` echoes `hub.challenge` when `hub.verify_token` matches your token. `POST` reads the raw body once, checks `X-Hub-Signature-256` with `node:crypto`, parses the JSON, returns 200 and hands the processing to `after()`. Export no `runtime` and no `dynamic` from the file. On Next.js 16.4 the defaults already do what a webhook needs, and Cache Components does not support either export.

## Project and secrets

The code targets Next.js 16.4 on Node.js 26. Next.js 16.4.5 was released on 2026-11-03 as the Active LTS line ([Next.js November 2026 security release, accessed 2026-11-04](https://nextjs.org/blog/november-2026-security-release)). Node.js 26 is the latest LTS, at v26.13.0 ([Node.js releases, accessed 2026-11-04](https://nodejs.org/en/about/previous-releases)).

```bash
npx create-next-app@latest whatsapp-webhook
cd whatsapp-webhook
```

Accept the recommended defaults. They include TypeScript, the App Router and Cache Components ([Next.js installation, accessed 2026-11-04](https://nextjs.org/docs/app/getting-started/installation)), which is why the runtime question below has one answer.

The route reads two environment variables. `WHATSAPP_APP_SECRET` is the app secret from your Meta app. `WHATSAPP_VERIFY_TOKEN` is any string you choose and type into the webhook settings of the App Dashboard. Next.js keeps both on the server: "By default, environment variables are only available on the server" ([Next.js self-hosting, accessed 2026-11-04](https://nextjs.org/docs/app/guides/self-hosting)). Only names prefixed with `NEXT_PUBLIC_` reach the browser, so never give either secret that prefix.

## The route file

```ts
// app/api/whatsapp/route.ts
import { createHmac, timingSafeEqual } from 'node:crypto'
import { after, type NextRequest } from 'next/server'

type WaMessage = {
  id: string
  from?: string
  from_user_id?: string
  timestamp: string
  type: string
  text?: { body: string }
}

type WaStatus = {
  id: string
  status: string
  recipient_id?: string
  recipient_user_id?: string
  errors?: unknown[]
}

type WaPayload = {
  object?: string
  entry?: Array<{
    changes?: Array<{
      field?: string
      value?: { messages?: WaMessage[]; statuses?: WaStatus[] }
    }>
  }>
}

const seen = new Set<string>() // demo dedupe in one process; use a unique index in your database

export function GET(request: NextRequest): Response {
  const verifyToken = process.env.WHATSAPP_VERIFY_TOKEN ?? ''
  const params = request.nextUrl.searchParams
  const challenge = params.get('hub.challenge')
  const valid =
    verifyToken !== '' &&
    params.get('hub.mode') === 'subscribe' &&
    params.get('hub.verify_token') === verifyToken &&
    challenge !== null
  if (!valid) return new Response(null, { status: 403 })
  return new Response(challenge, { status: 200, headers: { 'Content-Type': 'text/plain' } })
}

function validSignature(secret: string, rawBody: Buffer, header: string | null): boolean {
  if (header === null || !header.startsWith('sha256=')) return false
  const expected = createHmac('sha256', secret).update(rawBody).digest('hex')
  const received = Buffer.from(header.slice('sha256='.length), 'utf8')
  const computed = Buffer.from(expected, 'utf8')
  return received.length === computed.length && timingSafeEqual(received, computed)
}

function firstTime(key: string): boolean {
  if (seen.has(key)) return false
  seen.add(key)
  return true
}

function handle(payload: WaPayload): void {
  if (payload.object !== 'whatsapp_business_account') return
  for (const entry of payload.entry ?? []) {
    for (const change of entry.changes ?? []) {
      if (change.field !== 'messages') continue
      for (const msg of change.value?.messages ?? []) {
        if (!firstTime(`msg:${msg.id}`)) continue
        // Meta omits `from` when it cannot include the phone number; fall back to the BSUID
        const sender = msg.from ?? msg.from_user_id
        const text = msg.type === 'text' ? msg.text?.body : `[${msg.type}]`
        console.log(`message ${msg.id} from ${sender} at ${msg.timestamp}: ${text}`)
      }
      for (const st of change.value?.statuses ?? []) {
        if (!firstTime(`status:${st.id}:${st.status}`)) continue
        console.log(`status ${st.status} for ${st.id} to ${st.recipient_id ?? st.recipient_user_id}`)
        if (st.status === 'failed') console.log(JSON.stringify(st.errors))
      }
    }
  }
}

export async function POST(request: NextRequest): Promise<Response> {
  const appSecret = process.env.WHATSAPP_APP_SECRET ?? ''
  if (appSecret === '') return new Response('WHATSAPP_APP_SECRET is not set', { status: 500 })

  const rawBody = Buffer.from(await request.arrayBuffer()) // the exact bytes Meta signed
  if (!validSignature(appSecret, rawBody, request.headers.get('x-hub-signature-256'))) {
    return new Response(null, { status: 401 })
  }

  let payload: WaPayload
  try {
    payload = JSON.parse(rawBody.toString('utf8')) as WaPayload
  } catch {
    return new Response(null, { status: 400 })
  }

  // For events you cannot lose, await a write to your database or queue here, before the 200.
  after(() => handle(payload))
  return new Response(null, { status: 200 })
}
```

Next.js answers any method you don't export with "a `405 Method Not Allowed` response" ([Next.js route handlers, accessed 2026-11-04](https://nextjs.org/docs/app/getting-started/route-handlers)). The POST refuses to run with an empty app secret, because an HMAC keyed with an empty string would accept signatures anyone can compute.

## Why the file exports no runtime and no dynamic

The Next.js `runtime` page says "The Edge Runtime is deprecated. Remove the `runtime` export from your route files." With Cache Components on, it goes further: "remove the `runtime` export, including `runtime = 'nodejs'`" ([Next.js runtime config, accessed 2026-11-04](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/runtime)). Vercel adds that "Starting in Next.js 16.3, setting `runtime` to `edge` is no longer supported" ([Vercel Functions API reference, accessed 2026-11-04](https://vercel.com/docs/functions/functions-api-reference)). The default is Node.js, so the route gets `node:crypto` without asking.

Caching needs no setting either. "Route Handlers are not cached by default", and methods other than `GET` "are **not** cached" even next to a cached `GET` in the same file ([Next.js route handlers](https://nextjs.org/docs/app/getting-started/route-handlers)). Under Cache Components, a `GET` that reads request properties runs at request time, and this one reads the query string. Version 16.0.0 removed `dynamic` when Cache Components is enabled ([Next.js route segment config, accessed 2026-11-04](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config)). An old `export const dynamic = 'force-dynamic'` is unnecessary without Cache Components and unsupported with it.

## Read the body once, as bytes

Meta computes the header "using the post body payload and your app secret as the secret key" ([Meta create a webhook endpoint, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). The route hashes the bytes from `request.arrayBuffer()` and then parses those same bytes. A Fetch request body can be consumed once, so keep it in one variable for both steps.

Next.js's own webhook example reads the body with `request.text()` and notes that "you do not need to use `bodyParser`" in the App Router ([Next.js route.js](https://nextjs.org/docs/app/api-reference/file-conventions/route)). Hashing the UTF-8 of that string works for valid JSON too. Hashing a re-serialized object breaks the check, and [the signature verification guide](/academy/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) shows how accents and emoji cause it.

## Node crypto or Web Crypto

Both work on the Node.js runtime. `createHmac` plus `timingSafeEqual` is the shorter path, and it's what the route uses. Node's documentation warns that "An error is thrown if `a` and `b` have different byte lengths" ([Node.js crypto, accessed 2026-11-04](https://nodejs.org/api/crypto.html)). The length comparison before the call makes a short or over-long header return 401. Without it, a forged request throws inside the handler and the response becomes a 500.

Web Crypto is on `globalThis.crypto` in Node ([Node.js Web Crypto, v26 docs, accessed 2026-11-04](https://nodejs.org/api/webcrypto.html)). Choose `crypto.subtle.importKey` and `crypto.subtle.verify` if you want one function that also runs on Cloudflare. [The Workers version of this endpoint](/academy/articles/whatsapp-webhook-cloudflare-workers/) has that code with its hex decoding.

## After the 200 with after()

`after` "allows you to schedule work to be executed after a response (or prerender) is finished", and it is allowed in route handlers ([Next.js after, accessed 2026-11-04](https://nextjs.org/docs/app/api-reference/functions/after)). Stable since v15.1.0, it runs for "the platform's default or configured max duration of your route", even when the handler throws. With `next start`, Next.js finishes in-flight requests and pending `after()` callbacks before the process exits ([Next.js self-hosting](https://nextjs.org/docs/app/guides/self-hosting)).

Meta publishes no response deadline in seconds. On any status other than 200, Meta retries "with decreasing frequency until the request succeeds, for up to 7 days" ([Meta webhooks overview, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)). "These retries can result in duplicate webhook notifications." Returning 200 before your CRM call or AI step keeps their failures from turning into retries.

The same 200 is why `after()` is no place for work you can't lose. The callback runs in the same invocation. If the instance dies mid-callback, Meta has its 200 and never resends. "There are no APIs for fetching historical webhook data" either ([Meta create a webhook endpoint](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). Await a write to a table or queue before the 200, as the comment in `POST` marks. [Webhook queue architecture](/academy/articles/whatsapp-webhook-queue-architecture-workers/) covers that layout.

## Vercel time and body limits

On Vercel, a function invocation stops at its maximum duration with "a 504 error code (`FUNCTION_INVOCATION_TIMEOUT`)" ([Vercel Functions limits, accessed 2026-11-04](https://vercel.com/docs/functions/limitations)). With Fluid compute on Node.js, the limits are:

| Plan | Default duration | Maximum duration |
|---|---|---|
| Hobby | 300 s | 300 s |
| Pro and Enterprise | 300 s | 800 s (1,800 s in beta) |

The request body cap is 4.5 MB, above the 3 MB Meta sets for webhook payloads ([Meta webhooks overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)). To change the duration for this route, add one line to `route.ts`:

```ts
export const maxDuration = 60
```

Vercel's sample pairs `maxDuration` with `export const runtime = 'nodejs'`. Leave that line out, because Cache Components does not support the `runtime` export.

## Parse messages and statuses

Meta batches up to 1000 updates per POST, but "batching cannot be guaranteed", so one request may hold one event or many ([Meta create a webhook endpoint](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). The route walks every `entry[].changes[]` and both arrays in `value`, whose fields are in [the payload reference](/academy/articles/whatsapp-webhook-payload-reference-messages-statuses/).

The sender comes from `msg.from ?? msg.from_user_id`. Meta says `from` "Will be omitted if the phone number cannot be included", while `from_user_id` carries the user's business-scoped user ID (BSUID). For statuses, `recipient_id` "Will be set to the user's phone number, if you sent the message to the user's phone number" ([Meta business-scoped user IDs, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids)). `recipient_user_id` carries the BSUID. [BSUIDs and usernames](/academy/articles/whatsapp-usernames-business-scoped-user-ids/) covers what that means for a contact table.

Meta's retries produce duplicates. The route keys messages on `id` and statuses on `id` plus `status`, since one message moves through `sent`, `delivered` and `read`. The `Set` lives in one server process, so it forgets on restart and isn't shared between instances. Replace it with a unique index, as in [the idempotency pattern](/academy/articles/n8n-duplicate-webhooks-idempotency/).

## Test it locally

```bash
export WHATSAPP_APP_SECRET="APP_SECRET"
export WHATSAPP_VERIFY_TOKEN="VERIFY_TOKEN"
npm run dev
```

Open a second terminal and export the same two variables. Check the GET, then send Meta's sample text webhook, compacted to one line and signed with your app secret.

```bash
curl -i "http://localhost:3000/api/whatsapp?hub.mode=subscribe&hub.challenge=12345&hub.verify_token=$WHATSAPP_VERIFY_TOKEN"

cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$WHATSAPP_APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:3000/api/whatsapp \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary @sample.json
```

The GET returns `12345`. The first POST returns 200 and the dev server logs the message. A second identical POST returns 200 and logs nothing. Edit one character in `sample.json` without re-signing and the route returns 401. Meta needs a public HTTPS URL, which [testing with ngrok](/academy/articles/whatsapp-webhook-local-testing-ngrok/) sets up. Point the callback URL at `https://YOUR_DOMAIN/api/whatsapp` and subscribe to the `messages` field. The [Express version](/academy/articles/whatsapp-webhook-nodejs-express-receive-messages/) shows the same flow without a framework router.

*Z-API Omni team*
