Open History to see the last commit
1import { env } from 'cloudflare:workers'
2import { tanstackStartCookies } from 'better-auth/tanstack-start'
3
4import { getDb } from '#/db/index.ts'
5import { createEmailSender, otpEmail } from '#/server/email.ts'
6import { createAuth } from '#/lib/auth.ts'
7import type { Auth } from '#/lib/auth.ts'
8
9let instance: Auth | undefined
10
11// Lazy: betterAuth() performs random-value generation at construction, which
12// workerd forbids in module/global scope in the built worker — build the
13// instance on first use inside a request handler instead.
14export function getAuth(): Auth {
15 const sendEmail = createEmailSender(env.EMAIL)
16 instance ??= createAuth(getDb(env), {
17 secret: env.BETTER_AUTH_SECRET,
18 baseUrl: env.BETTER_AUTH_URL,
19 sendOtp: ({ email, otp }) => sendEmail(otpEmail(email, otp)),
20 // Last in the plugin list (better-auth requirement for cookie handling).
21 extraPlugins: [tanstackStartCookies()],
22 })
23 return instance
24}