Skip to the page

Guides · Integrations

Receiving webhooks

Verify incoming webhooks from external services, deduplicate deliveries and apply each update in a single transaction.

In the schema
ext::napalm::Job

What you’ll build#

You will build an HTTPS route that receives webhooks from an external service and applies them idempotently. The example resolves a support ticket when its linked GitHub issue closes. The same four steps handle Stripe, Clerk, Resend, Shopify or Slack: verify the raw-byte signature, record the event ID once, mutate your domain row in the same commit and acknowledge.

Signature check and single-commit deduplication

Verify the sender’s HMAC over the raw body first, then insert InboundEvent with unless conflict inside the same statement as your domain update so duplicate deliveries become safe no-ops.

Webhook senders retry aggressively and deliver events out of order. Enforcing uniqueness in the schema makes repeats harmless without distributed locks or separate deduplication caches.

Before you start#

Set up an HTTPS endpoint for the sender to reach, store the sender’s signing secret and configure your branch’s service role.

A route of your own
Any server or function that answers HTTPS. The sender calls the route, and the route calls your project.
The sender’s secret
GitHub shows a webhook’s secret when you add the webhook. Store the secret as GITHUB_WEBHOOK_SECRET.
The service role
{ "default::role": "service" } in the endpoint’s serviceGlobals, set in the console or through the Control API. The rules below name the service role.

Keep each event once#

Every sender attaches a stable delivery or event ID. InboundEvent records that ID under an exclusive constraint that rejects duplicate deliveries from the same sender.

dbschema/default.gel
using extension auth;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;  # 'service' for a service key, set in the endpoint's serviceGlobals. A session can't set it.  global role: str;   # Each event another service sent, kept once: a sender's id for an event can't repeat.  type InboundEvent {    required source: str;    required event_id: str;    required kind: str;    required body: json;    required receive_time: datetime {      readonly := true;      default := datetime_of_statement();    };     constraint exclusive on ((.source, .event_id));     access policy service_has_full_access      allow all      using (global role ?= 'service');  }   type Ticket {    required title: str;    # The GitHub issue that tracks it, as owner/name#number.    issue: str {      constraint exclusive;    };    required is_resolved: bool {      default := false;    };     access policy signed_in_can_read      allow select      using (exists global caller);    access policy service_can_read_and_update      allow select, update      using (global role ?= 'service');  }}

Recording the event and mutating the target record inside one EdgeQL statement guarantees both commit together or roll back together.

