钩子

Better Auth 让你可以hook生命周期并执行自定义逻辑。它们提供了一种自定义 Better Auth 行为的方式,而无需编写完整的插件。

如果你需要对端点进行自定义调整,而不是在 Better Auth 之外创建另一个端点,我们强烈建议使用hook。

前置钩子

前置钩子在端点执行之前运行。使用它们来修改请求、预验证数据或提前返回。

示例:强制邮箱域名限制

这个钩子确保用户只有在他们的邮箱以 @example.com 结尾时才能注册:

auth.ts
import { betterAuth } from "better-auth";
import { createAuthMiddleware, APIError } from "better-auth/api";
 
export const auth = betterAuth({
    hooks: {
        before: createAuthMiddleware(async (ctx) => {
            if (ctx.path !== "/sign-up/email") {
                return;
            }
            if (!ctx.body?.email.endsWith("@example.com")) {
                throw new APIError("BAD_REQUEST", {
                    message: "邮箱必须以 @example.com 结尾",
                });
            }
        }),
    },
});

示例:修改请求上下文

在继续之前调整请求上下文:

auth.ts
import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";
 
export const auth = betterAuth({
    hooks: {
        before: createAuthMiddleware(async (ctx) => {
            if (ctx.path === "/sign-up/email") {
                return {
                    context: {
                        ...ctx,
                        body: {
                            ...ctx.body,
                            name: "John Doe",
                        },
                    }
                };
            }
        }),
    },
});

后置钩子

后置钩子在端点执行之后运行。使用它们来修改响应。

示例:当新用户注册时向你的频道发送通知

auth.ts
import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";
import { sendMessage } from "@/lib/notification"
 
export const auth = betterAuth({
    hooks: {
        after: createAuthMiddleware(async (ctx) => {
            if(ctx.path.startsWith("/sign-up")){
                const newSession = ctx.context.newSession;
                if(newSession){
                    sendMessage({
                        type: "user-register",
                        name: newSession.user.name,
                    })
                }
            }
        }),
    },
});

上下文对象

当你调用 createAuthMiddleware 时,会传递一个 ctx 对象,它提供了许多有用的属性。包括:

  • 路径: ctx.path 获取当前端点路径。
  • 请求体: ctx.body 获取解析后的请求体(适用于 POST 请求)。
  • 请求头: ctx.headers 访问请求头。
  • 请求对象: ctx.request 访问请求对象(在仅服务器端端点中可能不存在)。
  • 查询参数: ctx.query 访问查询参数。
  • 上下文: ctx.context 认证相关的上下文,可用于访问新会话、认证 cookie 配置、密码哈希、配置等。

以及更多。

请求响应

这些工具允许你从钩子中获取请求信息并发送响应。

JSON 响应

使用 ctx.json 发送 JSON 响应:

const hook = createAuthMiddleware(async (ctx) => {
    return ctx.json({
        message: "Hello World",
    });
});

重定向

使用 ctx.redirect 重定向用户:

import { createAuthMiddleware } from "better-auth/api";
 
const hook = createAuthMiddleware(async (ctx) => {
    throw ctx.redirect("/sign-up/name");
});
  • 设置 cookie:ctx.setCookiesctx.setSignedCookie
  • 获取 cookie:ctx.getCookiesctx.getSignedCookies

示例:

import { createAuthMiddleware } from "better-auth/api";
 
const hook = createAuthMiddleware(async (ctx) => {
    ctx.setCookies("my-cookie", "value");
    await ctx.setSignedCookie("my-signed-cookie", "value", ctx.context.secret, {
        maxAge: 1000,
    });
 
    const cookie = ctx.getCookies("my-cookie");
    const signedCookie = await ctx.getSignedCookies("my-signed-cookie");
});

错误

使用 APIError 抛出带有特定状态码和消息的错误:

import { createAuthMiddleware, APIError } from "better-auth/api";
 
const hook = createAuthMiddleware(async (ctx) => {
    throw new APIError("BAD_REQUEST", {
        message: "无效的请求",
    });
});

上下文

ctx 对象内部包含另一个 context 对象,用于保存与认证相关的上下文。包括后置钩子中新创建的会话、cookie 配置、密码哈希器等。

新会话

端点运行后新创建的会话。这仅存在于后置钩子中。

auth.ts
createAuthMiddleware(async (ctx) => {
    const newSession = ctx.context.newSession
});

返回值

钩子的返回值会传递给链中的下一个钩子。

auth.ts
createAuthMiddleware(async (ctx) => {
    const returned = ctx.context.returned; // 这可能是成功的响应或 APIError
});

响应头

由端点和在此钩子之前运行的钩子添加的响应头。

auth.ts
createAuthMiddleware(async (ctx) => {
    const responseHeaders = ctx.context.responseHeaders;
});

访问 Better Auth 的预定义 cookie 属性:

auth.ts
createAuthMiddleware(async (ctx) => {
    const cookieName = ctx.context.authCookies.sessionToken.name;
});

密钥

你可以在 ctx.context.secret 中访问认证实例的 secret

密码

密码对象提供 hashverify 方法:

  • ctx.context.password.hash:让你可以哈希给定的密码。
  • ctx.context.password.verify:让你可以验证给定的 passwordhash

适配器

适配器暴露了 Better Auth 使用的适配器方法。包括 findOnefindManycreatedeleteupdateupdateMany。通常你应该使用你的 ORM 中的实际 db 实例,而不是这个适配器。

内部适配器

这些是对你的数据库执行特定操作的调用。createUsercreateSessionupdateSession...

如果你要执行与这些内部适配器操作类似的查询,使用这些方法而不是直接使用数据库可能很有用,这样可以获得 databaseHooks 和适当的 secondaryStorage 支持等功能。

生成 ID

你可以使用 ctx.context.generateId 来生成各种用途的 ID。

可重用的钩子

如果你需要在多个端点中重用钩子,考虑创建一个插件。在插件文档中了解更多信息。