Run your code at a hook point (hooks)
For: an app developer who must write a row of the app, refuse a write, or audit an event at a core flow.
What it does: core calls your function at a named hook point of a flow. A before hook can refuse the flow. An after hook runs after the commit.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
organizationsin the config for an organization hook. Organizations lists its keys.
- Pass plain objects of functions in
hooks.organization,hooks.session,hooks.user,hooks.identity,hooks.operator,hooks.sso,hooks.scim, andhooks.anonymous. - To refuse, throw
hookRefusal(message)in a before hook. The caller getshook_refusedwith your message. - To write the app’s own row with each core row, write it in the before hook.
- The app’s row takes the id that core minted, so the two rows match.
- To store no IP or user agent, answer
{ ip: null, userAgent: null }fromsession.beforeCreate. - For an audit trail, write from the after hooks.
import { createAuth, hookRefusal, type MailPort, type StorageAdapter } from "@authtempo/core";
/** The app's audit trail. A real app writes its own table. */export const auditLog: string[] = [];
export function createHooksAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string }) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, organizations: {}, hooks: { organization: { // A before hook runs inside the flow's transaction, after core's own checks. async beforeCreate({ organization }) { if (organization.slug.startsWith("acme-")) throw hookRefusal("Choose another name."); }, // An after hook runs after the commit. A throw here is logged, never answered. async afterAddMember({ organization, member, via }) { auditLog.push(`member.added ${organization.id} ${member.userId} ${via}`); }, }, session: { // Store no IP and no user agent with the session. beforeCreate: () => ({ ip: null, userAgent: null }), async afterEnd({ session, reason }) { auditLog.push(`session.ended ${session.id} ${reason}`); }, }, }, });}import { describe, expect, it } from "vitest";import { call, harness, signIn } from "../support/harness.ts";import { auditLog, createHooksAuth } from "./hooks.ts";
describe("run your code at a hook point", () => { it("refuses with the app's message, and records the after events", async () => { auditLog.length = 0; const h = harness(); const auth = createHooksAuth(h); const ada = await signIn(auth, h, "ada@example.com");
const refused = await call( auth, "POST", "/auth/organizations/create", { slug: "acme-x", name: "X" }, { cookie: ada }, ); expect(refused.status).toBe(403); expect(await refused.json()).toEqual({ error: "hook_refused", message: "Choose another name.", });
const made = await call( auth, "POST", "/auth/organizations/create", { slug: "team", name: "Team" }, { cookie: ada }, ); expect(made.status).toBe(200); expect( auditLog.some((line) => line.startsWith("member.added ") && line.endsWith(" create")), ).toBe(true);
await call(auth, "POST", "/auth/sign-out", {}, { cookie: ada }); expect( auditLog.some((line) => line.startsWith("session.ended ") && line.endsWith(" sign_out")), ).toBe(true); });});The hook points
Section titled “The hook points”| Group | Hook points |
|---|---|
hooks.organization |
beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete, afterDelete, beforeAddMember, afterAddMember, beforeUpdateMemberRole, afterUpdateMemberRole, beforeRemoveMember, afterRemoveMember, beforeInvite, afterInvite, afterAcceptInvitation, afterDeclineInvitation, afterRevokeInvitation. With organizations.teams, also beforeCreateTeam, afterCreateTeam, beforeUpdateTeam, afterUpdateTeam, beforeDeleteTeam, afterDeleteTeam, beforeAddTeamMember, afterAddTeamMember, beforeRemoveTeamMember, afterRemoveTeamMember |
hooks.session |
beforeCreate, afterCreate, afterEnd |
hooks.user |
beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete, afterDelete, beforeVerify, afterVerify |
hooks.identity |
beforeLink, afterLink, beforeUnlink, afterUnlink |
hooks.operator |
beforeAction, afterAction |
hooks.sso |
beforeSignIn |
hooks.scim |
afterChange |
hooks.anonymous |
beforeLink, afterLink |
hooks.request |
before, after |
via of a member |
create, add, invitation, operator, sso, scim; for a removal remove, leave, operator, or scim |
via of a session |
password, magic_link, social, passkey, handoff, email_otp, impersonation, sso, phone, anonymous, invite |
via of a user create |
the via of the sign-in, password_reset for a reset that creates the user, operator for createAdmin, or scim for a create by the directory |
via of a user update |
profile, email_change, ban, unban, scim, username, phone, operator |
via of a user verify |
password_verify, magic_link, email_otp, social, password_reset, sso, scim, invite |
via of an identity link |
sign_in for a social sign-in, link for the link of a signed-in user |
reason of afterEnd |
sign_out, password_reset, password_change, claim, expired, two_factor, revoked, email_change, account_deleted, oidc_logout, banned, operator, impersonation_end, displaced, anonymous_upgrade, claimed, capped |
How it behaves
Section titled “How it behaves”- A before hook runs inside the flow’s transaction, after the rank checks and the limits, and before the first write. The one exception is a lock write: some flows lock a row before the hook, as Locks over a before hook lists. A throw leaves no row and no change of a locked row.
- An after hook runs after the commit, before the answer. A throw cannot undo the row: core logs one line and answers success.
- A cascade fires no team hook. A member removal, a team delete, and an organization delete remove team rows with no team hook. The default team of an organization create and the team rows of an accept fire none either.
- Each hook gets a copy of its event. Only two hooks may change a row.
session.beforeCreatemay changeip,userAgent, andactiveOrganizationId.user.beforeCreatemay changenameandimage. - Answer a plain object. Core reads its own enumerable fields only. A class instance or another object that is not plain answers
hook_failed. - In one sign-in that creates a user, the order is
user.beforeCreate,identity.beforeLink, andsession.beforeCreate, all before the first write. After the commit, the order isuser.afterCreate,identity.afterLink, andsession.afterCreate. - In an SSO sign-in that adds a member row, the order is
sso.beforeSignIn,organization.beforeAddMember, andsession.beforeCreate. All three run before the first write, by the first rule of this list. - A flow that moves an existing user from
emailVerified: falseto true runsuser.beforeVerifyanduser.afterVerifyonce. They take the place ofuser.beforeCreateanduser.afterCreatein that order. user.beforeVerifysees the stored row, still unverified. A refusal leaves the user unverified. The magic link, the email code, the verify link, and social spend their proof first, so a refusal spends it. The reset keeps its link.- Two proofs of one user at once both run
user.beforeVerify. One claims the user and runsuser.afterVerify. The other finds the user verified. The magic link, the email code, social, and the reset sign in that user. The verify link opens no session. It answersinvalid_tokenwhen the claim deleted the user’s password. So a before can have no after. - A claim is final once its last write is done. When the flow fails after that point, the claim stays. Before its error answer, the flow runs
user.afterVerify,session.afterEndwith reasonclaim, andoperator.afterActionfor each stop row. On Postgres and MySQL such a failure undoes the whole claim, so no after point runs. On D1 and SQLite a claim is final already at its mark of the address. When a later step of the claim fails, the claim stays, and none of these after points run. - A sign-out of a claimant session during a claim fires
session.afterEndonce, withsign_out. The claim fires no secondafterEndfor that session, and goes on. - A user that a flow creates verified fires the create hook points, not the verify hook points. The change of address fires the update hook points.
- The sign-up rule runs before
user.beforeCreate. So no user hook sees a create thatsignUprefuses. - A claim fires the verify hook points only. The
emailidentity, the social fill of the name and the image, the sweep, and the importer fire no user or identity hook. user.beforeUpdatecan run more than once for one change, withvia: "profile"and withvia: "email_change".- A parallel write that lands first makes core read the user row again. Then
user.beforeUpdateruns again on the new row. Write the hook so that a second call does no harm. - A SCIM deactivate or delete that a group write races reads the member row again. Then
organization.beforeRemoveMemberruns again with the new role, up to 5 times. identity.beforeLinkwithvia: "link"runs inside the transaction of the link, before the identity write.- It can run twice for one identity, when two link states of one user race. The second write then fails.
identity.beforeUnlinkruns inside the transaction, after core counts the ways in and locks the user row, and before the first delete. It has novia.- An unlink that
last_credentialrefuses runs no hook.identity.afterUnlinkruns after the commit. - The account delete runs
organization.beforeDeletefor each organization that goes, thenuser.beforeDeletewith the ids of those organizations. Both run inside the transaction, before the first delete. - After the commit of the delete,
session.afterEndfires withaccount_deletedfor the sessions that the delete ended. On the D1 storage of the compatibility package, that is one page of sessions. On the Postgres and SQLite storages of that package, that is up to 500 of the user’s own sessions. In both cases, the cascade of the Better Auth tables deletes the rest with no hook. With the impersonation tool on, the delete records the impersonation sessions that the cascade ends. The sweep writes theirimpersonation_stoprows from its next run. A delete of a user with more than 100 live impersonation sessions answersdelete_too_largeand changes nothing. Thenorganization.afterDeleteanduser.afterDeletefire. - The rows that the delete removes fire no member or identity hook.
- A refusal message of 1 to 200 characters with no control character reaches the caller. Any other message becomes “The app refused this request.”.
- Hooks have no timeout. A hook that never settles holds the request, and a before hook holds the transaction.
- The sweep fires two hooks.
session.afterEndfires for each session that an act left for it, with the reason of that act:banned,operator,account_deleted,impersonation_end,revoked, orclaimed.user.afterDeletefires once for each anonymous user that it deletes.expiredfires only when a request presents a token after its expiry. - Core has no request hooks. Wrap
auth.handle, and readauth.caller(request).
The SSO hook point
Section titled “The SSO hook point”hooks.ssoneedssso.beforeSignIngets the connection, the profile from the provider, and the user that the sign-in answers. The user is null when the sign-in creates the user.- It runs in the sign-in’s transaction, before its first write. A refusal answers
hook_refused, and the sign-in writes nothing.
The request points
Section titled “The request points”hooks.requestneeds no feature.beforeandafterrun inhandle, around the handler of each matched route.- They run after each rule of the router: the host rule, the Origin rule, and the impersonation and anonymous refusals. A request that the router refused runs no hook.
- An in-process call of
auth.apiruns neither point. - Each point gets
route,params,url,headers,ip, andjson().routeis the route key, such asPOST /magic-link/request. json()answers the JSON body, read through the cap of the route. The handler then reads the same bytes.json()answersundefinedfor a body that is not JSON. It answers the same on the SCIM routes, on the SAML ACS, and on the two SSO connection writes. These routes read their body with a cap of their own.- A
hookRefusalinbeforeanswers 403hook_refusedwith the message, and the handler does not run. Any other throw answers 500hook_failedand writes one line. afteralso getsstatusandcode. It cannot change the answer. A throw in it writes one line, and the answer stays.- Each value is new for the hook. A change of the headers, the URL, or the body changes nothing of the request.
A request hook never widens a rule or a limit of core. Use it to refuse a request for a reason of your app.
The operator hook points
Section titled “The operator hook points”hooks.operatorneedsoperator.users. Run the operator tools turns the tools on.beforeActiongets the audit row of the act, with no id yet. It runs before the act’s transaction, so before its first write. A refusal answershook_refused, and the act writes nothing.afterActiongets each stored audit row once, after the commit. A throw writes one log line, and the act stays. Send the row to a separate system here.afterActionalso gets eachimpersonation_stoprow that another flow writes, such as the user’s end of an impersonation session. NobeforeActionruns for such a row.- In the six member hook points,
byis null for an act of an operator secret or of the app. Those acts have no user. via: "operator"of a member is the grant or the revoke of the platform role, orcreateAdmin.banned: a ban, or a session of a banned user that a request or the sweep ends.operator: an operator ends the sessions of a user or of all users, or revokes the platform role.banned,operator, andaccount_deletedalso end the impersonation sessions that the user opened as an operator. Each of those sessions belongs to another user, soafterEndgets the session of that user.impersonation_endhas three causes:- the stop of an impersonation;
- the loss of the platform role at a removal, a leave, or a role change of a platform operator’s member row;
- the door of a request: the operator of the impersonation session is banned, deleted, or without the platform role.
displaced: withmultiSessionon, a sign-in in a browser whose bag is full ends the oldest session of the bag. A sign-in of a user who has a session in the browser ends that session withsign_out.user.beforeUpdatewithvia: "ban"can run more than once for one ban, when a parallel write lands first.anonymous_upgrade: a sign-in replaced the anonymous user of the session. See The anonymous upgrade.claimed: a session read found a session from before the proof of its user’s address, after the proof, and ended it. The session proof tells why. The sweep also ends with it a session that a claim left. With this hook on D1, SQLite, and the memory store, a claim ends at most 100 sessions in its own request, withclaim. The sessions of a claimant tells why.capped: a session create ended the oldest session of the user pastsession.maxPerUser. It fires after the commit, beforeafterCreateof the new session.
The anonymous upgrade
Section titled “The anonymous upgrade”A sign-in from a browser with a live anonymous session replaces the anonymous user. Core never changes the anonymous user into the user of the sign-in.
- These sign-ins link: the password sign-in, the password sign-up and its confirm, the magic link, the email code, and the phone code. A social sign-in, a passkey sign-in, and the challenge verify of a gated sign-in also link.
- An SSO sign-in, a password reset that opens a session, and a handoff link nothing. Their session replaces the cookie. The anonymous user stays with no hook, and the sweep deletes it and its data.
- With
anonymousoff, nothing links. This includes a sign-in that started before the deployment turnedanonymousoff. - The event holds
anonymousUser,user,proof, andvia.useris the account that the person signed in to. beforeLinkruns in the sign-in’s transaction, before the session write. A refusal answershook_refused, and no session opens. The anonymous user and its session stay.afterLinkruns after the commit. Move the app’s data here. Then the anonymous session ends withanonymous_upgrade, and the anonymous user goes.user.afterDeleteruns for it, anduser.beforeDeletedoes not.- A throw of
afterLinkwrites the linehook.after_failed, with the anonymous user’s id asrowId. The anonymous user and its session stay, but no later sign-in links them: the upgrade spent the claim. When the anonymous session expires andanonymous.ttlDayspass, the sweep deletes the user. Act on the line: move the data before that sweep. The sweep firesuser.afterDeletefor the user. - A failure after
afterLink, at the session end or the delete, writes the lineanonymous.cleanup_failed. The sign-in still answers with its session. The sweep deletes the anonymous user later. afterLinkruns in the request of the sign-in. On D1, its queries count toward the 50 queries of that invocation, with those of the sign-in. The worst request is an ID-token sign-in that claims an unverified account, over an anonymous session with a fullmultiSessionbag. With every hook set, it uses 39 queries. A sign-up confirm by code withuniformSignUpon uses 38, and a password sign-in with a full bag uses 26. So on such a sign-in, hooks with more than 11 queries together can pass the D1 Free limit of 50. Then a step after them fails. The claimant’s sessions end in one query per 50 sessions, so up to 50 of them add no query.proofisunverifiedwhenuserholds an address that no proof verified. The real owner of the address can claim that account later. Move data only whenproofisverified.- A proof by mail or SMS links only when the completing request carries the anonymous session that asked for it. These proofs are the magic link, the email code, the confirm link of a sign-up, and the phone code. So a stranger cannot move data into your account with a link for your address.
- A social sign-in links the anonymous user of its start: the binding cookie ties the callback to that browser. A password sign-in, a passkey sign-in, and an ID-token sign-in link the anonymous session of their own request. A passkey sign-up links the anonymous user of its options, or else the anonymous session of its verify.
- A sign-in with the second factor links at the challenge verify. A challenge that expires links nothing.
- With
multiSessionon, the anonymous session never enters the bag, so an upgrade displaces no bag session. A switch to a bag session is no sign-in and links nothing. - Two sign-ins from one anonymous session at once: each can run
beforeLink, and one links. The other signs in with noafterLink. So move data inafterLinkonly. An impersonation session never links. - Residual:
POST /handoff/continueis open to an anonymous session, so an anonymous user can hold more than one session. An upgrade ends all of them, and with anafterEndhook each end adds queries. - Residual: a
POST /anonymous/deletein parallel with an upgrade can delete the anonymous user beforeafterLinkruns. ThenafterLinkruns afteruser.afterDelete. The same person does both, so no other person gains data.
Locks over a before hook
Section titled “Locks over a before hook”Some flows lock a row before their before hook. The lock holds until the commit. A refusal rolls back these lock writes with the transaction.
| Flow | Before hooks | Rows locked before the hook |
|---|---|---|
| Organization create | organization.beforeCreate, organization.beforeAddMember |
the creator’s user row |
| Member add | organization.beforeAddMember |
The added user’s row, and with membersPerOrganization the organization row. An SSO sign-in or a SCIM write locks none: its hook runs before any lock and write. |
| Invitation accept | organization.beforeAddMember, organization.beforeUpdateMemberRole |
the accepting user’s row; for a new member with membersPerOrganization, the organization row; each team row of the invitation |
| Invite | organization.beforeInvite |
with pendingInvitationsPerOrganization, the organization row |
| Member removal or leave | organization.beforeRemoveMember |
The person’s user row and sessions. For an owner or with revokeTokens, the organization row. For a loss of the platform role, the sessions of each impersonation that the person opened. |
| Member role change | organization.beforeUpdateMemberRole |
For an owner demotion, the organization row. For a loss of the platform role, the member’s user row and the sessions of the member and of each impersonation that the member opened. For a gain of the platform role, the member’s user row, and with an owner demotion the member’s sessions too. |
| Organization delete | organization.beforeDelete |
the sessions that act in the organization; on Postgres, the organization row |
| Team create | organization.beforeCreateTeam |
the organization row |
| Team delete | organization.beforeDeleteTeam |
the sessions that act in the team; with keepLastTeam, the organization row; on Postgres, the team row |
| Team member add | organization.beforeAddTeamMember |
the added user’s row and the team row |
| Team member removal | organization.beforeRemoveTeamMember |
the sessions of the person and the team row |
| SCIM group write | organization.beforeUpdateMemberRole |
The scimGroup row, first. The users of the added and removed members, and of each member whose role the write computes. The sessions of the persons who leave the group’s team. The organization row of a team create, or the team row. On Postgres, the member rows of each role change. |
| Identity unlink | identity.beforeUnlink |
the user’s row |
| Phone remove | user.beforeUpdate |
the user’s row |
| Account delete | organization.beforeDelete, user.beforeDelete |
the user’s row and sessions; when the user opened an impersonation, the sessions of each impersonation that the user opened |
| Anonymous delete | user.beforeDelete |
the user’s row |
| Platform role grant | organization.beforeAddMember, organization.beforeUpdateMemberRole |
the target’s user row; before organization.beforeAddMember of a new member row with membersPerOrganization set, the organization row too |
| Platform role revoke | organization.beforeRemoveMember, organization.beforeUpdateMemberRole |
the user’s row and the sessions of the user and of each impersonation that the user opened; for an owner, the organization row |
| Impersonation start | session.beforeCreate |
the operator’s user row |
- A SCIM group write runs the member role hooks with
by: null, and no team hook (plan 12d ruling 54). Its team create, rename, delete, and member changes are part of the group write, as a cascade is. An app that watches the team hooks must also watchhooks.scim.afterChange, which reports each group write after its commit. - On Postgres a slow before hook in one of these flows blocks every other write of its locked rows until the commit. A sign-in of a verified user writes its user row, so it waits too.
- A passkey sign-in moves the passkey counter outside the transaction of the session. No lock of the passkey row holds while
session.beforeCreateruns. - The sweep deletes anonymous users past
anonymous.ttlDayswith nouser.beforeDelete: the user did not ask for the delete. It firesuser.afterDeleteonce for each deleted user, outside the call budget of the sweep. See the sweep.
If it fails
Section titled “If it fails”hook_refused: a before hook threwhookRefusal(message). The body carriesmessage.hook_failed: a before hook threw another error, or a session patch or a user patch was wrong.not_found: a session patch named an organization that the user is not a member of.
createAuth refuses a hook that is not a function and a name that is no hook point. It also refuses a group that core does not have, and organization hooks while organizations is off.