diff --git a/packages/better-auth/src/auth/full.test.ts b/packages/better-auth/src/auth/full.test.ts index 2e35b75801..3b6d7f2221 100644 --- a/packages/better-auth/src/auth/full.test.ts +++ b/packages/better-auth/src/auth/full.test.ts @@ -192,6 +192,20 @@ describe("auth with dynamic baseURL (allowedHosts)", () => { ).rejects.toThrow('Host "evil.com" is not in the allowed hosts list'); }); + /** + * @see https://github.com/better-auth/better-auth/issues/8447 + */ + test("should use fallback as initial baseURL for non-request contexts", async () => { + const { auth } = await getTestInstance({ + baseURL: { + allowedHosts: ["localhost:*"], + fallback: "http://localhost:5173", + }, + }); + const ctx = await auth.$context; + expect(ctx.baseURL).toBe("http://localhost:5173/api/auth"); + }); + test("should use fallback for disallowed host", async () => { let baseURL: string | undefined; const { customFetchImpl } = await getTestInstance({ diff --git a/packages/better-auth/src/context/create-context.ts b/packages/better-auth/src/context/create-context.ts index 2680c65414..54ec624580 100644 --- a/packages/better-auth/src/context/create-context.ts +++ b/packages/better-auth/src/context/create-context.ts @@ -126,12 +126,16 @@ export async function createAuthContext( } } - const baseURL = isDynamicConfig - ? undefined - : getBaseURL( - typeof options.baseURL === "string" ? options.baseURL : undefined, - options.basePath, - ); + const basePath = options.basePath || "/api/auth"; + const baseURL = + isDynamicConfig && isDynamicBaseURLConfig(options.baseURL) + ? options.baseURL.fallback + ? getBaseURL(options.baseURL.fallback, basePath) + : getBaseURL(undefined, basePath, undefined, true) + : getBaseURL( + typeof options.baseURL === "string" ? options.baseURL : undefined, + basePath, + ); if (!baseURL && !isDynamicConfig) { logger.warn( @@ -178,7 +182,7 @@ Most of the features of Better Auth will not work correctly.`, : baseURL ? new URL(baseURL).origin : "", - basePath: options.basePath || "/api/auth", + basePath, plugins: plugins.concat(internalPlugins), };