Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Better Auth · Pipe

hooks

Better Auth hooks let you run custom middleware before or after an auth endpoint. They support request and response customization, validation, cookies, errors, auth context access, and background work.

How it works

Hooks attach custom logic to Better Auth's request lifecycle. A before hook can inspect or alter an incoming request, validate data, stop processing early, or throw an error; an after hook can inspect or modify the response and perform follow-up work.

Syntax

betterAuth({ hooks: { before: createAuthMiddleware(async (ctx) => { /* ... */ }), after: createAuthMiddleware(async (ctx) => { /* ... */ }) } })

Parameters

NameTypeDescription
hooksobjectRequest lifecycle configuration containing before and after middleware handlers.
ctxAuthMiddlewareContextMiddleware context for the current auth request and endpoint.
beforeAuthMiddlewareHook middleware executed before endpoint processing.
afterAuthMiddlewareHook middleware executed after endpoint processing.

Returns

A hook may return a response/context for early handling; otherwise endpoint processing continues. After hooks can modify the resulting response.

Key points

  • Hooks customize endpoint behavior without requiring a complete plugin.
  • Before handlers are useful for request transformation, validation, authorization, and short-circuiting.
  • After handlers can adjust the endpoint response after the main operation finishes.
  • The context provides helpers for setting ordinary or signed cookies.
  • Cookie values can be read through signed and unsigned context helpers.
  • The nested context carries authentication-related state available to hook logic.

Common mistakes

  • Before hooks run before endpoint execution, so they are appropriate for request changes, validation, early returns, and authorization checks.
  • After hooks cannot influence work that already happened in the endpoint; use them for response changes or post-processing.
  • Use APIError when a hook must produce a deliberate HTTP status and message instead of allowing an unspecified error.

Example: Global before and after hooks

import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";

export const auth = betterAuth({
  hooks: {
    before: createAuthMiddleware(async (ctx) => {
      console.log("Request path:", ctx.path);
    }),
    after: createAuthMiddleware(async (ctx) => {
      console.log("Response:", ctx.context.returned);
    }),
  },
});

Registers middleware that runs before and after Better Auth endpoint processing.

When to use it

Pre-validation and authorization

Validate signup or sign-in input before the endpoint runs and reject invalid requests.

Cookie management

Add or update cookies using the request context's cookie helpers.

Response handling and follow-up work

Adjust endpoint output or trigger work after a successful operation.

Interview questions

QWhat problem do Better Auth hooks solve?

Hooks let custom logic participate in Better Auth's endpoint lifecycle without implementing a separate endpoint or full plugin. The configuration exposes before and after handlers, and each handler is created with createAuthMiddleware.

Follow-up: How would you prevent an endpoint from continuing? Put the validation in a before hook and return early or throw APIError when the request is invalid.

QWhat is the difference between before and after hooks?

A before hook executes before the endpoint and can modify the request, validate data, return early, or perform authorization logic. An after hook executes after the endpoint and is suited to response changes and background work.

Follow-up: Where should response-dependent logic go? In an after hook, because it runs after endpoint execution and can access the returned response through the auth context.

QWhat can a hook access through ctx?

The hook context exposes request/response helpers and an auth-related context object. For example, ctx.json sends JSON, cookie helpers set or read cookies, and APIError creates an error with a chosen status and message.

Follow-up: How can a hook interact with the session created during processing? Use the nested auth context, which contains values such as the newly created session and cookie configuration.

  • createAuthMiddleware
  • APIError
  • ctx.json
  • ctx.setCookie
  • ctx.setSignedCookie
  • ctx.getCookie
  • ctx.getSignedCookie
  • databaseHooks

Source: Hooks | Better Auth. Checked 2026-10-15.