Skip to Content

Core

Compose endpoint management and PostgreSQL delivery.

The root entry point combines endpoint management and PostgreSQL delivery in one client.

import {
  createWebhooks,
  createDelivery,
  describeEvents,
  generateEncryptionKey,
  verifyWebhook,
  WebhookError,
} from 'good-webhooks'
import type {
  WebhookOptions,
  Webhooks,
  WebhookClient,
  EndpointInput,
  EndpointPatch,
  WebhookErrorCode,
  EventDescription,
  DescribeEventsOptions,
} from 'good-webhooks'

The root also exports the shared types listed under other root exports. For the step-by-step setup, see installation.

createWebhooks

createWebhooks<const E extends EventDefinitions>(options: WebhookOptions<E>): Webhooks<E>
webhooks.ts
import { createWebhooks } from 'good-webhooks'
import { Pool } from 'pg'
import { z } from 'zod'

export const pool = new Pool({ connectionString: process.env.DATABASE_URL })

export const webhooks = createWebhooks({
  database: pool,
  encryptionKey: process.env.WEBHOOK_ENCRYPTION_KEY!,
  events: {
    'invoice.paid': z.object({ invoiceId: z.string(), amount: z.number().int() }),
  },
})

WebhookOptions<E> accepts every delivery option except source, plus these fields:

FieldType
encryptionKeystring | Uint8Array
managementEndpointManagement
maxEndpointsEndpointLimit

encryptionKey is required for the default PostgreSQL management provider. It takes base64-encoded 32 bytes or a 32-byte array.

management is an optional existing provider. Its source supplies recipients and current endpoint state.

maxEndpoints is an optional (scope) => number | Promise<number> from 0 to 1,000 for the default provider. The default is 1,000 per scope.

  • Without management, the constructor creates standalone PostgreSQL management from database, schema, the configured event names, encryptionKey, and allowLocalhost. schema then applies to both the management and delivery tables.
  • With management, that provider keeps its own database, schema, encryption, URL-validation, and endpoint-limit configuration. Core options do not reconfigure it, encryptionKey is unused, and maxEndpoints throws INVALID_CONFIG.

Invalid options throw INVALID_CONFIG: a missing event map, a malformed key, a database without query() and connect(), or any delivery option out of range. To pass old keys during key rotation, build the provider with createPostgresManagement and pass it as management.

Returned client

The client exposes publish, deliveries, deliverySettings, and worker from the delivery engine, plus these members:

  • endpoints.create(input): creates an endpoint and returns { endpoint, secret }.
  • endpoints.list(): returns all nondeleted endpoints in application scope.
  • endpoints.get(id): returns one endpoint, including its deleted state.
  • endpoints.update(id, patch): changes URL, description, events, or headers.
  • endpoints.pause(id): records paused state with pauseReason: 'owner'.
  • endpoints.resume(id): records active state after URL validation, including after an automatic pause.
  • endpoints.remove(id): deletes it, clearing secrets and headers.
  • endpoints.rotateSecret(id, { graceMs? }): returns a new signing secret and the endpoint.
  • endpoints.sendTestEvent(id): sends one signed test event and returns the receiver's answer. It records nothing.
  • check(): checks the default management provider, if constructed here, then delivery schema compatibility.
  • describeEvents(options?): returns the event names and payload JSON Schemas.
  • forScope(scope): returns the same publication, history, settings, and endpoint methods bound to one named scope.

endpoints

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

const { endpoint, secret } = await webhooks.endpoints.create({
  url: 'https://receiver.example/webhooks',
  eventTypes: ['invoice.paid'],
})
await webhooks.endpoints.rotateSecret(endpoint.id, { graceMs: 60 * 60 * 1000 })

Endpoint methods follow the management contract and limits, including its errors. EndpointInput<E> and EndpointPatch<E> restrict subscriptions to event names in E, and take optional headers. Built-in management returns headers on every Endpoint, {} when there are none; a wrapper or test double may omit it. removeScope and reencrypt are direct provider operations, not members of this client. The endpoints guide covers the lifecycle.

forScope

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

const organization = webhooks.forScope({ type: 'organization', id: 'org_123' })
await organization.publish({ type: 'invoice.paid', data: { invoiceId: 'inv_1', amount: 4200 } })
await organization.endpoints.list()

