Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(auth): keep web sessions alive with deferred session refresh (#21707)

YuTengjingdb7bd682b99f
diff --git a/package.json b/package.json
index e7244e55de2..668af703aab 100644
--- a/package.json
+++ b/package.json
@@ -184,7 +184,7 @@
"overrides": {
"@types/react": "19.2.13",
"baseline-browser-mapping": "2.10.31",
- "better-auth": "1.6.15",
+ "better-auth": "1.6.33",
"drizzle-orm": "^0.45.2",
"fast-xml-parser": "5.4.2",
"lexical": "0.42.0",
@@ -201,8 +201,8 @@
"@aws-sdk/s3-request-presigner": "~3.932.0",
"@azure-rest/ai-inference": "1.0.0-beta.5",
"@azure/core-auth": "^1.11.0",
- "@better-auth/expo": "1.6.15",
- "@better-auth/passkey": "1.6.15",
+ "@better-auth/expo": "1.6.33",
+ "@better-auth/passkey": "1.6.33",
"@cfworker/json-schema": "^4.1.1",
"@chat-adapter/discord": "~4.38.0",
"@chat-adapter/slack": "~4.38.0",
@@ -367,7 +367,7 @@
"ahooks": "^3.9.7",
"async-retry": "^1.3.3",
"bcryptjs": "^3.0.3",
- "better-auth": "1.6.15",
+ "better-auth": "1.6.33",
"brotli-wasm": "^3.0.1",
"buffer.js": "npm:buffer@^6.0.3",
"chat": "~4.38.0",
diff --git a/src/app/(backend)/api/auth/[...all]/route.test.ts b/src/app/(backend)/api/auth/[...all]/route.test.ts
index 107f56095ca..9d1c0050ca7 100644
--- a/src/app/(backend)/api/auth/[...all]/route.test.ts
+++ b/src/app/(backend)/api/auth/[...all]/route.test.ts
@@ -77,6 +77,22 @@ describe('/api/auth/[...all] route', () => {
expect(mocks.post).toHaveBeenCalledTimes(1);
});
+ it('drops the empty body of an untyped POST so Better Auth does not reject it with 415', async () => {
+ const request = new Request('https://localhost/api/auth/get-session', {
+ body: new ReadableStream({ start: (controller) => controller.close() }),
+ duplex: 'half',
+ headers: { cookie: 'better-auth.session_token=token' },
+ method: 'POST',
+ } as RequestInit) as NextRequest;
+
+ const response = await POST(request);
+
+ expect(response.status).toBe(200);
+ const forwarded = mocks.post.mock.calls[0][0];
+ expect(forwarded.body).toBeNull();
+ expect(forwarded.headers.get('cookie')).toBe('better-auth.session_token=token');
+ });
+
it('delegates GET requests to Better Auth', async () => {
const request = new Request('https://localhost/api/auth/get-session') as NextRequest;
diff --git a/src/app/(backend)/api/auth/[...all]/route.ts b/src/app/(backend)/api/auth/[...all]/route.ts
index 28642011aca..5f38b3b71c4 100644
--- a/src/app/(backend)/api/auth/[...all]/route.ts
+++ b/src/app/(backend)/api/auth/[...all]/route.ts
@@ -2,6 +2,7 @@ import { toNextJsHandler } from 'better-auth/next-js';
import type { NextRequest } from 'next/server';
import { auth } from '@/auth';
+import { stripEmptyUntypedBody } from '@/libs/better-auth/request-body';
const jsonContentTypeRegex = /^application\/(?:[a-z0-9.+-]*\+)?json/i;
@@ -32,5 +33,5 @@ export const POST = async (request: NextRequest) => {
const invalidJsonResponse = await validateJsonBody(request);
if (invalidJsonResponse) return invalidJsonResponse;
- return handler.POST(request);
+ return handler.POST(await stripEmptyUntypedBody(request));
};
diff --git a/src/libs/better-auth/define-config.ts b/src/libs/better-auth/define-config.ts
index 1f531f246fd..697a9133d5f 100644
--- a/src/libs/better-auth/define-config.ts
+++ b/src/libs/better-auth/define-config.ts
@@ -20,7 +20,9 @@ import {
getVerificationEmailTemplate,
getVerificationOTPEmailTemplate,
} from '@/libs/better-auth/email-templates';
+import { deferredSessionRefresh } from '@/libs/better-auth/plugins/deferred-session-refresh';
import { emailWhitelist } from '@/libs/better-auth/plugins/email-whitelist';
+import { sessionOptions } from '@/libs/better-auth/session-options';
import { initBetterAuthSSOProviders } from '@/libs/better-auth/sso';
import {
createSecondaryStorage,
@@ -210,14 +212,7 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {
onAPIError: {
errorURL: '/auth-error',
},
- session: {
- cookieCache: {
- enabled: true,
- maxAge: 2 * 60, // Cache duration in seconds
- },
- // Keep a DB-backed fallback when Redis secondary storage entries are unexpectedly missing.
- storeSessionInDatabase: true,
- },
+ session: sessionOptions,
database: drizzleAdapter(serverDB, {
provider: 'pg',
// experimental joins feature needs schema to pass full relation
@@ -316,6 +311,7 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {
},
plugins: [
...customOptions.plugins,
+ deferredSessionRefresh(),
emailWhitelist(),
expo(),
admin(),
diff --git a/src/libs/better-auth/plugins/deferred-session-refresh.ts b/src/libs/better-auth/plugins/deferred-session-refresh.ts
new file mode 100644
index 00000000000..67951245738
--- /dev/null
+++ b/src/libs/better-auth/plugins/deferred-session-refresh.ts
@@ -0,0 +1,25 @@
+import { createAuthMiddleware } from 'better-auth/api';
+import { type BetterAuthPlugin } from 'better-auth/types';
+
+/**
+ * Makes the deferred session refresh (`POST /get-session`) actually refresh.
+ *
+ * With `deferSessionRefresh`, the client's `GET /get-session` writes the `session_data` cookie
+ * cache and returns `needsRefresh`. Better Auth then serves the client's follow-up POST from that
+ * fresh cache and returns before its refresh logic, so the session would never slide and would
+ * expire 7 days after sign-in. Bypassing the cache on this POST lets it read the stored session
+ * and re-issue the session cookie. Still unfixed upstream as of better-auth 1.8.0-beta.3.
+ */
+export const deferredSessionRefresh = (): BetterAuthPlugin => ({
+ hooks: {
+ before: [
+ {
+ handler: createAuthMiddleware(async (ctx) => ({
+ context: { query: { ...ctx.query, disableCookieCache: true } },
+ })),
+ matcher: (ctx) => ctx.path === '/get-session' && ctx.request?.method === 'POST',
+ },
+ ],
+ },
+ id: 'deferred-session-refresh',
+});
diff --git a/src/libs/better-auth/request-body.test.ts b/src/libs/better-auth/request-body.test.ts
new file mode 100644
index 00000000000..96fdb848236
--- /dev/null
+++ b/src/libs/better-auth/request-body.test.ts
@@ -0,0 +1,50 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { stripEmptyUntypedBody } from './request-body';
+
+const URL = 'https://localhost/api/auth/get-session';
+
+const createPost = (body: BodyInit | null, headers?: HeadersInit) =>
+ new Request(URL, { body, duplex: 'half', headers, method: 'POST' } as RequestInit);
+
+const emptyStream = () => new ReadableStream({ start: (controller) => controller.close() });
+
+describe('stripEmptyUntypedBody', () => {
+ it('drops an empty body stream from a POST without a content type', async () => {
+ const request = createPost(emptyStream(), { cookie: 'session=1', origin: 'https://localhost' });
+
+ const result = await stripEmptyUntypedBody(request);
+
+ expect(result.body).toBeNull();
+ expect(result.method).toBe('POST');
+ expect(result.url).toBe(URL);
+ expect(result.headers.get('cookie')).toBe('session=1');
+ expect(result.headers.get('origin')).toBe('https://localhost');
+ });
+
+ it('keeps requests that declare a content type', async () => {
+ const request = createPost('{}', { 'content-type': 'application/json' });
+
+ const result = await stripEmptyUntypedBody(request);
+
+ expect(result).toBe(request);
+ await expect(result.json()).resolves.toEqual({});
+ });
+
+ it('keeps an untyped request that carries data without consuming it', async () => {
+ const request = createPost('payload');
+ request.headers.delete('content-type');
+
+ const result = await stripEmptyUntypedBody(request);
+
+ expect(result).toBe(request);
+ await expect(result.text()).resolves.toBe('payload');
+ });
+
+ it('keeps requests without a body stream', async () => {
+ const request = createPost(null);
+
+ expect(await stripEmptyUntypedBody(request)).toBe(request);
+ });
+});
diff --git a/src/libs/better-auth/request-body.ts b/src/libs/better-auth/request-body.ts
new file mode 100644
index 00000000000..730568585bd
--- /dev/null
+++ b/src/libs/better-auth/request-body.ts
@@ -0,0 +1,22 @@
+/**
+ * Drops the empty body stream of a POST that declares no content type.
+ *
+ * Next.js gives every POST route request a non-null `body` stream, even when the client sent
+ * nothing. better-call then requires a JSON content type and rejects the request with
+ * 415 `UNSUPPORTED_MEDIA_TYPE`. Better Auth's own client sends such bodyless POSTs, notably
+ * the `POST /get-session` refresh used by `deferSessionRefresh`, so without this every
+ * session refresh fails and the user sees the "login status check failed" screen.
+ * @see https://github.com/better-auth/better-auth/issues/6197
+ */
+export const stripEmptyUntypedBody = async (request: Request): Promise<Request> => {
+ if (!request.body || request.headers.has('content-type')) return request;
+
+ const body = await request.clone().arrayBuffer();
+ if (body.byteLength > 0) return request;
+
+ return new Request(request.url, {
+ headers: request.headers,
+ method: request.method,
+ signal: request.signal,
+ });
+};
diff --git a/src/libs/better-auth/session-options.test.ts b/src/libs/better-auth/session-options.test.ts
new file mode 100644
index 00000000000..5409849bc67
--- /dev/null
+++ b/src/libs/better-auth/session-options.test.ts
@@ -0,0 +1,143 @@
+// @vitest-environment node
+import { betterAuth } from 'better-auth';
+import { memoryAdapter } from 'better-auth/adapters/memory';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deferredSessionRefresh } from './plugins/deferred-session-refresh';
+import { stripEmptyUntypedBody } from './request-body';
+import { sessionOptions } from './session-options';
+
+const BASE_URL = 'http://localhost:3000';
+const DAY = 24 * 60 * 60 * 1000;
+const SESSION_EXPIRES_IN_SECONDS = 7 * 24 * 60 * 60;
+
+/**
+ * A real Better Auth instance using the production session options, so the test exercises
+ * the actual refresh rules rather than asserting the config shape.
+ */
+const createAuth = (plugins = [deferredSessionRefresh()]) => {
+ const db: Record<string, any[]> = { account: [], session: [], user: [], verification: [] };
+ const auth = betterAuth({
+ baseURL: BASE_URL,
+ database: memoryAdapter(db),
+ emailAndPassword: { enabled: true },
+ plugins,
+ secret: 'test-secret-test-secret-test-secret',
+ session: sessionOptions,
+ });
+
+ return { auth, db };
+};
+
+/**
+ * The client's refresh POST as a Next.js route handler receives it: no content type, but a
+ * non-null (empty) body stream.
+ */
+const createRefreshPost = (cookie: string) =>
+ new Request(`${BASE_URL}/api/auth/get-session`, {
+ body: new ReadableStream({ start: (controller) => controller.close() }),
+ duplex: 'half',
+ headers: { cookie, origin: BASE_URL },
+ method: 'POST',
+ } as RequestInit);
+
+const getCookie = (setCookie: string | null, name: string) => {
+ const match = setCookie?.match(new RegExp(`(?:^|,\\s*)(better-auth\\.${name}=[^;]+)`));
+ return match?.[1];
+};
+
+const getSessionTokenMaxAge = (setCookie: string | null) => {
+ const match = setCookie?.match(/better-auth\.session_token=[^;]+;[^,]*?Max-Age=(\d+)/i);
+ return match ? Number(match[1]) : undefined;
+};
+
+/** Signs up, then moves past `updateAge` (1 day) so the session is due for refresh. */
+const signUpAndAge = async (auth: ReturnType<typeof createAuth>['auth']) => {
+ const signUp = await auth.api.signUpEmail({
+ body: { email: '[email protected]', name: 'User', password: 'password-123456' },
+ returnHeaders: true,
+ });
+ const sessionCookie = getCookie(signUp.headers.get('set-cookie'), 'session_token');
+ expect(sessionCookie).toBeDefined();
+
+ vi.setSystemTime(new Date(Date.now() + 2 * DAY));
+
+ return sessionCookie!;
+};
+
+describe('session refresh', () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-01T00:00:00Z'));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('only slides the session when the client can receive the renewed cookie', async () => {
+ const { auth, db } = createAuth();
+ const sessionCookie = await signUpAndAge(auth);
+ const initialExpiresAt = new Date(db.session[0].expiresAt).getTime();
+ const headers = new Headers({ cookie: sessionCookie, origin: BASE_URL });
+
+ // Server-side callers (proxy, tRPC context) drop Set-Cookie, so they must not refresh.
+ const serverSession = await auth.api.getSession({ headers });
+ expect(serverSession?.user.email).toBe('[email protected]');
+ expect(new Date(db.session[0].expiresAt).getTime()).toBe(initialExpiresAt);
+
+ // The browser's GET is read-only too, asks the client to refresh and caches the session.
+ const getResponse = await auth.handler(
+ new Request(`${BASE_URL}/api/auth/get-session`, { headers }),
+ );
+ expect(await getResponse.json()).toMatchObject({ needsRefresh: true });
+ const getSetCookie = getResponse.headers.get('set-cookie');
+ expect(getCookie(getSetCookie, 'session_token')).toBeUndefined();
+ const sessionDataCookie = getCookie(getSetCookie, 'session_data');
+ expect(sessionDataCookie).toBeDefined();
+ expect(new Date(db.session[0].expiresAt).getTime()).toBe(initialExpiresAt);
+
+ // The follow-up POST carries the fresh cookie cache, yet still extends the session and
+ // re-issues a full-length cookie.
+ const postResponse = await auth.handler(
+ await stripEmptyUntypedBody(createRefreshPost(`${sessionCookie}; ${sessionDataCookie}`)),
+ );
+ expect(postResponse.status).toBe(200);
+ const maxAge = getSessionTokenMaxAge(postResponse.headers.get('set-cookie'));
+ expect(maxAge).toBeGreaterThan(SESSION_EXPIRES_IN_SECONDS - 60);
+ expect(new Date(db.session[0].expiresAt).getTime()).toBeGreaterThan(
+ Date.now() + SESSION_EXPIRES_IN_SECONDS * 1000 - 60_000,
+ );
+ });
+
+ it('rejects the bodyless refresh POST as Next.js delivers it unless the body is dropped', async () => {
+ const { auth, db } = createAuth();
+ const sessionCookie = await signUpAndAge(auth);
+ const initialExpiresAt = new Date(db.session[0].expiresAt).getTime();
+
+ const response = await auth.handler(createRefreshPost(sessionCookie));
+
+ expect(response.status).toBe(415);
+ expect(new Date(db.session[0].expiresAt).getTime()).toBe(initialExpiresAt);
+ });
+
+ it('serves the refresh POST from the cookie cache without the plugin', async () => {
+ const { auth, db } = createAuth([]);
+ const sessionCookie = await signUpAndAge(auth);
+ const initialExpiresAt = new Date(db.session[0].expiresAt).getTime();
+ const getResponse = await auth.handler(
+ new Request(`${BASE_URL}/api/auth/get-session`, {
+ headers: { cookie: sessionCookie, origin: BASE_URL },
+ }),
+ );
+ const sessionDataCookie = getCookie(getResponse.headers.get('set-cookie'), 'session_data');
+
+ const postResponse = await auth.handler(
+ await stripEmptyUntypedBody(createRefreshPost(`${sessionCookie}; ${sessionDataCookie}`)),
+ );
+
+ expect(postResponse.status).toBe(200);
+ expect(getCookie(postResponse.headers.get('set-cookie'), 'session_token')).toBeUndefined();
+ expect(new Date(db.session[0].expiresAt).getTime()).toBe(initialExpiresAt);
+ });
+});
diff --git a/src/libs/better-auth/session-options.ts b/src/libs/better-auth/session-options.ts
new file mode 100644
index 00000000000..74980ca8ddd
--- /dev/null
+++ b/src/libs/better-auth/session-options.ts
@@ -0,0 +1,33 @@
+import { type BetterAuthOptions } from 'better-auth/minimal';
+
+/**
+ * Session behavior shared by every Better Auth instance.
+ *
+ * Kept free of server-only imports so the refresh contract can be exercised against a real
+ * Better Auth instance in tests.
+ */
+export const sessionOptions = {
+ cookieCache: {
+ enabled: true,
+ maxAge: 2 * 60, // Cache duration in seconds
+ },
+ /**
+ * Only a client `POST /get-session` may slide the session expiry; every `GET`, including
+ * server-side `auth.api.getSession()` calls, is read-only and reports `needsRefresh`.
+ *
+ * Without this, the proxy and tRPC context refresh the session in the database but cannot
+ * forward the renewed `Set-Cookie`. The browser's own `/get-session` then sees a fresh
+ * session and never re-issues the cookie, so the 7-day session cookie expires while the
+ * database row is still valid and active users are signed out every week.
+ *
+ * The web client (`useSession`) sends the follow-up POST since better-auth 1.6.17.
+ * Imperative `authClient.getSession()` callers (the Expo mobile app) must send it themselves.
+ * The POST relies on `stripEmptyUntypedBody` in the auth route and the
+ * `deferredSessionRefresh` plugin; without them it fails with 415 or never refreshes.
+ * @see https://www.better-auth.com/docs/concepts/session-management#defer-session-refresh
+ * @see https://github.com/better-auth/better-auth/issues/2115
+ */
+ deferSessionRefresh: true,
+ // Keep a DB-backed fallback when Redis secondary storage entries are unexpectedly missing.
+ storeSessionInDatabase: true,
+} satisfies BetterAuthOptions['session'];