Every export is server-side. auth is your betterAuth() instance: pass the real instance, not auth.$context.
| Export | Kind | Input | Returns |
|---|---|---|---|
createEventBus |
function | consumers: ByoEventHandler[] | ByoEventHandler, { onError? } |
ByoEventHandler: runs each consumer in order, awaited, and never throws or rejects |
sweepAll |
function | auth, { budgetMs?, now?, onError? } |
{ results: { pluginId, runs, last?, error? }[]; hasMore: boolean; timedOut: boolean } |
deleteOrganizationData |
function | auth, organizationId: string |
Promise<void>; throws ByoFanOutError after all plugins ran if any failed |
deleteMemberData |
function | auth, { userId, organizationId } |
Promise<void>; same failure rule |
listByoPlugins |
function | auth |
{ id, hooks: ("sweep" | "deleteOrganizationData" | "deleteMemberData")[] }[] |
ByoFanOutError |
class | AggregateError with hook, failures: { pluginId, error }[], and one wrapped Error per failure in errors (cause is the original) |
|
ByoEvent |
type | The event shape every BYO plugin emits | |
ByoEventHandler |
type | (event: ByoEvent) => void | Promise<void> |
|
ByoPlugin<P> |
type | P & { byo?: ByoPluginHooks } |
|
ByoPluginHooks |
type | { sweep?, deleteOrganizationData?, deleteMemberData? } |
|
ByoSweepResult |
type | { hasMore: boolean } & Record<string, number | boolean> |
|
ByoAuth |
type | { options: { plugins?: readonly unknown[] }; $context: Promise<object> }. Any betterAuth() instance assigns to it. |
createEventBus
createEventBus(consumers, options?) returns the handler you pass as onEvent to every BYO plugin that takes one.
| Option | Default | Notes |
|---|---|---|
onError |
console.error with a [@byo-oss/core] prefix |
(error, event, consumerIndex) => void | Promise<void>. Called once per failing consumer. If it throws, that goes to console.error too. |
- Consumers run one after another, in the order given. The list is copied when the bus is created.
- A consumer that throws or rejects is reported through
onError, and the next consumer still runs. The bus never fails the request that emitted the event.
The event every consumer receives:
type ByoEvent = {
type: `${string}.${string}.${string}` // "<package>.<noun>.<past-tense verb>"; <package> is the package name without the scope, e.g. "support.ticket.created", "notifications.notification.created"
occurredAt: Date
actorId: string | null // a user id, or null for the system
userId?: string // whom it's about, if one person
organizationId?: string
subject: { type: string; id: string } // e.g. { type: "supportTicket", id }
data: Record<string, unknown> // ids, statuses, kinds; never bodies
}Events are in-process and best-effort. Nothing is retried or stored, so a consumer that needs durability writes its own rows.
sweepAll
sweepAll(auth, options?) runs the byo.sweep hook of every plugin that declares one.
| Option | Default | Notes |
|---|---|---|
budgetMs |
25_000 |
Total time across all plugins, checked before every call. A call already running can overrun it, so pick a value below your platform’s timeout. |
now |
Date.now |
Clock in ms, for tests. |
onError |
console.error with a [@byo-oss/core] prefix |
(error, pluginId) => void. Called when a plugin’s sweep throws. |
- Plugins run in
betterAuth({ plugins })order. Each plugin’sbyo.sweepis called again while it returnshasMore: trueand the budget remains, then the next plugin runs. - A plugin that throws is recorded in its result, reported, and skipped for the rest of the call. The other plugins still run.
- A plugin not reached before the budget ran out is listed with
runs: 0, and the result hastimedOut: trueandhasMore: true. - A plugin that threw doesn’t count toward
hasMore, so a caller that re-runs onhasMorecan’t spin on a broken plugin. - Plugins run in order, so a busy plugin can use the whole budget.
hasMore: truemeans call again soon. sweepAlladds no guarantee of its own. Leases, retries, backoff and at-least-once delivery belong to each plugin’s sweep and are documented in that plugin’s README. Overlapping calls are as safe as each plugin’s sweep, which the BYO conventions require to be lease-based.
deleteOrganizationData and deleteMemberData
deleteOrganizationData(auth, organizationId) and deleteMemberData(auth, { userId, organizationId }) call each plugin’s matching byo hook.
- Each plugin’s hook is called in plugin order, one at a time. Every plugin runs even if an earlier one throws.
- Afterwards, if any failed, the call throws a
ByoFanOutError(anAggregateErrorwith a[@byo-oss/core]message naming the plugins), so you notice. Log it, or let it fail the job so it gets retried. - If no plugin declares the hook, the call does nothing.
- Outside a transaction, the cleanups that succeeded stay done when the call throws.
Core opens no transaction. BYO plugins resolve their adapter with better-auth’s getCurrentAdapter, so calling the fan-out inside your transaction (runWithTransaction, or a hook better-auth runs in one) runs every plugin’s cleanup on that transaction, and the thrown error rolls all of them back. better-auth doesn’t re-export runWithTransaction: import it from @better-auth/core/context, and install @better-auth/core at the same version as better-auth.
Leaving an organization fires no organizationHooks. Call deleteMemberData yourself after a leave if you need it, or rely on plugins that clean up through their own /organization/leave hook.
Hooks for plugin authors
A BYO plugin declares its hooks under a byo key, and core’s helpers call them. better-auth ignores byo at runtime and keeps your object as given in auth.options.plugins. End the plugin object with satisfies ByoPlugin<BetterAuthPlugin>: satisfies BetterAuthPlugin alone rejects the extra key.
import type { BetterAuthPlugin } from "better-auth";
import type { ByoPlugin } from "@byo-oss/core";
export const feedback = (options: FeedbackOptions = {}) =>
({
id: "feedback",
endpoints: { /* ... */ },
byo: {
sweep: (auth) => processFeedbackDigests(auth), // returns { sent, failed, hasMore }
deleteOrganizationData: async (auth, organizationId) => {
await deleteFeedbackOrgData(auth, organizationId);
},
deleteMemberData: async (auth, { userId, organizationId }) => {
await deleteFeedbackMemberData(auth, { userId, organizationId });
},
},
}) satisfies ByoPlugin<BetterAuthPlugin>;- Every hook is optional. Declare only what the plugin has.
- Inside a hook, read the adapter with
getCurrentAdapter((await auth.$context).adapter), so the hook joins the caller’s transaction. - A sweep returns counts plus
hasMore, typed asByoSweepResult. Declare its result as atype, not aninterface, so it assigns toByoSweepResult. - A cleanup hook returns
Promise<void>and throws on failure. Wrap functions that return counts:async (...) => { await fn(...) }. - Keep exporting your own
deleteOrganizationData/deleteMemberDataand sweep endpoint.byois a way to reach them, not a replacement. - Depend on
@byo-oss/corefor the types and helpers. It has no runtime dependency on better-auth.