Framework
Use an outbound webhook when an external system needs to hear about a platform event. Register its destination and event choices, verify the signature at the receiving endpoint and make the receiver recognize a delivery it has already processed.
Open Mercato provides a built-in webhook system compliant with the Standard Webhooks specification. The webhooks module enables:
When any module emits a domain event (e.g., customers.person.created, sales.order.fulfilled), the webhooks module:
*) catches all platform eventscustomers.*)webhook-deliveries queue Module emits event → Event Bus → Webhook Dispatcher → Delivery Queue → HTTP POST
Every outbound delivery includes these headers per the specification:
webhook-id: msg_2KWPBgLlAfxdpx2AI54pPJ85f4W
webhook-timestamp: 1674087231
webhook-signature: v1,<signature>
content-type: application/json
Signature format: v1,<base64_hmac_sha256> of {webhook-id}.{webhook-timestamp}.{body}
{
"type": "customers.person.created",
"timestamp": "2026-03-04T10:30:00.000Z",
"data": {
"id": "uuid-here",
"firstName": "John",
"lastName": "Doe",
"tenantId": "tenant-uuid",
"organizationId": "org-uuid"
}
}
The module also registers a Custom Webhooks integration in the Integration Marketplace. That integration acts as the global control plane for the webhook subsystem:
/backend/webhooks, a create action, and the Notify admins on failed delivery setting.This means webhook operations have two scopes:
Via API:
POST /api/webhooks
{
"name": "My Integration",
"url": "https://example.com/webhook",
"subscribedEvents": ["customers.*", "sales.order.created"],
"httpMethod": "POST"
}
The response includes a whsec_-prefixed signing secret. This is the only time the secret is returned in plaintext – store it securely.
Caution
The rateLimitPerMinute field is accepted and stored for outbound endpoints, but the delivery worker
does not enforce it yet. Configure throttling on the receiving service until outbound rate limiting
is implemented.
Webhooks support pattern-based event subscriptions:
| Pattern | Matches |
|---|---|
customers.person.created | Exact match only |
customers.* | All events in the customers namespace |
* | All platform events |
| Method | Path | Description |
|---|---|---|
GET | /api/webhooks | List webhooks |
POST | /api/webhooks | Create webhook |
GET | /api/webhooks/:id | Get webhook details |
PUT | /api/webhooks/:id | Update webhook |
DELETE | /api/webhooks/:id | Soft-delete webhook |
POST | /api/webhooks/:id/rotate-secret | Rotate signing secret |
POST | /api/webhooks/:id/test | Send test delivery |
GET | /api/webhooks/deliveries | List delivery logs |
POST | /api/webhooks/deliveries/:id/retry | Retry failed delivery |
GET | /api/webhooks/events | List available event types |
Inbound webhook sources and legacy adapters must verify provider-specific signatures and any provider-specific timestamp rules before returning a verified event. The shared inbound route adds a provider-neutral backstop for Standard Webhooks and Svix-style timestamp headers: when webhook-timestamp or svix-timestamp is present, requests outside the replay window are rejected before either the source-first or legacy adapter flow persists or emits the inbound receipt.
The default replay window is 5 minutes. Set OM_WEBHOOKS_INBOUND_TIMESTAMP_TOLERANCE_SECONDS when a deployment needs to accept a wider delay.
If you're building a service that receives webhooks from Open Mercato, verify the signature to ensure authenticity:
import { createHmac, timingSafeEqual } from 'node:crypto'
function verifyWebhook(headers: Record<string, string>, body: string, secret: string): boolean {
const webhookId = headers['webhook-id']
const timestamp = headers['webhook-timestamp']
const signature = headers['webhook-signature']
// Check replay window (5 minutes)
const now = Math.floor(Date.now() / 1000)
if (Math.abs(now - parseInt(timestamp)) > 300) return false
// Verify signature
const toSign = `${webhookId}.${timestamp}.${body}`
const secretBytes = Buffer.from(secret.replace('whsec_', ''), 'base64')
const expected = createHmac('sha256', secretBytes).update(toSign).digest('base64')
// Extract signature value (after "v1,")
const received = signature.split(' ').find(s => s.startsWith('v1,'))?.slice(3)
if (!received) return false
return timingSafeEqual(Buffer.from(expected), Buffer.from(received))
}
Tip
Use the official Standard Webhooks libraries for verification in production – they handle edge cases like key rotation and multiple signatures.
Each attempt is sent by one worker: before sending, the worker claims the delivery (pending once its
retry is due, or sending left over by a worker that stopped more than the webhook timeout + 15 s ago),
and jobs for deliveries that already finished are ignored. Receivers should still deduplicate on the
webhook-id header, because delivery is at-least-once.
Failed deliveries are retried with exponential backoff. The delay before attempt n is
1s × 2^(n-2) plus up to 1s of jitter (calculateNextRetry in lib/delivery.ts):
| Attempt | Delay before it |
|---|---|
| 1 | immediate |
| 2 | ~1 second |
| 3 | ~2 seconds |
| 4 | ~4 seconds |
| 5 | ~8 seconds |
| 6 | ~16 seconds |
| 7 | ~32 seconds |
| 8 | ~1 minute |
| 9 | ~2 minutes |
| 10 | ~4 minutes |
Total window: with the default maxRetries of 10, a delivery exhausts its attempts about
8.5 minutes after the first one – not hours. Retries stop once attemptNumber reaches
maxRetries, so the last delay is the one before the final attempt. In general the window is
2^(maxRetries - 1) - 1 seconds, so raising maxRetries grows it geometrically: 15 gives ~4.5 hours,
17 gives ~18 hours.
Warning
Size your alerting against this window, not against a multi-hour assumption. A receiver that is down
for more than ~9 minutes will exhaust every attempt for events emitted during the outage. If you need
longer durability, raise maxRetries on the webhook and monitor the delivery log. After the receiver
recovers, use the delivery's Retry action or POST /api/webhooks/deliveries/:id/retry to re-enqueue
an expired delivery.
Non-retryable responses: HTTP 4xx (except 408 and 429) are not retried.
Auto-disable: After a configurable number of consecutive failures (default: 100), the webhook is automatically disabled. HTTP 410 (Gone) responses immediately disable the webhook. Re-activating a disabled webhook resets its consecutive-failure counter, so it gets the full threshold again.
Rotate webhook secrets without downtime:
POST /api/webhooks/:id/rotate-secret
During the rotation period (default: 24 hours):
Webhook secrets use the Standard Webhooks format:
whsec_<provider-credential>/JbT9Feg98sgSFYsAy| Strategy | Use Case | Status |
|---|---|---|
http | Standard HTTP/HTTPS endpoints (default) | Available today |
sqs | AWS SQS queues for async processing | Planned |
sns | AWS SNS topics for fan-out | Planned |
The webhooks module provides a generic receiver for external webhook sources:
POST /api/webhooks/inbound/:endpointId
Third-party modules can register WebhookEndpointAdapter implementations to handle specific providers (e.g., Stripe, Zapier). The adapter contract:
interface WebhookEndpointAdapter {
readonly providerKey: string
readonly subscribedEvents: string[]
formatPayload(event): Promise<WebhookPayload>
verifyWebhook(input): Promise<InboundWebhookEvent>
processInbound(event): Promise<void>
}
Inbound webhooks are:
Set OM_WEBHOOK_MAX_BODY_BYTES to a positive byte count when globally bounded webhook receivers legitimately need a different default. InboxOps inherits that value when it is set; INBOX_OPS_WEBHOOK_MAX_BODY_BYTES can override only the email-ingress source, whose legacy fallback remains 2 MiB when neither variable is configured. Payment gateway handlers preserve legacy reads unless their registration opts into maxBodyBytes. The bounded reader checks a valid declared Content-Length before reading and also counts streamed bytes, so missing, invalid, or understated lengths cannot bypass the cap. Requests over the applicable limit return 413 without invoking provider verification. Keep the ingress or reverse-proxy limit scoped to the webhook paths and aligned with the effective application values.
The webhook signing, verification, and secret management utilities are available as a shared library for use by any module:
import {
signPayload,
buildStandardHeaders,
verifyStandardWebhook,
generateWebhookSecret,
parseWebhookSecret,
} from '@open-mercato/shared/lib/webhooks'
The webhook management dashboard is available at /backend/webhooks with:
/backend/integrations/webhook_custom| Route | Purpose |
|---|---|
/backend/integrations/webhook_custom | Global webhook settings, failed-delivery notifications, configured endpoint shortcuts, aggregated delivery log |
/backend/webhooks | Endpoint list and create entry point |
/backend/webhooks/create | Create a new webhook endpoint |
/backend/webhooks/:id | Endpoint detail, send test, rotate secret, inspect delivery history |
When Notify admins on failed delivery is enabled in the integration Settings tab, the module creates in-app notifications for admin-capable users after a delivery exhausts all retry attempts. This notification layer is independent from HTTP retry logic and is meant to surface operational issues early.
Secrets are generated automatically and revealed in plaintext only:
After that, the admin UI only shows a masked value. Operators must copy the secret during the reveal window or rotate it again later.
| Feature | Description |
|---|---|
webhooks.view | View webhooks and delivery logs |
webhooks.manage | Create, edit, and delete webhooks |
webhooks.secrets | View and rotate webhook secrets |
webhooks.test | Send test webhook deliveries |
The outbound dispatch subscriber (webhooks:outbound-dispatch) caches the active webhook subscriptions for each (tenant, organization) scope so that events for a tenant with no webhooks configured do not run a decrypting database query on every event.
Only non-sensitive matching data is cached: id, tenantId, organizationId, and subscribedEvents. Secrets and target URLs are never cached. When a cache entry names candidate webhook IDs, the subscriber still re-reads those rows from the database before building any delivery, so the data actually sent to a delivery is always fresh.
Invalidation happens two ways:
webhooks.webhook.created, webhooks.webhook.updated, webhooks.webhook.deleted, and webhooks.webhook.disabled, and clears the cache tag for that tenant (webhooks:subscriptions:tenant:<tenantId>) when one fires.OM_WEBHOOKS_SUBSCRIPTION_CACHE_TTL_MS sets the cache TTL in milliseconds (default 60000). Set it to 0 to disable the cache entirely. Because invalidation is inline and event-driven, the TTL is a safety net rather than the mechanism that keeps the cache correct.
Multi-instance caveat: this cache goes through CACHE_STRATEGY. With the memory strategy, the cache is per process, so a webhook write on one instance cannot invalidate another instance's copy inline – that instance only sees the change once its own TTL expires or it processes the invalidation event itself. Deployments running multiple instances that need webhook subscription changes to take effect everywhere promptly should use a shared strategy (CACHE_STRATEGY=redis) or lower OM_WEBHOOKS_SUBSCRIPTION_CACHE_TTL_MS.
Previous: Rate Limiting · Next: Add widgets to existing admin pages