Skip to content

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.

  1. Pass plain objects of functions in hooks.organization, hooks.session, hooks.user, hooks.identity, hooks.operator, hooks.sso, hooks.scim, and hooks.anonymous.
  2. To refuse, throw hookRefusal(message) in a before hook. The caller gets hook_refused with your message.
  3. 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.
  4. To store no IP or user agent, answer { ip: null, userAgent: null } from session.beforeCreate.
  5. For an audit trail, write from the after hooks.
Organization and session 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}`);
},
},
},
});
}
The hooks as a test
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);
});
});
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
  • 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.beforeCreate may change ip, userAgent, and activeOrganizationId. user.beforeCreate may change name and image.
  • 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, and session.beforeCreate, all before the first write. After the commit, the order is user.afterCreate, identity.afterLink, and session.afterCreate.
  • In an SSO sign-in that adds a member row, the order is sso.beforeSignIn, organization.beforeAddMember, and session.beforeCreate. All three run before the first write, by the first rule of this list.
  • A flow that moves an existing user from emailVerified: false to true runs user.beforeVerify and user.afterVerify once. They take the place of user.beforeCreate and user.afterCreate in that order.
  • user.beforeVerify sees 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 runs user.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 answers invalid_token when 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.afterEnd with reason claim, and operator.afterAction for 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.afterEnd once, with sign_out. The claim fires no second afterEnd for 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 that signUp refuses.
  • A claim fires the verify hook points only. The email identity, the social fill of the name and the image, the sweep, and the importer fire no user or identity hook.
  • user.beforeUpdate can run more than once for one change, with via: "profile" and with via: "email_change".
  • A parallel write that lands first makes core read the user row again. Then user.beforeUpdate runs 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.beforeRemoveMember runs again with the new role, up to 5 times.
  • identity.beforeLink with via: "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.beforeUnlink runs inside the transaction, after core counts the ways in and locks the user row, and before the first delete. It has no via.
  • An unlink that last_credential refuses runs no hook. identity.afterUnlink runs after the commit.
  • The account delete runs organization.beforeDelete for each organization that goes, then user.beforeDelete with the ids of those organizations. Both run inside the transaction, before the first delete.
  • After the commit of the delete, session.afterEnd fires with account_deleted for 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 their impersonation_stop rows from its next run. A delete of a user with more than 100 live impersonation sessions answers delete_too_large and changes nothing. Then organization.afterDelete and user.afterDelete fire.
  • 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.afterEnd fires for each session that an act left for it, with the reason of that act: banned, operator, account_deleted, impersonation_end, revoked, or claimed. user.afterDelete fires once for each anonymous user that it deletes. expired fires only when a request presents a token after its expiry.
  • Core has no request hooks. Wrap auth.handle, and read auth.caller(request).
  • hooks.sso needs sso.
  • beforeSignIn gets 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.
  • hooks.request needs no feature. before and after run in handle, 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.api runs neither point.
  • Each point gets route, params, url, headers, ip, and json(). route is the route key, such as POST /magic-link/request.
  • json() answers the JSON body, read through the cap of the route. The handler then reads the same bytes.
  • json() answers undefined for 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 hookRefusal in before answers 403 hook_refused with the message, and the handler does not run. Any other throw answers 500 hook_failed and writes one line.
  • after also gets status and code. 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.

  • hooks.operator needs operator.users. Run the operator tools turns the tools on.
  • beforeAction gets the audit row of the act, with no id yet. It runs before the act’s transaction, so before its first write. A refusal answers hook_refused, and the act writes nothing.
  • afterAction gets 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.
  • afterAction also gets each impersonation_stop row that another flow writes, such as the user’s end of an impersonation session. No beforeAction runs for such a row.
  • In the six member hook points, by is 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, or createAdmin.
  • 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, and account_deleted also end the impersonation sessions that the user opened as an operator. Each of those sessions belongs to another user, so afterEnd gets the session of that user.
  • impersonation_end has 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: with multiSession on, 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 with sign_out.
  • user.beforeUpdate with via: "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, with claim. The sessions of a claimant tells why.
  • capped: a session create ended the oldest session of the user past session.maxPerUser. It fires after the commit, before afterCreate of the new session.

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 anonymous off, nothing links. This includes a sign-in that started before the deployment turned anonymous off.
  • The event holds anonymousUser, user, proof, and via. user is the account that the person signed in to.
  • beforeLink runs in the sign-in’s transaction, before the session write. A refusal answers hook_refused, and no session opens. The anonymous user and its session stay.
  • afterLink runs after the commit. Move the app’s data here. Then the anonymous session ends with anonymous_upgrade, and the anonymous user goes. user.afterDelete runs for it, and user.beforeDelete does not.
  • A throw of afterLink writes the line hook.after_failed, with the anonymous user’s id as rowId. The anonymous user and its session stay, but no later sign-in links them: the upgrade spent the claim. When the anonymous session expires and anonymous.ttlDays pass, the sweep deletes the user. Act on the line: move the data before that sweep. The sweep fires user.afterDelete for the user.
  • A failure after afterLink, at the session end or the delete, writes the line anonymous.cleanup_failed. The sign-in still answers with its session. The sweep deletes the anonymous user later.
  • afterLink runs 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 full multiSession bag. With every hook set, it uses 39 queries. A sign-up confirm by code with uniformSignUp on 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.
  • proof is unverified when user holds an address that no proof verified. The real owner of the address can claim that account later. Move data only when proof is verified.
  • 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 multiSession on, 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 no afterLink. So move data in afterLink only. An impersonation session never links.
  • Residual: POST /handoff/continue is open to an anonymous session, so an anonymous user can hold more than one session. An upgrade ends all of them, and with an afterEnd hook each end adds queries.
  • Residual: a POST /anonymous/delete in parallel with an upgrade can delete the anonymous user before afterLink runs. Then afterLink runs after user.afterDelete. The same person does both, so no other person gains data.

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 watch hooks.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.beforeCreate runs.
  • The sweep deletes anonymous users past anonymous.ttlDays with no user.beforeDelete: the user did not ask for the delete. It fires user.afterDelete once for each deleted user, outside the call budget of the sweep. See the sweep.
  • hook_refused: a before hook threw hookRefusal(message). The body carries message.
  • 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.