Receiving webhooks
OpenEmail's webhooks with the TypeScript SDK, end to end: register a hook, verify and parse what it sends, answer it, recover from failures, test it.
The API sends two kinds of webhook, both POSTs signed with the hook's secret
(x-openemail-signature: sha256=<hex HMAC-SHA256 of the exact body>):
- Event batches: what changed in a mailbox or a domain (mail arriving, flags changing, deliveries settling), as identifiers.
- Message deliveries: a whole message, for an address whose mail goes to a URL.
Register a hook
A mailbox's and a domain's event webhooks each get their own copy of a batch, signed with their own secret:
await openemail.mailboxes.setEventWebhook(mailboxId, { url: 'https://example.com/hooks/openemail', secret })
await openemail.domains.setEventWebhook(domain, { url: 'https://example.com/hooks/openemail', secret })Messages come from a mailbox's message webhook,
mailboxes.setMessageWebhook,
and from a route: routes.create with a
webhookUrl, as its destination or as a tap beside another one (its secret is
webhookSecret).
Give each a secret. It is optional, but without one the API signs nothing, so
there is nothing to check: verifyWebhookSignature and the parsers throw a
TypeError when given an empty secret.
Receive the raw body
The signature is over the body's exact bytes: parsed and written again, it is no longer what was signed. Read the body before anything parses it.
-
A handler given a Fetch
Request(Next.js route handlers, Hono, Cloudflare Workers, Bun, Deno):await request.text(). -
Express: give the hook's route
express.raw(), and passreq.body, aBuffer:app.post('/hooks/openemail', express.raw({ type: '*/*' }), async (req, res) => { const batch = await parseEventWebhook(req.body, req.get('x-openemail-signature'), secret) res.sendStatus(204) })
The body is a string, an ArrayBuffer or any typed array (a Buffer, a
DataView); anything else, parsed JSON or a Blob, throws a TypeError.
Verify and parse
import { parseEventWebhook, WebhookSignatureError } from '@openemail/sdk'
async function onEvents(request: Request): Promise<Response> {
const body = await request.text()
const signature = request.headers.get('x-openemail-signature')
try {
const batch = await parseEventWebhook(body, signature, secret)
// queue the batch's work here, then answer
return new Response(null, { status: 204 })
} catch (error) {
if (!(error instanceof WebhookSignatureError)) throw error
return new Response(null, { status: 401 })
}
}parseEventWebhookchecks the signature, then parses the batch (EventWebhookPayload). It throws aWebhookSignatureErrorwhen the signature is not the body's.parseMessageWebhookdoes the same for a message delivery (WebhookDeliveryPayload).verifyWebhookSignature(body, signature, secret)only answers whether the signature is the body's, compared in constant time.
Answer, and dedupe
Answer 2xx within 30 seconds and do the work after. A non-2xx answer or a
timeout is a failed attempt, sent again later on a backoff; a redirect is never
followed, and counts as a failed attempt too.
- A batch keeps its
idacross retries, and a mailbox's and a domain's copies of one batch share it: dedupe on itsidand itsscope. - A message delivery keeps its
deliveryId: dedupe on that.
Refuse a replayed batch
A batch's sentAt is its attempt's own time, in epoch seconds, inside the
signed body. A retry carries a fresh one; a request captured and sent again
later carries an old one. Refuse a batch whose sentAt is more than a few
minutes from now:
import type { EventWebhookPayload } from '@openemail/sdk'
function isFresh(batch: EventWebhookPayload): boolean {
return Math.abs(Date.now() / 1000 - batch.sentAt) <= 300 // five minutes, either way
}When the answers keep failing
After 24 hours of failed attempts the API disables the hook: its
disabledReason is failing. Setting the hook again enables it.
const hook = await openemail.mailboxes.getEventWebhook(mailboxId)
if (hook.disabledReason === 'failing') await openemail.mailboxes.setEventWebhook(mailboxId, { url: hook.url, secret })Events are signals, not a journal. After a disabled hook, or any gap, catch up
with messages.getChanges from
the last batch's state, its states.Email:
const changes = await openemail.messages.getChanges(mailboxId, { since: state })Send a test
mailboxes.testEventWebhook
and domains.testEventWebhook
send the hook one batch now: a way to check an endpoint before real events
arrive.
Message deliveries
A message delivery's POST is the delivery itself: answer 2xx within 30
seconds, or it is sent again with the same deliveryId. Its bodies and
attachments are inlined up to fixed ceilings (1 MiB a body, 256 KiB an
attachment, 1 MiB of attachments in all). Anything larger arrives as a signed
link that expires (url, rawUrl), which needs no credential: fetch it as it
is, or pass its token, the link's last segment, to
deliveries.download. A route or
a tap set to webhookFormat: 'reference' gets the envelope and every header
without the parsed bodies, for a receiver that parses MIME itself.
What each payload holds is in the API reference's Webhooks: an event batch and a message delivery.
Errors and retries
The TypeScript SDK's one error type, RequestError, and its codes; which calls it sends again, and how idempotency keys make a send safe to retry.
Live events
A mailbox's live changes with the TypeScript SDK: a channel that holds itself open, typed frames, reconnects with backoff, and when it ends for good.