forScope validates and snapshots its scope, so later changes to the argument have no effect. An invalid scope throws INVALID_INPUT. It does not authorize a caller. See scopes.

The scoped client has no worker, check, or describeEvents: those operate at installation level. WebhookClient<E> is its type.

check

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

await webhooks.check() // Throws SCHEMA_MISMATCH if tables are missing or outdated.

check() never applies migrations. When a provider is injected, it does not call that provider's optional health checks. The host stays responsible for checking its management storage.

describeEvents

describeEvents(events: EventDefinitions, options?: DescribeEventsOptions): EventDescription[]
webhooks.describeEvents(options?: DescribeEventsOptions): EventDescription[]
import { describeEvents } from 'good-webhooks'
import { events } from './events.js'

const catalog = describeEvents(events, { target: 'draft-07' })

Returns one entry per event, in the order of the event map. The client method describes the map passed to createWebhooks() or createDelivery(). The standalone function needs no database, so management-only hosts can use it. It runs synchronously and starts no work.

EventDescription fieldTypeMeaning
typestringThe event name
schemaRecord<string, unknown> | nullOutput JSON Schema, or null

type is the key from the event map. schema describes the validated output. It is null when the validator does not implement Standard JSON Schema.

DescribeEventsOptions fieldDefaultContract
target'draft-2020-12'JSON Schema dialect
libraryOptionsNonePassed to the converter unchanged

target must be a nonempty string, such as 'draft-07'. libraryOptions must be an object, such as Zod's { unrepresentable: 'any' }. It goes to every event's converter, and is omitted from the call when not set.

The schema comes from the validator's ~standard.jsonSchema.output(). In Zod and ArkType, a field with a default is therefore required. Good Webhooks imports no validator library. The publish guide lists which validators support it and their libraryOptions.

  • An invalid event map throws INVALID_CONFIG, as in createWebhooks().
  • Options that are not an object, a target that is not a nonempty string, or libraryOptions that are not an object throw INVALID_INPUT.
  • A validator that cannot convert its schema, for example a transform or a date, throws INVALID_CONFIG naming the event.
    • The validator's error is the cause.
  • A target the validator rejects throws the same way.
    • Zod accepts unknown targets and omits $schema.

generateEncryptionKey

generateEncryptionKey(): string
import { generateEncryptionKey } from 'good-webhooks'

console.log(generateEncryptionKey()) // Store once in your secret manager.

Returns 32 cryptographically random bytes encoded as base64. The key is the storage encryption key for standalone management signing secrets. It is distinct from the endpoint's whsec_ signing secret. Keep it outside the database.

Other root exports

ExportDocumented at
createDeliveryDelivery entry point
verifyWebhookReceiver entry point
WebhookErrorErrors

parseWebhook is available only from good-webhooks/verify.

The root also exports these types:

  • Events: EventDefinitions, EventName, EventDescription, DescribeEventsOptions, JsonValue, PublishInput, PublishOptions, PublishResult
  • Database: SqlClient, DatabaseClient, Database, QueryResult
  • Endpoints: Endpoint, EndpointStatus, PauseReason, EndpointWithSecret, EndpointInput, EndpointPatch
  • Delivery: Delivery, DeliveryDetail, DeliveryStatus, DeliveryQuery, DeliveryStats, ReplayManyInput, ReplayManyResult, Attempt, Page, WorkerResult, DeliveryOptions, DeliveryEngine, DeliveryHooks, AttemptEvent, EndpointPausedEvent, EndpointHealthOptions
  • Composition: WebhookOptions, Webhooks, WebhookClient, EndpointManagement, EndpointSource, EndpointResolution, AutomaticPauseInput, AutomaticPauseReason, ManagementScope, Scope
  • Errors: WebhookErrorCode

Database adapters

A node-postgres Pool satisfies Database. Another driver needs an adapter that behaves like node-postgres:

  • A failed query rejects with the PostgreSQL SQLSTATE in error.code. For example, 25P01 becomes TRANSACTION_REQUIRED.
  • timestamptz columns read as Date values.
  • text[] columns read as arrays of strings.
  • integer columns read as numbers.
  • connect() returns a client pinned to one session until release(). BEGIN, SAVEPOINT, and advisory transaction locks depend on it.

On this page