Skip to Content

Webhooks

Foir pushes events to your backend when content changes — a record is published, an operation finishes, and so on. It delivers those events by dispatching an operation that you attach to a model event as a lifecycle hook. Each delivery is an HTTP POST to an endpoint you control, authenticated with a short-lived, JWKS-verifiable scoped token rather than a classic shared-secret HMAC signature.

This page is the map: what events exist, how a delivery is wired and shaped, how you authenticate it, and how retries and redelivery work. The hooks, operations, and verification pieces are each documented in depth on their own pages — this ties them together for the “how do I receive events from Foir” question.

Two different things called “webhook.” Foir’s outbound event delivery is a scoped-token-authenticated operation dispatch (below). The classic HMAC pattern, verifyWebhookSignature(body, signature, secret), is for the reverse direction: your Foir app or extension receiving a webhook from a third-party service like Shopify. See Inbound HMAC webhooks. Don’t reach for an HMAC secret to verify a Foir delivery: verify the token instead.

The event catalog

Foir emits events across a dozen families — records, users, sessions, operations, imports, migrations, bulk updates, organizations, memberships, billing, project lifecycle and invitations.

Hook Events is the complete catalogue, with the exact payload keys each one delivers. It is generated from the platform’s own event registry and copied here on each release, so it is the list to trust rather than any summary on this page.

No count is given here on purpose. The registry grows, and a number written into prose goes stale quietly — the catalogue is the only place that counts.

The two families you reach for most often from this page:

  • Record events (RECORD_CREATED, RECORD_UPDATED, RECORD_DELETED, RECORD_PUBLISHED, RECORD_UNPUBLISHED) — content lifecycle.
  • Operation events (OPERATION_COMPLETED, OPERATION_FAILED, OPERATION_CANCELLED, OPERATION_TIMED_OUT) — an operation execution reached a terminal state, for chaining follow-up work.

Both are project-plane events: you subscribe with a project hook. The membership, billing, project and invitation events are workspace-plane and are subscribed on the workspace instead — see the catalogue.

Wiring a delivery

Receiving an event is three steps:

1. Deploy an HTTP endpoint (anywhere — a Worker, a Lambda, your API). 2. Register it as an Operation → endpoint URL + declared grants. 3. Attach that operation to a model event as a Hook → optional condition.
  • The operation owns the endpoint URL and the grants its dispatch token should carry. See Operations → Creating an Operation or define it in config with defineOperation.
  • The hook binds a model + event to that operation, with an optional condition. Define it in the console (Automation → Hooks, or the Hooks tab on a model), via foir hooks create, or in foir.config.ts with defineHook.

The delivery request

When the event fires, Foir POSTs to your endpoint:

Method / URLPOST to the operation’s registered endpoint URL
HeadersX-Foir-Token: the scoped token to verify. X-Foir-Context: the run’s context as key=value pairs separated by ;, namely project, org_id (when the run stands in an organization), app, operation, triggered_by, execution_id and causation_chain
Bodyan OperationPayload

For a hook-fired delivery the payload’s trigger.type is lifecycle, and the event’s own keys arrive under input — so RECORD_PUBLISHED’s record id is payload.input.recordId, not payload.recordId. Record events carry the keys that identify what changed, not the record’s content: read the record back under your own credentials when you need its data. Hook Events lists the exact keys each event delivers, and the full request/response contract is under Operations → The HTTP Contract.

Verifying a delivery

Verify X-Foir-Token before you process anything. It’s a short-lived token scoped to this single dispatch; verify it against Foir’s JWKS at https://api.foir.dev/.well-known/jwks.json. The verified claims tell you which tenant, project, and app the delivery belongs to, and which grants it carries. The SDK’s verifyScopedToken does the fetch-and-verify for you — see Server API → verifyScopedToken.

