Skip to Content

Receive webhooks

Verify the raw request, decode a typed event, and process each event exactly once. Examples for Next.js, Hono, Express, Fastify, NestJS, and Node.js.

A receiver reads the raw body, verifies it with parseWebhook(), processes the event once, and responds. good-webhooks/verify loads no database or worker code, so it fits in any Node.js service.

Add a webhook route

Each handler is complete. Put your event map in events.ts and the endpoint's signing secret in WEBHOOK_SECRET.

app/webhooks/route.ts
import { parseWebhook, WebhookError } from 'good-webhooks/verify'
import { events } from '@/lib/events'

export async function POST(request: Request) {
  // Reject oversized bodies before buffering. Your platform's body limit also applies.
  if (Number(request.headers.get('content-length')) > 512 * 1024) {
    return new Response('Webhook body is too large', { status: 413 })
  }
  try {
    const event = await parseWebhook({
      body: new Uint8Array(await request.arrayBuffer()),
      headers: request.headers,
      secret: process.env.WEBHOOK_SECRET!,
      events,
    })
    console.log(event.type, event.id) // Process once: see below.
    return new Response(null, { status: 204 })
  } catch (error) {
    if (error instanceof WebhookError && isRejection(error)) {
      return new Response('Invalid webhook', { status: 400 })
    }
    throw error // 500: the sender retries.
  }
}

const isRejection = (error: WebhookError) =>
  ['SIGNATURE_INVALID', 'SIGNATURE_EXPIRED', 'PAYLOAD_INVALID'].includes(error.code)

During a secret rotation, pass both secrets: secret: [newSecret, oldSecret].

Share the event map

Use the sender's map, from a module that imports no server configuration or secrets:

events.ts
import { z } from 'zod'

export const events = {
  'invoice.paid': z.object({ invoiceId: z.string(), amount: z.number().int().nonnegative() }),
}

event is a union over the map. Checking event.type narrows event.data:

if (event.type === 'invoice.paid') {
  event.data.amount // number
}

An event type that is not in your map is rejected as PAYLOAD_INVALID. There is no "ignore unknown events" mode. The one exception is the test event, which every receiver accepts.

Respond with the right status

The sender retries every response except 2xx and 410, so a 400 doesn't stop retries. It tells the endpoint's owner that the request was at fault, not your code, so return 400 only when the request itself is bad:

Error codeRespond
SIGNATURE_INVALID400
SIGNATURE_EXPIRED400
PAYLOAD_INVALID400
INVALID_CONFIG500
INVALID_INPUT500
Anything else500
  • SIGNATURE_INVALID: missing, malformed, or wrong signature headers.
  • SIGNATURE_EXPIRED: the timestamp is outside the tolerance (five minutes by default).
  • PAYLOAD_INVALID: bad encoding, JSON, or envelope, an unknown event, or a schema error.
  • INVALID_CONFIG: your event map is wrong.
  • INVALID_INPUT: the body is not a string or bytes, or the secret or options are bad.
  • Anything else: your database, your business logic, or a thrown validator.

Error messages carry no payload values. Unexpected errors keep a cause for your logs; don't send it back.

Answer test events

An endpoint owner can send a test event to check your receiver. parseWebhook() accepts it without an entry in your event map and returns type: 'good-webhooks.test' with data: { endpointId }. Answer 2xx and skip processing:

if (event.type === 'good-webhooks.test') return new Response(null, { status: 204 })

Because the test event is part of the union, check event.type before reading event.data, even with a single event in your map. Event names starting with good-webhooks. are reserved, so your map can't define them.

Process each event once

Delivery is at least once: a retry or a replay repeats the same event.id and body. Make the change and record the ID in one transaction, then respond. A table with a unique ID column is enough:

receipts.sql
CREATE TABLE webhook_receipts (
  event_id text PRIMARY KEY,
  received_at timestamptz NOT NULL DEFAULT now()
);
if (event.type === 'good-webhooks.test') return // Answer 2xx; nothing to process.
await client.query('BEGIN')
const receipt = await client.query(
  'INSERT INTO webhook_receipts (event_id) VALUES ($1) ON CONFLICT DO NOTHING RETURNING event_id',
  [event.id],
)
if (receipt.rowCount) {
  // First time we see this event: apply the change.
  await client.query('INSERT INTO invoices (id, amount) VALUES ($1, $2)', [
    event.data.invoiceId,
    event.data.amount,
  ])
}
await client.query('COMMIT')
// Respond 2xx whether or not the event was new.

The basic example runs exactly this and checks that a retry and a replay produce one invoice.

To keep only the newest state of each entity when events arrive out of order, compare versions.

Retries and replays can also deliver an event published before your latest deploy. Keep event names backward compatible: add invoice.paid.v2 for a breaking payload change, and deploy receiver support before the sender publishes it.

Verify a stored request later

parseWebhook() rejects a timestamp more than five minutes from now, which defaults to the current time. To verify a request you stored earlier, pass the time you received it. Store the raw body, the headers, and the receipt time.

const event = await parseWebhook({
  body: row.body,
  headers: row.headers,
  secret: process.env.WEBHOOK_SECRET!,
  events,
  now: new Date(row.receivedAt),
})

The tolerance is measured from now. To change it, see toleranceSeconds in the verify reference.

Verify another sender's format

verifyWebhook() authenticates any Standard Webhooks request and leaves parsing to you. See the verify reference.

import { verifyWebhook } from 'good-webhooks/verify'

verifyWebhook({ body: rawBody, headers: request.headers, secret })
// Parse the body only after this returns.

On this page