From e6793c9655c2af02e9c79f7d34267922b7b1b81f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Tr=C3=A1vn=C3=ADk?= Date: Thu, 8 Jan 2026 15:13:30 +0100 Subject: [PATCH] refactor: restructure auth initialization to fix type errors --- app/lib/auth.ts | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/app/lib/auth.ts b/app/lib/auth.ts index 93f2333c..8b0264a3 100644 --- a/app/lib/auth.ts +++ b/app/lib/auth.ts @@ -14,13 +14,9 @@ import { ensureOnlyOneUser } from "./auth-middlewares/only-one-user"; export type AuthMiddlewareContext = MiddlewareContext>; -let _auth: ReturnType | null = null; - -const createAuth = async () => { - if (_auth) return _auth; - - _auth = betterAuth({ - secret: await cryptoUtils.deriveSecret("better-auth"), +const createBetterAuth = (secret: string) => + betterAuth({ + secret, hooks: { before: createAuthMiddleware(async (ctx) => { await ensureOnlyOneUser(ctx); @@ -53,10 +49,19 @@ const createAuth = async () => { plugins: [username({})], }); +type Auth = ReturnType; + +let _auth: Auth | null = null; + +const createAuth = async (): Promise => { + if (_auth) return _auth; + + _auth = createBetterAuth(await cryptoUtils.deriveSecret("better-auth")); + return _auth; }; -export const auth = { +export const auth: Auth = { get api() { if (!_auth) throw new Error("Auth not initialized. Call initAuth() first."); return _auth.api; @@ -65,6 +70,6 @@ export const auth = { if (!_auth) throw new Error("Auth not initialized. Call initAuth() first."); return _auth.handler; }, -}; +} as Auth; export const initAuth = createAuth;