import { verifyScopedToken, parseSubject } from '@foir/sdk/server'; app.post('/hooks/on-publish', async (c) => { const token = c.req.header('x-foir-token'); if (!token) return c.json({ error: 'missing token' }, 401); const claims = await verifyScopedToken( token, 'https://api.foir.dev/.well-known/jwks.json', ); const { appName } = parseSubject(claims.sub); const payload = await c.req.json(); // OperationPayload // ...react to payload.input, payload.trigger, etc. return c.json({ success: true }); });

There is no HMAC secret to configure for this path, and no X-Foir-Signature header — the token is the only credential.

Responding: sync vs async

A hook has no async field. How your endpoint answers is set by the operation’s execution mode, and a delivery goes out after the write that raised the event has committed, so nothing waits for your endpoint and a hook cannot reject the write:

  • Sync: do the work and return an OperationResult ({ success, result?, error? }) inline.
  • Async: return 202 Accepted, queue the work, and report back later using the callback block in the payload (a bearer token plus the exact complete / fail / progress / cancel mutation names). Use for long-running work and external syncs. See Operations → Response (async mode).

Ordering: last-write-wins

Foir does not guarantee delivery order, and deliberately does not offer an ordered mode. Deliveries are claimed in batches and dispatched concurrently, and a retry re-inserts a delivery behind ones that were sent after it. Two changes to the same record can therefore reach your endpoint in either order.

This matters more than it used to. A delivery body describes the resource as of the event, not as it is now — that is what makes replay and late subscription meaningful. Most events carry that as a state snapshot; RECORD_* events deliberately do not (state is null), so for those you re-read the record yourself. Either way the hazard is the same: if an older delivery lands after a newer one and you act on it, you overwrite good data with stale data, and nothing in the response tells you it happened.

Every delivery of a real event carries a seq for exactly this. Apply last-write-wins:

app.post('/hooks/on-publish', async (c) => { const payload = await c.req.json(); // OperationPayload const { recordId, seq } = payload.input; // A synthetic `foir hooks test` fire has no position in any stream and // carries no seq. Handle it, but never let it move your high-water mark. if (typeof seq !== 'number') return c.json({ success: true }); const applied = await db.getAppliedSeq(recordId); if (applied !== null && seq <= applied) { // Already have this delivery, or a newer one. Ack and drop it. return c.json({ success: true }); } // Record events identify what changed; read the content back yourself. const record = await readRecord(recordId); await db.applyAndRecordSeq(recordId, seq, record); return c.json({ success: true }); });

seq is assigned in commit order and increases monotonically within one project. Compare it only against another seq from the same project — it is not a global counter, and values from two projects are unrelated. Tenant-scoped events (plan changes, membership, invitations) form their own sequence.

Two properties worth relying on:

  • Gaps are normal and are not lost events. Your project’s events share the sequence with events your subscription does not match, and history eventually ages out of retention. seq is for comparing, not for counting.
  • The same value is the read API’s cursor. A seq you received can be handed straight back to the event log as after to resume reading from that point.

One delivery has no seq: a synthetic fire from foir hooks test. It is a probe of your endpoint, not a fact on the stream, so stamping it with a position would teach your handler a lie — the field is simply absent. Guard for it, as above, or a smoke test will advance a high-water mark that no real event ever reached.

Why not serial delivery? Because a per-key ordered queue would be a promise that quietly stops holding under load — head-of-line blocking, a stuck endpoint stalling every later event for that key, and no signal you could act on when it degraded. A number in the body is the opposite: you can check it, and you decide what to do. This is the standard webhook contract for the same reason Stripe states plainly that its events can arrive out of order.

Reliability: retries, redelivery, dead letters

  • Automatic retries. Async deliveries run on a background job queue and retry automatically when your endpoint is temporarily unavailable.

  • Dead-letter queue. An async execution that exhausts its retries lands in the dead-letter queue, where you can inspect the error and retry or dismiss it.

  • Inspect and replay from the hook side:

    foir hooks deliveries <hookId> --status failed --first 20 # recent failures foir hooks retry-delivery <deliveryId> # replay one foir hooks test <hookId> --data '{"recordId":"rec_abc123"}' # synthetic delivery to smoke-test a receiver
  • Make your handler idempotent. A retry after a network blip means your endpoint may receive the same delivery more than once. Key on executionId (present on every payload) and treat repeats as no-ops. Idempotency and ordering are separate obligations — dropping a duplicate does not tell you whether what you kept is the newest.

Inbound HMAC webhooks (from third parties)

The reverse direction, a third-party service calling your Foir app or extension, uses the classic pattern: the sender HMAC-signs the raw body, and you verify it with a shared secret. This is unrelated to the scoped-token path above.

import { verifyWebhookSignature } from '@foir/sdk/server'; app.post('/webhooks/shopify', async (c) => { const body = await c.req.text(); const signature = c.req.header('x-shopify-hmac-sha256') ?? ''; if (!(await verifyWebhookSignature(body, signature, process.env.SHOPIFY_WEBHOOK_SECRET!))) { return c.text('Invalid signature', 401); } // Process webhook... });

verifyWebhookSignature computes an HMAC-SHA256 of the raw request body and compares it with the signature sent, in hex or in base64. A signature with a prefix such as sha256=, or a timestamped header, needs the prefix stripped or the sender’s own library. See Server API → Webhook Verification.

See also

Last updated on