@@ -10,7 +10,7 @@ import { withoutProtocol } from 'ufo'
1010
1111type AuthInstance = Auth < ReturnType < typeof createServerAuth > >
1212
13- let _auth : AuthInstance | null = null
13+ const _authCache = new Map < string , AuthInstance > ( )
1414let _baseURLInferenceLogged = false
1515
1616function normalizeLoopbackOrigin ( origin : string ) : string {
@@ -144,24 +144,28 @@ function getBaseURL(event?: H3Event): string {
144144 throw new Error ( 'siteUrl required. Set NUXT_PUBLIC_SITE_URL.' )
145145}
146146
147- /** Returns Better Auth instance. Pass event for accurate URL detection on first call . */
147+ /** Returns Better Auth instance. Caches per resolved host (or single instance when siteUrl is explicit) . */
148148export function serverAuth ( event ?: H3Event ) : AuthInstance {
149- if ( _auth )
150- return _auth
151-
152149 const runtimeConfig = useRuntimeConfig ( )
153150 const siteUrl = getBaseURL ( event )
151+ const hasExplicitSiteUrl = runtimeConfig . public . siteUrl && typeof runtimeConfig . public . siteUrl === 'string'
152+ const cacheKey = hasExplicitSiteUrl ? '__explicit__' : siteUrl
153+
154+ const cached = _authCache . get ( cacheKey )
155+ if ( cached )
156+ return cached
154157
155158 const database = createDatabase ( )
156159 const userConfig = createServerAuth ( { runtimeConfig, db } )
157160
158- _auth = betterAuth ( {
161+ const auth = betterAuth ( {
159162 ...userConfig ,
160163 ...( database && { database } ) ,
161164 secondaryStorage : createSecondaryStorage ( ) ,
162165 secret : runtimeConfig . betterAuthSecret ,
163166 baseURL : siteUrl ,
164167 } )
165168
166- return _auth
169+ _authCache . set ( cacheKey , auth )
170+ return auth
167171}
0 commit comments