dbschema/queries/recordIssueClosed.edgeql
with  event := (    insert InboundEvent {      source := 'github',      event_id := <str>$event_id,      kind := 'issues.closed',      body := <json>$body,    }    # An event told twice inserts nothing here, and then the update below finds nothing.    unless conflict on ((.source, .event_id))  ),  resolved := (    update Ticket    filter exists event and .issue ?= <str>$issue    set { is_resolved := true }  ),select { is_new := exists event, tickets := count(resolved) }
An event sent twice
unless conflict returns empty on redelivery, so the query skips the ticket update and returns is_new: false. Your route still responds 204 so the sender stops retrying.
A crash mid-write
The event log row and the ticket transition share one PostgreSQL commit, so a crash cannot record the event without updating the ticket.
Stored body
Persisting the full payload as json lets you replay historical deliveries if your business logic changes.

Check the sender, then write#

Create a dedicated service key for the webhook route, verify the sender’s HMAC against the raw request bytes and call the deployed query.

External webhook sender

GitHub, Stripe, Clerk or Shopify posts event deliveries with a stable provider delivery ID to your HTTPS route.

Raw-byte HMAC verification

Your route verifies the sender’s HMAC-SHA256 signature in constant time over the unparsed ArrayBuffer body before parsing JSON.

Route-scoped service key

A dedicated ndb_… service key invokes recordIssueClosed, audited with napalm keys reach and revocable independently.

Terminal
# A key for the route alone. It's shown once: store it as NAPALM_KEY.napalm keys create support --label github-webhooks --days 90 # What it can reach, before anything depends on itnapalm keys reach support <key-id> napalm queries push support
src/app/hooks/github/route.ts
// src/app/hooks/github/route.tsimport { NapalmClient } from 'napalm-client' const address = process.env.NAPALM_URL!// A service key: this route is GitHub speaking, not a person.const napalm = new NapalmClient(address, { token: process.env.NAPALM_KEY }) /** Whether GitHub signed these bytes. X-Hub-Signature-256 is "sha256=" and the body's HMAC-SHA256 in hex. */async function isFromGitHub(body: ArrayBuffer, signature: string | null) {  const hex = /^sha256=([0-9a-f]{64})$/.exec(signature ?? '')?.[1]  if (!hex) return false  const key = await crypto.subtle.importKey(    'raw',    new TextEncoder().encode(process.env.GITHUB_WEBHOOK_SECRET!),    { name: 'HMAC', hash: 'SHA-256' },    false,    ['verify'],  )  const signed = Uint8Array.from(hex.match(/../g)!, (pair) => parseInt(pair, 16))  // verify compares in constant time.  return crypto.subtle.verify('HMAC', key, signed, body)} export async function POST(request: Request) {  // The raw bytes. A body parsed and written again wouldn't match its signature.  const body = await request.arrayBuffer()  if (!(await isFromGitHub(body, request.headers.get('x-hub-signature-256')))) {    return new Response(null, { status: 401 })  }  const event = JSON.parse(new TextDecoder().decode(body))  // An event this route has no use for is taken and dropped.  if (request.headers.get('x-github-event') !== 'issues' || event.action !== 'closed') {    return new Response(null, { status: 204 })  }  const answer = await napalm.fetch(`${address}/query/recordIssueClosed`, {    method: 'POST',    headers: { 'Content-Type': 'application/json' },    body: JSON.stringify({      variables: {        // GitHub's own id for this delivery, the same when it's sent again.        event_id: request.headers.get('x-github-delivery'),        issue: `${event.repository.full_name}#${event.issue.number}`,        body: event,      },    }),  })  // Anything but success shows as a failed delivery at GitHub, to send again.  return new Response(null, { status: answer.ok ? 204 : 500 })}
The raw body
A signature covers the bytes as sent. Read the body once as bytes, check the signature, then parse.
The answer
Success once the write commits, and a failure for anything else. Do not answer success for an event you failed to keep. After a success, most senders never send the event again.
A sender that does not retry
GitHub does not resend a failed delivery automatically. The webhook’s page lists each delivery, and you can resend any delivery from that page.

Check each sender’s signature#

Each webhook provider signs the raw HTTP body and supplies a stable delivery identifier for deduplication.

SenderSignatureEvent id
GitHubX-Hub-Signature-256: sha256= and the body’s HMAC-SHA256 in hex.Event idThe X-GitHub-Delivery header
StripeStripe-Signature, checked with stripe.webhooks.constructEvent.Event idid in the body
Clerk, ResendSvix’s three headers, checked with the svix library’s Webhook.verify.Event idThe svix-id header
ShopifyX-Shopify-Hmac-Sha256: the body’s HMAC-SHA256 in base64.Event idThe X-Shopify-Webhook-Id header
SlackX-Slack-Signature: an HMAC-SHA256 over v0, the timestamp header and the body.Event idevent_id in the body

Billing & payments has Stripe’s route written out.

Answer fast and queue slow work#

A sender waits a few seconds for an answer and counts a slow answer as a failure. When an event starts work that takes longer, keep the event and queue the work in one commit, then answer.

dbschema/queries/recordEvent.edgeql
with  event := (    insert InboundEvent {      source := <str>$source,      event_id := <str>$event_id,      kind := <str>$kind,      body := <json>$body,    }    unless conflict on ((.source, .event_id))  ),  # Queued only for an event that's new, in the commit that keeps it.  queued := (    for kept in event union (      insert ext::napalm::Job {        query := 'handleEvent',        variables := <json>(event := <str>kept.id),      }    )  ),select { is_new := exists event }
dbschema/queries/handleEvent.edgeql
select InboundEvent { id, source, kind, body }filter .id = <uuid>$event

handleEvent is an action. When the job runs, Napalm executes the query and sends the matching rows to your handler, retrying failed runs with exponential backoff for 24 hours. Because the job ID stays the same on every attempt, pass it as the idempotency key to any external API your handler calls. Actions & background jobs builds an example.

Handle late and out-of-order events#

An event describes the state at send time. Two events about one record can arrive in either order, and an event can arrive an hour late.

Ask the sender
Treat the event as a nudge. Read the record’s current state from the sender’s API and write that state. Any order and any number of deliveries then end the same.
Or compare times
Keep the sender’s own timestamp on your row, and have the update skip an event older than the row. Add the comparison to the update’s filter.
Events that only add
A closed issue stays closed in the ticket example, so order does not matter. Prefer changes that hold regardless of earlier events.

Give the route a key#

The route holds a service key, which gets the access your rules give the service role. Here the role has full access to events and can read and update tickets, without permission to insert or delete.

Count the reach
napalm keys reach counts the rows of each type the key can read and change before you deploy the route.
Limit the key to your queries
napalm endpoint support --passthrough none blocks ad-hoc statements from every caller. The key can then run your deployed queries and nothing else.
A leaked key
napalm keys revoke ends the key at once. The sender’s deliveries fail until the route has a new key. You can resend the failed deliveries afterward.

Check the route#

  1. Send a request with no signature

    The route answers 401, and InboundEvent has no new row.

  2. Close an issue a ticket tracks

    The ticket is resolved, and one event is kept. The delivery on the webhook’s page at GitHub shows a 204 answer.

  3. Redeliver the event

    The route answers 204 again, InboundEvent still holds one row, and the query returns is_new: false.

  4. Count the key’s reach

    napalm keys reach support <key-id> counts events and tickets and nothing else.

Type a word or two to search every docs page.