Skip to Content

Publish events

Define a typed event catalog, describe it for receivers, publish with idempotency keys, reach the right scope, and commit events with your own database writes.

publish() records an event and one delivery per subscribed endpoint. It sends nothing itself; a worker does. The examples use the webhooks client from installation.

import { webhooks } from './webhooks.js'

const { eventId, deliveryCount } = await webhooks.publish({
  type: 'invoice.paid',
  data: { invoiceId: 'inv_123', amount: 4200 },
})

deliveryCount is how many endpoints will receive it. Zero means nobody subscribed, not an error.

Define your events

The event map is your public webhook catalog: names and payload schemas. Keep it in its own module so receivers can import it too.

events.ts
import { z } from 'zod'

export const events = {
  'invoice.paid': z.object({
    invoiceId: z.string(),
    amount: z.number().int().nonnegative(),
  }),
  'account.activated': z.object({ accountId: z.string() }),
}

Pass it to createWebhooks({ events }). TypeScript then checks every publish(), endpoint subscription, and parseWebhook() against it, and payloads are validated at runtime before anything is stored:

await webhooks.publish({ type: 'invoice.paid', data: { invoiceId: 'inv_1', amount: '42' } })
//                                                                             ^ type error

Describe your events

describeEvents() returns each event name with a JSON Schema of its payload. Use it to publish a catalog page for receivers.

import { webhooks } from './webhooks.js'

const catalog = webhooks.describeEvents()

With the Zod map above, the first entry is:

{
  "type": "invoice.paid",
  "schema": {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
      "invoiceId": { "type": "string" },
      "amount": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }
    },
    "required": ["invoiceId", "amount"],
    "additionalProperties": false
  }
}

Entries follow the order of the event map. The result depends only on the map, so you can serve it as JSON from any route:

app/webhooks/events/route.ts
import { webhooks } from '@/lib/webhooks'

export function GET() {
  return Response.json(webhooks.describeEvents())
}

Or render each type with its schema on a docs page. Without a delivery engine, for example in a Better Auth app that only manages endpoints, call describeEvents(events) from good-webhooks with the validator map your own sender uses.

The schema describes the validated output, because that is the payload receivers get. In Zod and ArkType, a field with a default is therefore required. Pick the JSON Schema dialect with target:

webhooks.describeEvents({ target: 'draft-07' }) // default 'draft-2020-12'

The validator converts the schema itself. Support depends on the library:

ValidatorSupport
Zod 4.2+Built in
ArkType 2.1.28+Built in
ValibotThrough a wrapper
Other Standard Schema librariesName only

From ArkType 2.2.9, types JSON Schema cannot express, such as dates, become {}. Other Standard Schema libraries get schema: null.

Valibot needs each schema wrapped with toStandardJsonSchema() from @valibot/to-json-schema 1.5+. The wrapper still validates, so the same map works for publish() and parseWebhook():

events.ts
import { toStandardJsonSchema } from '@valibot/to-json-schema'
import * as v from 'valibot'

export const events = {
  'invoice.paid': toStandardJsonSchema(v.object({ invoiceId: v.string(), amount: v.number() })),
}

Zod and Valibot cannot convert transforms or dates by default. describeEvents() then throws INVALID_CONFIG naming the event, and returns no entries at all. To fix it:

  • Define the event with a JSON-shaped schema, such as z.iso.datetime() instead of z.date().
  • Or pass the validator's own option through libraryOptions, from the table below.
  • Or call describeEvents() on a map without that event, and append your own entry for it.
webhooks.describeEvents({ libraryOptions: { unrepresentable: 'any' } })

libraryOptions goes to every event's converter unchanged:

ValidatorlibraryOptions
Zod{ unrepresentable: 'any' }
Valibot{ errorMode: 'ignore' }
ArkType{ fallback }

With Zod's option, transforms and dates become {}. With Valibot's option, dates become {} and transforms are skipped, so the field shows its input type. That is wrong for a transform that changes the type, such as a string parsed into a number: publish() stores the number, and a receiver validating against the catalog would reject it. Give such an event an explicit output schema instead. With ArkType's option, your function returns the schema for each type it cannot express:

webhooks.describeEvents({
  libraryOptions: {
    fallback: { date: (ctx) => ({ ...ctx.base, type: 'string', format: 'date-time' }) },
  },
})

Make retries of your code safe

Your own code can run twice: a retried job, a double-clicked button. Add an idempotencyKey built from the business fact:

const result = await webhooks.publish({
  type: 'invoice.paid',
  data: { invoiceId: 'inv_123', amount: 4200 },
  idempotencyKey: 'invoice.paid:inv_123', 
})

result.duplicate // true when this key was already accepted
You publish again withResult
Same key, same type and payloadThe original event, duplicate: true. Nothing new sent
Same key, different type or payloadThrows IDEMPOTENCY_CONFLICT
A new keyA new event

Keys are unique per scope and are released when the event is pruned (seven days by default).

Publish in a named scope

The root client publishes in application scope. To reach the endpoints in a named scope, publish in that scope:

const organization = webhooks.forScope({ type: 'organization', id: organizationId })
await organization.publish({ type: 'invoice.paid', data, idempotencyKey })

A scope does not check permissions: decide in your app that the caller may act for this scope first.

Publish inside your transaction

When your tables and the webhook tables share a database, pass your transaction client. The event then commits or rolls back with your data:

import { pool, webhooks } from './webhooks.js'

const client = await pool.connect()
try {
  await client.query('BEGIN')
  await client.query('UPDATE invoices SET paid = true WHERE id = $1', ['inv_123'])
  await webhooks.publish(
    { type: 'invoice.paid', data: { invoiceId: 'inv_123', amount: 4200 } },
    { transaction: client }, 
  )
  await client.query('COMMIT')
} catch (error) {
  await client.query('ROLLBACK')
  throw error
} finally {
  client.release()
}
  • Workers can't see the event until you commit.
  • A failed publish() runs in a savepoint, so it doesn't break your transaction.
  • Pass a checked-out client, not the pool, and don't run other queries on it at the same time.
  • Finding recipients is a separate read. A Better Auth or second PostgreSQL database does not join the commit.

If recipients depend on the payload or on uncommitted rows, use transactional recipient selection.

Limit load per endpoint

By default each endpoint gets at most 2 requests at a time, across all workers. Change it per endpoint with deliverySettings:

await organization.deliverySettings.set(endpointId, { maxInFlight: 4 })

Nothing is sent until a worker runs.

On this page