Integrations
Better Auth
Mount Better Auth's handler behind CORS, and read or require the session with middleware from @rhythmjs/better-auth.
On this page
Better Auth is framework-agnostic: its handler takes a standard Request and returns a Response. @rhythmjs/better-auth mounts it on a Rhythm app and gives you session middleware. Create your auth instance as Better Auth's docs describe, and import it here.
Install#
bun add better-auth @rhythmjs/better-auth@rhythmjs/http and @rhythmjs/security come with the package.
Mount the handler#
Two pieces work together. betterAuthModule.forRoot({ auth }) is startup-only: it holds auth on its startup context, and you include it to put auth on your app. authHandler({ auth }) is the middleware that answers Better Auth's routes: it forwards requests under ${path}/** (default: the instance's basePath, else /api/auth) to auth.handler, and everything else continues down the chain.
// src/app.module.ts
import { authHandler, betterAuthModule } from "@rhythmjs/better-auth";
import { Rhythm, include, mount } from "@rhythmjs/rhythm";
import type { RhythmHttpContext } from "@rhythmjs/router/context";
import { appController } from "./app.controller";
import { auth } from "./lib/auth";
export const appModule = new Rhythm<{}, RhythmHttpContext>({ name: "app" })
.register(include(betterAuthModule.forRoot({ auth }), ({ auth }) => ({ auth })))
.use(authHandler({ auth, path: "/api/auth" }))
.use(mount(appController));Nothing reaches the app until include picks it, so pick auth for the session middleware below. Serve the app with Bun.serve({ fetch: toFetchHandler(appModule) }).
CORS#
For a frontend on another origin, use the cors exported by @rhythmjs/better-auth (it is cors from @rhythmjs/security/cors, unchanged). Put it before authHandler, so preflights are answered and Better Auth's own responses carry the headers. Cookie sessions need credentials: true, and the origin must also be in Better Auth's trustedOrigins: Better Auth checks origins separately from CORS.
import { authHandler, betterAuthModule, cors } from "@rhythmjs/better-auth";
export const appModule = new Rhythm<{}, RhythmHttpContext>({ name: "app" })
.register(include(betterAuthModule.forRoot({ auth }), ({ auth }) => ({ auth })))
.use(cors({ origin: "http://localhost:3001", credentials: true, allowHeaders: ["Content-Type", "Authorization"] }))
.use(authHandler({ auth }))
.use(mount(appController));Session middleware#
Both read ctx.auth, so they go after the include above, and after authHandler so sign-in and sign-up stay reachable without a session.
withSession()putssessionanduseron the context, bothnullwhen anonymous.requireSession()answers 401 when there is no session, and its type tells the handler thatctx.sessionandctx.userare set.
import { authHandler, betterAuthModule, cors, withSession } from "@rhythmjs/better-auth";
export const appModule = new Rhythm<{}, RhythmHttpContext>({ name: "app" })
.register(include(betterAuthModule.forRoot({ auth }), ({ auth }) => ({ auth })))
.use(cors({ origin: "http://localhost:3001", credentials: true }))
.use(authHandler({ auth }))
.use(withSession())
.use(mount(appController));Guard a route with requireSession(). Its context type needs AuthContext and SessionContext, both exported by the package. Put the guard on the route: a router-level guard narrows the router's context, and that router would then not type-check when mounted.
// src/app.controller.ts
import { requireSession, type AuthContext, type SessionContext } from "@rhythmjs/better-auth";
import { RhythmRouter } from "@rhythmjs/router";
import type { RhythmHttpContext } from "@rhythmjs/router/context";
import { json } from "@rhythmjs/router/response";
export type AppContext = RhythmHttpContext & AuthContext & SessionContext;
export const appController = new RhythmRouter<AppContext>().get("/me", requireSession(), (ctx) => {
json(ctx, { id: ctx.user.id, name: ctx.user.name, email: ctx.user.email });
});session and user have Better Auth's base types. For plugin or custom fields, call ctx.auth.api.getSession({ headers: ctx.request.headers }) yourself: it is typed from your instance. For roles, check ctx.user.role in a guard of your own.
Build auth from app resources#
When auth needs things the app provides (a database, a mailer), use betterAuthModule.forRootAsync({ useFactory }) instead of the pair above. It is a single middleware added with .use(): it derives auth onto the request context and mounts auth.handler like authHandler. useFactory receives the request context (including your startup fields), may be async, and runs once on the first request; if it throws, the failure surfaces on that request and the factory is retried on the next.
const app = new Rhythm<{}, RhythmHttpContext>()
.register(decorate(() => ({ database: openDatabase() })))
.use(
betterAuthModule.forRootAsync({
useFactory: ({ database }: RhythmHttpContext & { database: Database }) => createAuth(database),
}),
)
.use(withSession())
.use(mount(appController));Things to check#
- Better Auth rate-limits its own endpoints; Rhythm middleware placed after
authHandlerdoes not see requests that it answers. - You own the
authinstance and its database: run migrations and close the database on shutdown (register the close as the cleanup of theregistercall, soapp.stop()runs it). - Set
BETTER_AUTH_SECRETandBETTER_AUTH_URLoutside local runs.
The full app, with tests, is examples/better-auth, built from the template.