Better Auth
The server plugin, its authenticated routes, the trusted management provider, and the client plugin.
good-webhooks/better-auth adds authenticated endpoint management routes to Better Auth and exposes the same storage as a trusted provider. good-webhooks/better-auth/client is the matching client plugin.
import { goodWebhooks, createBetterAuthManagement } from 'good-webhooks/better-auth'
import type {
GoodWebhooksOptions,
WebhookEndpointDTO,
ManagementAction,
ScopeAuthorization,
ScopePolicy,
BetterAuthManagementSchemaOptions,
WebhookEndpointField,
} from 'good-webhooks/better-auth'The optional peer range is >=1.7.7 <1.8.0 || >=1.8.0-beta.0 <1.9.0-0, tested on 1.7.7 and the newest 1.7 and 1.8 releases with these databases. For setup steps, see the plugin guide.
goodWebhooks
goodWebhooks<const EventTypes extends readonly string[]>(
options: GoodWebhooksOptions<EventTypes>,
)import { betterAuth } from 'better-auth'
import { goodWebhooks } from 'good-webhooks/better-auth'
import { database } from './database.js' // Your existing database or adapter.
export const auth = betterAuth({
database,
secret: process.env.BETTER_AUTH_SECRET!,
plugins: [goodWebhooks({ eventTypes: ['invoice.created', 'invoice.paid'] as const })],
})Returns the good-webhooks Better Auth server plugin. It adds one management model and nine authenticated POST routes. It does not publish events, create delivery storage, or start a worker.
eventTypes: required configured event names. A literal tuple preserves names in server and client types.allowLocalhost: optional boolean, defaultfalse. Permits development HTTP loopback destinations.schema.modelName: optional physical model name, defaultwebhookEndpoint. This is not a PostgreSQL namespace.schema.fields: optional mapping from logical fields to physical field names.schemahas the typeBetterAuthManagementSchemaOptions, andWebhookEndpointFieldnames the logical fields.
authorizeScope: optional policy required for application and custom scopes. It cannot override user or organization rules.maxEndpoints: optional(scope) => number | Promise<number>from 0 to 1,000, default 1,000. It sets the most endpoints a scope may have.
Storage model
Schema field names are scopeKey, allocationKey, creationToken, url, description, eventTypes, additionalEventTypes, status, pauseReason, encryptedSecret, previousEncryptedSecret, previousSecretExpiresAt, encryptedHeaders, revision, createdAt, and updatedAt. encryptedHeaders is an optional string, never accepted as input or returned. It holds the endpoint headers as one encrypted value, and is empty when there are none.
The plugin declares a unique allocationKey index for the per-scope endpoint limit. Generated fields and indexes are part of the storage contract. The host runs Better Auth's migration or schema-generation workflow. Standalone management.sql does not create this model.
Signing secrets and endpoint headers are encrypted with the auth instance's secret configuration. Unlike the PostgreSQL provider, this provider does not resolve hostnames at registration. The worker still checks each destination before connecting.
Authenticated routes
import { auth } from './auth.js'
export async function createEndpoint(request: Request) {
return auth.api.createWebhookEndpoint({
headers: request.headers,
body: { url: 'https://receiver.example/webhooks', eventTypes: ['invoice.paid'] },
})
}Each route lives under Better Auth's configured base path. Every route uses sensitive session middleware and disables response storage. Server calls use auth.api.<method>({ body, headers }) with the caller's session headers. Browsers use the client plugin.
| Server method | POST path | Action |
|---|---|---|
createWebhookEndpoint | /good-webhooks/create | create |
listWebhookEndpoints | /good-webhooks/list | read |
getWebhookEndpoint | /good-webhooks/get | read |
updateWebhookEndpoint | /good-webhooks/update | update |
pauseWebhookEndpoint | /good-webhooks/pause | update |
resumeWebhookEndpoint | /good-webhooks/resume | update |
removeWebhookEndpoint | /good-webhooks/remove | delete |
rotateWebhookEndpointSecret | /good-webhooks/rotate-secret | update |
sendWebhookEndpointTestEvent | /good-webhooks/send-test-event | update |
Every body accepts scope?. The other body fields and the result of each method:
createWebhookEndpoint: bodyurl,eventTypes,description?. Returns{ endpoint, secret }.listWebhookEndpoints: no other body fields. ReturnsWebhookEndpointDTO[].getWebhookEndpoint: bodyid. ReturnsWebhookEndpointDTO.updateWebhookEndpoint: bodyid,url?,description?,eventTypes?. ReturnsWebhookEndpointDTO.pauseWebhookEndpoint: bodyid. ReturnsWebhookEndpointDTO.resumeWebhookEndpoint: bodyid. ReturnsWebhookEndpointDTO.removeWebhookEndpoint: bodyid. ReturnsWebhookEndpointDTO.rotateWebhookEndpointSecret: bodyid,graceMs?. Returns{ endpoint, secret }.sendWebhookEndpointTestEvent: bodyid. ReturnsTestEventResult.
scope accepts { type, id }, null, or omission. Bodies reject unknown fields. Create and update bodies also accept optional headers. Creation and updates use the management input limits. An update accepts description: null to clear the value, and headers: null or {} to remove every header. A new headers object replaces the whole set. Rotation accepts an integer graceMs from 0 through 86,400,000, defaulting to 86,400,000.
The test event route returns the receiver's answer with status 200 even when the receiver fails; see test events. Each call makes your server send a request, so the plugin rate-limits the route to 10 requests per 60 seconds. Better Auth applies plugin rate limits only when its rate limiter is on, which by default means production. Your own rateLimit.customRules replace plugin rules for the paths they match, and the first matching key wins, so a wildcard such as '/good-webhooks/*' also replaces this limit. List '/good-webhooks/send-test-event' before it to keep one.
WebhookEndpointDTO<EventType> contains id, url, nullable description, eventTypes, status, pauseReason, headers, createdAt, and updatedAt. headers is always present, {} when there are none, and returns the values the owner set. Its timestamps are ISO strings, unlike trusted provider results, which contain Date values. Ordinary route results contain no signing material. Creation and rotation return the new secret separately.
Scope authorization
Every route resolves an omitted scope to { type: 'user', id: session.user.id }, then authorizes the requested scope and action as the permissions guide describes. Application scope (null) and custom scope types need authorizeScope.
type ManagementAction = 'create' | 'read' | 'update' | 'delete'
interface ScopeAuthorization {
scope: ManagementScope
action: ManagementAction
user: User
session: Session
}
type ScopePolicy = (input: ScopeAuthorization) => boolean | Promise<boolean>import { goodWebhooks, type ScopePolicy } from 'good-webhooks/better-auth'
const authorizeScope: ScopePolicy = ({ scope, action, user }) =>
scope === null && action === 'read' && user.emailVerified
export const plugin = goodWebhooks({ eventTypes: ['invoice.paid'] as const, authorizeScope })The policy defaults to denial and never overrides user or organization authorization. A policy that throws an error other than an APIError produces a 500. API keys do not authenticate these routes.
Route errors
| Condition | HTTP status |
|---|---|
| Missing session | 401 |
| Unauthorized scope or action | 403 |
INVALID_INPUT or UNSAFE_URL | 400 |
NOT_FOUND | 404 |
INVALID_STATE or ENDPOINT_LIMIT | 409 |
Other WebhookError | 500 with the message Webhook management failed. |
Better Auth validates request bodies and handles errors outside this mapping. The Good Webhooks error code remains in mapped error bodies.
createBetterAuthManagement
createBetterAuthManagement(auth: { $context: Promise<object> }): Promise<EndpointManagement>import { createBetterAuthManagement } from 'good-webhooks/better-auth'
import { auth } from './auth.js'
const management = await createBetterAuthManagement(auth)
await management.removeScope({ type: 'organization', id: 'org_123' })Returns the same trusted management provider installed by goodWebhooks. A missing plugin produces INVALID_CONFIG.
This helper needs neither a session nor an HTTP listener. Direct calls bypass route authorization. It uses Better Auth's adapter and encryption helpers with the auth instance's secret configuration. App and worker must share compatible configuration, storage, and decryption keys. See add delivery to Better Auth.
The provider exposes every EndpointManagement operation, including removeScope and reencrypt, plus source for a sender. There are no HTTP routes for removeScope or reencrypt.
Client plugin
The client plugin gives a Better Auth client typed methods for the plugin's routes.
goodWebhooksClient<const EventTypes extends readonly string[] = readonly string[]>(
options?: { eventTypes: EventTypes },
)import { createAuthClient } from 'better-auth/client'
import { goodWebhooksClient } from 'good-webhooks/better-auth/client'
const eventTypes = ['invoice.created', 'invoice.paid'] as const
export const authClient = createAuthClient({
plugins: [goodWebhooksClient({ eventTypes })],
})Returns a Better Auth client plugin for createAuthClient.
eventTypes is an optional tuple that carries the server's event-name literals into client types. Omitting it leaves event names typed as string. It does not change the server's configured names or authorize requests.
The dedicated client entry point has no runtime import of the server plugin, database driver, or delivery worker. It configures all Good Webhooks route methods as POST and preserves JSON values with JSON.parse, including descriptions that look like dates.
Client methods
import { authClient } from './auth-client.js'
const { data, error } = await authClient.goodWebhooks.create({
url: 'https://receiver.example/webhooks',
eventTypes: ['invoice.paid'],
})
if (error) throw new Error(error.message)
console.log(data.secret) // Show once. No later response contains it.All methods return Better Auth's client result containing data and error. Request bodies and data shapes match the server routes. create and update accept headers like the server routes, and WebhookEndpointDTO.headers is always present.
| Client method | Server method | data |
|---|---|---|
create | createWebhookEndpoint | { endpoint, secret } |
list | listWebhookEndpoints | WebhookEndpointDTO[] |
get | getWebhookEndpoint | WebhookEndpointDTO |
update | updateWebhookEndpoint | WebhookEndpointDTO |
pause | pauseWebhookEndpoint | WebhookEndpointDTO |
resume | resumeWebhookEndpoint | WebhookEndpointDTO |
remove | removeWebhookEndpoint | WebhookEndpointDTO |
rotateSecret | rotateWebhookEndpointSecret | { endpoint, secret } |
sendTestEvent | sendWebhookEndpointTestEvent | TestEventResult |
Call each client method as authClient.goodWebhooks.<method>(input), for example authClient.goodWebhooks.rotateSecret(input).
Each input accepts optional scope. Omission selects the signed-in user's personal scope. scope: null requests application scope and requires server policy. The client does not weaken server authorization. See scope authorization.
Endpoint timestamps remain ISO strings.
Inference example
This compile-only example checks the public server and client types. It omits the database and session setup required by a running application. The Better Auth quick start provides that setup.
const eventTypes = ['invoice.created', 'invoice.paid'] as const
const auth = betterAuth({ plugins: [goodWebhooks({ eventTypes })] })
const client = createAuthClient({ plugins: [goodWebhooksClient({ eventTypes })] })
const result = await client.goodWebhooks.create({
url: 'https://receiver.example/hook',
eventTypes: ['invoice.created'],
})The same event-name tuple restricts both APIs to invoice.created and invoice.paid. Unknown names fail typechecking.