diff --git a/.changeset/fair-sessions-retry.md b/.changeset/fair-sessions-retry.md new file mode 100644 index 0000000000..34107f118c --- /dev/null +++ b/.changeset/fair-sessions-retry.md @@ -0,0 +1,5 @@ +--- +"better-auth": patch +--- + +Fix `customSession` treating session lookup failures as signed-out users. Server-side `getSession` now throws an API error, and HTTP clients receive an error response. diff --git a/packages/better-auth/src/plugins/custom-session/custom-session.test.ts b/packages/better-auth/src/plugins/custom-session/custom-session.test.ts index ddebb268c1..7cd001c2b0 100644 --- a/packages/better-auth/src/plugins/custom-session/custom-session.test.ts +++ b/packages/better-auth/src/plugins/custom-session/custom-session.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, expectTypeOf, it } from "vitest"; +import { describe, expect, expectTypeOf, it, vi } from "vitest"; import { createAuthClient } from "../../client"; import { parseSetCookieHeader } from "../../cookies"; import { getTestInstance } from "../../test-utils/test-instance"; @@ -65,6 +65,29 @@ describe("Custom Session Plugin Tests", async () => { expect(session?.newData).toEqual({ message: "Hello, World!" }); }); + /** + * @see https://github.com/better-auth/better-auth/issues/10566 + */ + it("propagates session lookup failures to server and HTTP clients", async () => { + const { auth, client, signInWithTestUser } = await getTestInstance({ + plugins: [customSession(async (session) => session)], + }); + const { headers } = await signInWithTestUser(); + const context = await auth.$context; + const lookup = vi + .spyOn(context.internalAdapter, "findSession") + .mockRejectedValue(new Error("database unavailable")); + try { + await expect(auth.api.getSession({ headers })).rejects.toMatchObject({ + status: "INTERNAL_SERVER_ERROR", + }); + const result = await client.getSession({ fetchOptions: { headers } }); + expect(result.error?.status).toBe(500); + } finally { + lookup.mockRestore(); + } + }); + it("should return set cookie headers as separate entries", async () => { const { headers } = await signInWithTestUser(); await client.getSession({ diff --git a/packages/better-auth/src/plugins/custom-session/index.ts b/packages/better-auth/src/plugins/custom-session/index.ts index ab0c556a4c..3e8426d9a3 100644 --- a/packages/better-auth/src/plugins/custom-session/index.ts +++ b/packages/better-auth/src/plugins/custom-session/index.ts @@ -104,8 +104,6 @@ export const customSession = < asResponse: false, headers: ctx.headers, returnHeaders: true, - }).catch((e) => { - return null; }); if (!session?.response) { return ctx.json(null);