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 each event 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.

Single-commit event deduplication

Unique event rows and domain updates commit together in one statement.

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.

HTTPS endpoint
Any server route or serverless function reachable over HTTPS that forwards verified events to your project.
Signing secret
Copy the webhook secret generated when registering the endpoint in GitHub and store it as GITHUB_WEBHOOK_SECRET.
Service role
{ "default::role": "service" } in the endpoint’s serviceGlobals, configured in the console or through the Control API. The schema policies below check global role.

Deduplicate events in one commit#

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;  # Set to 'service' for service keys via endpoint serviceGlobals (user sessions cannot spoof it).  global role: str;   # Deduplicates inbound webhooks by enforcing uniqueness on (source, event_id).  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;    # Linked GitHub issue reference formatted as owner/repo#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,    }    # Duplicate deliveries return an empty set here, so the ticket update below is skipped.    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) }
Duplicate deliveries
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.
Mid-write crashes
The event log row and the ticket transition share one PostgreSQL commit, so a crash cannot record the event without updating the ticket.
Stored payload
Persisting the full payload as json lets you replay historical deliveries if your business logic changes.

Verify the sender and write#

An inbound webhook route sits between the external provider’s HTTP delivery and your deployed EdgeQL mutation.

External webhook sender

Providers post signed payloads carrying a stable delivery ID per event.

Raw-byte HMAC check

Your route verifies the HMAC-SHA256 digest over raw bytes before parsing.

Scoped service key

A dedicated key executes your deployed query under row-level schema policies.

Create a dedicated service key for the webhook route, audit its row reach and push your query catalog.

Terminal
# Create a dedicated service key for the webhook route (store as NAPALM_KEY)napalm keys create support --label github-webhooks --days 90 # Audit how many rows the key can read or write before deploying the routenapalm keys reach support <key-id> napalm queries push support

In the route handler, verify the sender’s HMAC against the raw request bytes before calling recordIssueClosed.

src/app/hooks/github/route.ts
// src/app/hooks/github/route.tsimport { NapalmClient } from 'napalm-client' const address = process.env.NAPALM_URL!// Authenticate as a backend service rather than an end user.const napalm = new NapalmClient(address, { token: process.env.NAPALM_KEY }) /** Verifies GitHub's X-Hub-Signature-256 ("sha256=" + hex HMAC-SHA256) over the raw body. */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))  // crypto.subtle.verify compares digests in constant time.  return crypto.subtle.verify('HMAC', key, signed, body)} export async function POST(request: Request) {  // Read the raw bytes first so JSON parsing never alters the signed payload.  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))  // Acknowledge and ignore event types this route does not handle.  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: {        // Stable GitHub delivery ID across retries.        event_id: request.headers.get('x-github-delivery'),        issue: `${event.repository.full_name}#${event.issue.number}`,        body: event,      },    }),  })  // Non-2xx responses signal a failed delivery in GitHub's webhook log.  return new Response(null, { status: answer.ok ? 204 : 500 })}
Raw request bytes
HMAC signatures cover the exact wire bytes. Read request.arrayBuffer() first, verify the digest and decode JSON afterward.
Status codes
Return 2xx only after your database write commits. Most webhook senders treat any 2xx as final and never resend that delivery.
Manual redelivery
GitHub does not retry failed deliveries automatically, though operators can inspect and redeliver any failed payload from the repository’s webhook settings.

Provider signature headers#

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

SenderSignatureEvent ID
GitHubX-Hub-Signature-256: sha256= followed by the body’s HMAC-SHA256 in hex.Event IDThe X-GitHub-Delivery header
StripeStripe-Signature, verified via stripe.webhooks.constructEvent.Event IDid in the body
Clerk, ResendSvix’s three headers, verified via 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: HMAC-SHA256 over v0, the timestamp header and the body.Event IDevent_id in the body

Billing & payments walks through a complete Stripe webhook route.

Acknowledge fast and queue slow work#

Webhook senders time out after a few seconds and mark slow responses as failed. When handling an event requires external API calls or heavy work, record InboundEvent and insert an ext::napalm::Job in one statement, then return 204 immediately.

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))  ),  # Enqueue the background handler job in the same transaction only when the event is new.  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 constant on every attempt, pass call.job.id as the idempotency key to any external API your handler calls. Actions & background jobs walks through a complete outbox handler.

Handle late and out-of-order events#

Webhook payloads reflect provider state at send time. Two updates to the same record can arrive in either order, or a delayed retry can arrive an hour after a newer change.

Fetch current state
Treat the webhook as a wake-up signal, fetch the latest resource state from the provider’s API and write that snapshot. Out-of-order deliveries then converge to the same row.
Guard on timestamps
Store the provider’s event timestamp on your row and add a filter clause so updates skip events older than the stored timestamp.
Monotonic transitions
In the ticket example above, closing an issue is a one-way transition, so arrival order does not affect the final state.

Scope the route’s service key#

The webhook route authenticates with a service key under your schema’s service-role policies. In the schema above, that role has full access to InboundEvent and can read and update Ticket rows without permission to insert or delete tickets.

Audit reach first
napalm keys reach counts the readable and writable rows of each type before you deploy the route.
Lock to deployed queries
napalm endpoint support --passthrough none blocks ad-hoc statements from every caller so the key can invoke only deployed queries.
Revoke on leak
napalm keys revoke disables the credential immediately. Incoming deliveries fail until you deploy a replacement key, after which you can redeliver missed events from the sender’s dashboard.

Check the route#

  1. Send an unsigned request

    Confirm the route returns 401 and inserts zero rows into InboundEvent.

  2. Close a tracked GitHub issue

    Confirm the linked ticket transitions to resolved, InboundEvent records one row and GitHub’s webhook log shows a 204 response.

  3. Redeliver the same event

    Confirm the route returns 204 again, InboundEvent still holds a single row and the query returns is_new: false.

  4. Audit the key’s reach

    napalm keys reach support <key-id> reports counts for events and tickets and zero access to any other type.

Type a word or two to search every docs page.