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>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:
| Field | Type |
|---|---|
encryptionKey | string | Uint8Array |
management | EndpointManagement |
maxEndpoints | EndpointLimit |
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 fromdatabase,schema, the configured event names,encryptionKey, andallowLocalhost.schemathen 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,encryptionKeyis unused, andmaxEndpointsthrowsINVALID_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 withpauseReason: '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 field | Type | Meaning |
|---|---|---|
type | string | The event name |
schema | Record<string, unknown> | null | Output 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 field | Default | Contract |
|---|---|---|
target | 'draft-2020-12' | JSON Schema dialect |
libraryOptions | None | Passed 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 increateWebhooks(). - Options that are not an object, a
targetthat is not a nonempty string, orlibraryOptionsthat are not an object throwINVALID_INPUT. - A validator that cannot convert its schema, for example a transform or a date, throws
INVALID_CONFIGnaming the event.- The validator's error is the
cause.
- The validator's error is the
- A target the validator rejects throws the same way.
- Zod accepts unknown targets and omits
$schema.
- Zod accepts unknown targets and omits
generateEncryptionKey
generateEncryptionKey(): stringimport { 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
| Export | Documented at |
|---|---|
createDelivery | Delivery entry point |
verifyWebhook | Receiver entry point |
WebhookError | Errors |
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,25P01becomesTRANSACTION_REQUIRED. timestamptzcolumns read asDatevalues.text[]columns read as arrays of strings.integercolumns read as numbers.connect()returns a client pinned to one session untilrelease().BEGIN,SAVEPOINT, and advisory transaction locks depend on it.