훅
Better Auth의 훅을 사용하면 라이프사이클에 "연결"하여 커스텀 로직을 실행할 수 있습니다. 전체 플러그인을 작성하지 않고도 Better Auth의 동작을 커스터마이징하는 방법을 제공합니다.
Better Auth 외부에서 다른 엔드포인트를 만드는 것보다 엔드포인트에 커스텀 조정이 필요한 경우 훅을 사용하는 것을 강력히 권장합니다.
Before 훅
Before 훅은 엔드포인트가 실행되기 전에 실행됩니다. 요청을 수정하거나, 데이터를 사전 검증하거나, 일찍 반환하는 데 사용합니다.
예제: 이메일 도메인 제한 강제하기
이 훅은 사용자의 이메일이 @example.com으로 끝나는 경우에만 가입할 수 있도록 보장합니다:
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으로 끝나야 합니다",
});
}
}),
},
});예제: 요청 컨텍스트 수정하기
계속 진행하기 전에 요청 컨텍스트를 조정하려면:
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",
},
}
};
}
}),
},
});After 훅
After 훅은 엔드포인트가 실행된 후에 실행됩니다. 응답을 수정하는 데 사용합니다.
예제: 새 사용자가 등록되면 채널에 알림 보내기
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,
})
}
}
}),
},
});Ctx
createAuthMiddleware를 호출하면 많은 유용한 속성을 제공하는 ctx 객체가 전달됩니다. 여기에는 다음이 포함됩니다:
- Path: 현재 엔드포인트 경로를 가져오는
ctx.path. - Body: 파싱된 요청 본문을 위한
ctx.body(POST 요청에 사용 가능). - Headers: 요청 헤더에 접근하는
ctx.headers. - Request: 요청 객체에 접근하는
ctx.request(서버 전용 엔드포인트에는 존재하지 않을 수 있음). - Query Parameters: 쿼리 매개변수에 접근하는
ctx.query. - Context: auth 관련 컨텍스트에 접근하는
ctx.context, 새 세션, auth 쿠키 설정, 비밀번호 해싱, 설정 등에 유용합니다...
등등.
요청 응답
이 유틸리티를 사용하면 요청 정보를 가져오고 훅에서 응답을 보낼 수 있습니다.
JSON 응답
JSON 응답을 보내려면 ctx.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");
});쿠키
- 쿠키 설정:
ctx.setCookies또는ctx.setSignedCookie. - 쿠키 가져오기:
ctx.getCookies또는ctx.getSignedCookie.
예제:
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.getSignedCookie("my-signed-cookie");
});오류
특정 상태 코드와 메시지로 오류를 던지려면 APIError를 사용하세요:
import { createAuthMiddleware, APIError } from "better-auth/api";
const hook = createAuthMiddleware(async (ctx) => {
throw new APIError("BAD_REQUEST", {
message: "잘못된 요청",
});
});Context
ctx 객체 내부에는 auth와 관련된 컨텍스트를 보관하기 위한 또 다른 context 객체가 있습니다. after 훅에서 새로 생성된 세션, 쿠키 설정, 비밀번호 해셔 등이 포함됩니다.
새 세션
엔드포인트가 실행된 후 새로 생성된 세션. 이는 after 훅에만 존재합니다.
createAuthMiddleware(async (ctx) => {
const newSession = ctx.context.newSession
});반환됨
훅에서 반환된 값은 체인의 다음 훅으로 전달됩니다.
createAuthMiddleware(async (ctx) => {
const returned = ctx.context.returned; //이는 성공적인 응답이거나 APIError일 수 있습니다
});응답 헤더
이 훅 전에 실행된 엔드포인트와 훅이 추가한 응답 헤더.
createAuthMiddleware(async (ctx) => {
const responseHeaders = ctx.context.responseHeaders;
});사전 정의된 Auth 쿠키
BetterAuth의 사전 정의된 쿠키 속성에 접근:
createAuthMiddleware(async (ctx) => {
const cookieName = ctx.context.authCookies.sessionToken.name;
});Secret
auth 인스턴스의 secret에 ctx.context.secret으로 접근할 수 있습니다
Password
password 객체는 hash와 verify를 제공합니다
ctx.context.password.hash: 주어진 비밀번호를 해시할 수 있습니다.ctx.context.password.verify: 주어진password와hash를 검증할 수 있습니다.
Adapter
Adapter는 Better Auth가 사용하는 어댑터 메서드를 노출합니다. findOne, findMany, create, delete, update, updateMany가 포함됩니다. 일반적으로 이 어댑터보다는 ORM의 실제 db 인스턴스를 사용해야 합니다.
Internal Adapter
이들은 특정 액션을 수행하는 db 호출입니다. createUser, createSession, updateSession...
이는 databaseHooks, 적절한 secondaryStorage 지원 등에 접근하기 위해 db를 직접 사용하는 대신 사용하는 것이 유용할 수 있습니다. 이 internal adapter 액션에 있는 것과 유사한 쿼리를 만드는 경우 살펴볼 가치가 있습니다.
generateId
다양한 이유로 Id를 생성하기 위해 ctx.context.generateId를 사용할 수 있습니다.
재사용 가능한 훅
여러 엔드포인트에서 훅을 재사용해야 하는 경우 플러그인을 만드는 것을 고려하세요. 자세한 내용은 플러그인 문서를 참조하세요.