new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Better Auth · Concepts · all subjects

hooks

26 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Before hooks - run before endpoint execution

Before hooks run before an endpoint is executed. Use them to modify requests, pre-validate data, or return early.

After hooks - run after endpoint execution

After hooks run after an endpoint is executed. Use them to modify responses.

Before hook to enforce email domain restriction

Example showing how to use a before hook to restrict sign-up to emails ending with @example.com. The hook checks if ctx.path equals "/sign-up/email", validates that ctx.body.email ends with the required domain, and throws an APIError with status "BAD_REQUEST" if validation fails.

Before hook to modify request context

Example showing how to modify request context in a before hook. The hook checks ctx.path, and if it equals "/sign-up/email", returns an object with a context property that spreads the original ctx and modifies ctx.body to set the name field to "John Doe".

Better Auth hooks - recommended over custom endpoints

Better Auth recommends using hooks if you need to make custom adjustments to an endpoint rather than making another endpoint outside of Better Auth.

After hook to send notification on user registration

Example showing how to use an after hook to send a notification when a new user registers. The hook checks if ctx.path starts with "/sign-up", accesses the newly created session via ctx.context.newSession, and calls sendMessage with the user's name.

Handle multiple endpoints in a single hook

Each hook (before/after) takes a single createAuthMiddleware call, not an array. To run logic for different endpoints, branch on ctx.path inside that single function. Examples include checking ctx.path === "/reset-password", ctx.path.startsWith("/sign-up"), and ctx.path === "/sign-in/email" within the same hook.

ctx object properties in hooks

The ctx object passed to createAuthMiddleware provides: ctx.path (current endpoint path), ctx.body (parsed request body for POST requests), ctx.headers (request headers), ctx.request (request object, may not exist in server-only endpoints), ctx.query (query parameters), and ctx.context (auth-related context for accessing new session, auth cookies configuration, password hashing, config, and more).

Send JSON responses from hooks with ctx.json

Use ctx.json to send JSON responses from a hook. Example: return ctx.json({ message: "Hello World" });

Redirect users from hooks with ctx.redirect

Use ctx.redirect to redirect users from a hook. Throw the redirect: throw ctx.redirect("/sign-up/name");

Set and get cookies in hooks

Hooks provide methods to handle cookies: ctx.setCookie and ctx.setSignedCookie to set cookies, ctx.getCookie and ctx.getSignedCookie to get cookies. Example: ctx.setCookie("my-cookie", "value"); await ctx.setSignedCookie("my-signed-cookie", "value", ctx.context.secret, { maxAge: 1000 }); const cookie = ctx.getCookie("my-cookie");

Throw APIError from hooks for specific status codes

Use APIError to throw errors with specific status codes and messages from hooks. Example: throw new APIError("BAD_REQUEST", { message: "Invalid request" });

Access newly created session in after hooks

In after hooks, access the newly created session via ctx.context.newSession. This property only exists in after hooks.

Access returned value from previous hooks

The ctx.context.returned property contains the returned value from the hook chain, which could be a successful response or an APIError.

Access response headers from previous hooks

The ctx.context.responseHeaders property provides access to response headers added by endpoints and hooks that run before the current hook.

Access predefined auth cookies configuration

Access Better Auth's predefined cookie properties via ctx.context.authCookies. Example: const cookieName = ctx.context.authCookies.sessionToken.name;

Access secret in hooks

Access the secret for the auth instance on ctx.context.secret.

Hash and verify passwords in hooks

The password object in ctx.context provides methods to hash and verify passwords: ctx.context.password.hash to hash a given password, and ctx.context.password.verify to verify a given password and hash.

Access database adapter methods in hooks

The adapter in ctx.context exposes adapter methods used by Better Auth including findOne, findMany, create, delete, update, and updateMany. Generally, you should use your actual db instance from your ORM rather than this adapter.

Access internal adapter for specific database operations

The internal adapter in ctx.context provides calls to your database that perform specific actions like createUser, createSession, updateSession. This may be useful instead of using your db directly to get access to databaseHooks and proper secondaryStorage support.

Generate IDs in hooks with ctx.context.generateId

Use ctx.context.generateId to generate IDs for various purposes within hooks.

Schedule background tasks with runInBackground

Use ctx.context.runInBackground to schedule a task to run after the response is sent. Use for fire-and-forget operations like cleanup, analytics, and rate limit counter updates. Configure the handler in advanced.backgroundTasks option.

Schedule background tasks with runInBackgroundOrAwait

Use ctx.context.runInBackgroundOrAwait to defer a task when a handler is configured, otherwise await it. Use for operations that must complete (like sending emails) but benefit from not blocking when a handler exists. Configure the handler in advanced.backgroundTasks option.

Example of runInBackground for analytics

Example showing how to use runInBackground in an after hook to send analytics events after sign-up: if (ctx.path.startsWith("/sign-up")) { const newSession = ctx.context.newSession; if (newSession) { ctx.context.runInBackground(sendAnalyticsEvent(newSession.user.id)); } }

Example of runInBackgroundOrAwait for sending emails

Example showing how to use runInBackgroundOrAwait in an after hook to send a welcome email after sign-up: if (ctx.path.startsWith("/sign-up")) { const newSession = ctx.context.newSession; if (newSession) { await ctx.context.runInBackgroundOrAwait(sendWelcomeEmail(newSession.user)); } }

Reuse hooks across multiple endpoints with plugins

If you need to reuse a hook across multiple endpoints, consider creating a plugin instead. Refer to the Plugins Documentation for more information.

Give your agent this brain