From 2ba021e8e3c17aba9226be65b492ca9fff700778 Mon Sep 17 00:00:00 2001 From: Bereket Engida Date: Fri, 27 Dec 2024 12:31:31 +0300 Subject: [PATCH] docs: imporve hooks docs --- docs/content/docs/concepts/hooks.mdx | 101 +++++++++++++++++++++------ 1 file changed, 78 insertions(+), 23 deletions(-) diff --git a/docs/content/docs/concepts/hooks.mdx b/docs/content/docs/concepts/hooks.mdx index df3540c970..2d5a80be97 100644 --- a/docs/content/docs/concepts/hooks.mdx +++ b/docs/content/docs/concepts/hooks.mdx @@ -3,7 +3,11 @@ title: Hooks description: Better Auth Hooks let you customize BetterAuth's behavior --- -Hooks in Better Auth let you "hook into" the lifecycle and execute custom logic. They provide a way to customize Better Auth's behavior without writing a full plugin. +Hooks in Better Auth let you "hook into" the lifecycle and execute custom logic. They provide a way to customize Better Auth's behavior without writing a full plugin. + + +We highly recommend using hooks if you need to make custom adjustments to an endpoint rather than making another endpoint outside of better auth. + ## Before Hooks @@ -62,39 +66,48 @@ export const auth = betterAuth({ **After hooks** run *after* an endpoint is executed. Use them to modify responses. -### Example: Add a Custom Header - -This hook adds a custom header to the response: +### Example: Send a notification to your channel when a new user is registered ```ts title="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) => { - ctx.responseHeader.set("X-Custom-Header", "Hello World"); - return { - responseHeader: ctx.responseHeader // return the updated response headers + if(ctx.path.startWith("/sign-up")){ + const newSession = ctx.context.newSession; + if(newSession){ + sendMessage({ + type: "user-register", + name: newSession.user.name, + }) + } } }), }, }); ``` -## Context Object +## Ctx -The `ctx` object provides: +When you call `createAuthMiddleware` a `ctx` object is passed that provides a lot of useful properties. Including: - **Path:** `ctx.path` to get the current endpoint path. - **Body:** `ctx.body` for parsed request body (available for POST requests). - **Headers:** `ctx.headers` to access request headers. - **Request:** `ctx.request` to access the request object (may not exist in server-only endpoints). - **Query Parameters:** `ctx.query` to access query parameters. +- **Context**: `ctx.context` auth related context, useful for accessing new session, auth cookies configuration, password hashing, config... and more. -### JSON Responses +### Request Response + +This utilities allows you to get request information and to send response from a hook. + +#### JSON Responses Use `ctx.json` to send JSON responses: @@ -106,7 +119,7 @@ const hook = createAuthMiddleware(async (ctx) => { }); ``` -### Redirects +#### Redirects Use `ctx.redirect` to redirect users: @@ -116,7 +129,7 @@ const hook = createAuthMiddleware(async (ctx) => { }); ``` -### Cookies +#### Cookies - Set cookies: `ctx.setCookies` or `ctx.setSignedCookie`. - Get cookies: `ctx.getCookies` or `ctx.getSignedCookies`. @@ -135,17 +148,7 @@ const hook = createAuthMiddleware(async (ctx) => { }); ``` -### Predefined Auth Cookies - -Access BetterAuth’s predefined cookie properties: - -```ts -const hook = createAuthMiddleware(async (ctx) => { - const cookieName = ctx.context.authCookies.sessionToken.name; -}); -``` - -### Errors +#### Errors Throw errors with `APIError` for a specific status code and message: @@ -157,6 +160,58 @@ const hook = createAuthMiddleware(async (ctx) => { }); ``` + + +### Context + +The `ctx` object contains another `context` object inside that's meant to hold contexts related to auth. Including a newly created session on after hook, cookies configuration, password hasher and so on. + +#### New Session + +The newly created session after an endpoint is run. This only exist in after hook. + +```ts title="auth.ts" +createAuthMiddleware(async (ctx) => { + const newSession = ctx.context.newSession +}); +``` + +#### Predefined Auth Cookies + +Access BetterAuth’s predefined cookie properties: + +```ts title="auth.ts" +createAuthMiddleware(async (ctx) => { + const cookieName = ctx.context.authCookies.sessionToken.name; +}); +``` + +#### Secret + +You can access the `secret` for your auth instance on `ctx.context.secret` + +#### Password + +The password object provider `hash` and `verify` + +- `ctx.context.password.hash`: let's you hash a given password. +- `ctx.context.password.verify`: let's you verify given `password` and a `hash`. + +#### Adapter + +Adapter exposes the adapter methods used by better auth. Including `findOne`, `findMany`, `create`, `delete`, `update` and `updateMany`. You generally should use your actually `db` instance from your orm rather than this adapter. + + +#### Internal Adapter + +These are calls to your db that perform specific actions. `createUser`, `createSession`, `updateSession`... + +This may be useful to use instead of using your db directly to get access to `databaseHooks`, proper `secondaryStorage` support and so on. If you're make a query similar to what exist in this internal adapter actions it's worth a look. + +#### generateId + +You can use `ctx.context.generateId` to generate Id for various reasons. + ## Reusable Hooks If you need to reuse a hook across multiple endpoints, consider creating a plugin. Learn more in the [Plugins Documentation](/docs/concepts/plugins).