[GH-ISSUE #6289] The session config not work as expected #19102

Closed
opened 2026-04-15 17:53:29 -05:00 by GiteaMirror · 4 comments
Owner

Originally created by @begonia666 on GitHub (Nov 25, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6289

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

I am using mongoose

  1. return db client

const getDbClient = async () => {
const conn = await connectToDatabase();
const client = conn?.connection?.getClient()?.db(DB_ENV.name);
if (!client) throw new UnprocessableEntityError('Cannot connect to mongo adapter');
return client;
};

  1. pass the db client to mongodbAdapter
  2. try to login the account
  3. check session stored in database

Current vs. Expected behavior

I am using mongoose, I have set up the "expiresIn" value and "updateAge" but when I logged in, the session's expire time stored in DB is not according to "expiresIn" but always be 1 day and the session not refreshed according to updateAge value

for example, I set up expiresIn as 60s, and updateAge as 30s

from my understanding, the expires value stored in database should be 60s after created time. when I switch between pages, and call authClient.getSession(), the session stored in database should be auto-refreshed after 30s but it doesn't work at all

What version of Better Auth are you using?

1.4.1

System info

{
  "system": {
    "platform": "darwin",
    "arch": "arm64",
    "version": "Darwin Kernel Version 25.1.0: Mon Oct 20 19:33:00 PDT 2025; root:xnu-12377.41.6~2/RELEASE_ARM64_T6020",
    "release": "25.1.0",
    "cpuCount": 10,
    "cpuModel": "Apple M2 Pro",
    "totalMemory": "16.00 GB",
    "freeMemory": "0.14 GB"
  },
  "node": {
    "version": "v22.16.0",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "10.9.2"
  },
  "frameworks": null,
  "databases": null,
  "betterAuth": {
    "version": "Unknown",
    "config": null
  }
}

Which area(s) are affected? (Select all that apply)

Backend, Client

Auth config (if applicable)

import bcrypt from 'bcryptjs';
import { betterAuth } from 'better-auth';
import { mongodbAdapter } from 'better-auth/adapters/mongodb';
import { APIError } from 'better-auth/api';
import { nextCookies } from 'better-auth/next-js';
import { customSession } from 'better-auth/plugins';
import dayjs from 'dayjs';
import { Config } from '@/config';
import { DB_MODEL_NAMES } from '@/constants';
import i18n from '@/libs/i18n';
import { USER_IDS, type UserAPISchema, UserModel, UserStates } from '@/schemas';
import { accountService, connectToDatabase } from '@/services';
import { getDbClient } from '@/services/database';

const client = await getDbClient();

const auth = betterAuth({
  debug: true,
  database: mongodbAdapter(client),
  emailAndPassword: {
    enabled: true,
    autoSignIn: false,
    // requireEmailVerification: false,
    // revokeSessionsOnPasswordReset: true,
    resetPasswordTokenExpiresIn: Config.resetPasswordExpiration * 60,
    password: {
      hash: async (pass) => {
        return await bcrypt.hash(pass, 10);
      },
      verify: async ({ hash, password }) => {
        return await bcrypt.compare(password, hash);
      },
    },
  },
  emailVerification: {
    autoSignInAfterVerification: false,
  },
  account: { modelName: DB_MODEL_NAMES.ACCOUNT },
  user: {
    modelName: DB_MODEL_NAMES.USER,
    fields: {
      email: USER_IDS.EMAIL,
      password: USER_IDS.PASSWORD,
    },
    additionalFields: {
      [USER_IDS.ID]: { type: 'string' },
      [USER_IDS.FIRST_NAME]: { type: 'string' },
      [USER_IDS.LAST_NAME]: { type: 'string' },
      [USER_IDS.ROLE]: { type: 'string' },
      [USER_IDS.STATE]: { type: 'string', defaultValue: UserStates.PENDING },
    },
  },
  session: {
    modelName: DB_MODEL_NAMES.SESSIONS,
    cookieCache: {
      enabled: false,
      maxAge: 5 * 60, // Cache duration in seconds
    },
    disableSessionRefresh: false,
    expiresIn: 60, 
    updateAge: 30, 
    freshAge: 0, 
  },
  plugins: [
    // Used to return session when GET
    customSession(async ({ user, session }) => {
      return {
        session,
        user: {
          ...user,
          [USER_IDS.ID]: user.id,
        },
      };
    }),
    nextCookies(),
  ],
  advanced: {
    useSecureCookies: process.env.NODE_ENV === 'production',
    defaultCookieAttributes: {
      sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
      secure: process.env.NODE_ENV === 'production',
      httpOnly: true,
    },
    ipAddress: {
      disableIpTracking: true,
    },
  },
  databaseHooks: {
    user: {
      create: {
        after: async (user) => {
          user[USER_IDS.ID] = user.id;
          await accountService.sendVerifyEmail(user);
        },
      },
    },
    session: {
      create: {
        before: async (session) => {
          const userId = session?.userId;
          await connectToDatabase();
          const user = await UserModel.findById(userId).lean<UserAPISchema>();
          if (!user) {
            throw new APIError('BAD_REQUEST', {
              message: i18n.t('account.userNotFound'),
            });
          }
          if (user[USER_IDS.STATE] === UserStates.PENDING) {
            throw new APIError('BAD_REQUEST', {
              message: i18n.t('account.userNotVerified'),
            });
          }
          if (user[USER_IDS.STATE] === UserStates.VERIFIED) {
            throw new APIError('BAD_REQUEST', {
              message: i18n.t('account.userNotApproved'),
            });
          }
          if (user[USER_IDS.STATE] === UserStates.DISABLED) {
            throw new APIError('BAD_REQUEST', {
              message: i18n.t('account.userDisabled'),
            });
          }
          return {
            data: {
              ...session
            },
          };
        },
      },
    },
  },
});

export { auth };

Additional context

Originally created by @begonia666 on GitHub (Nov 25, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6289 ### Is this suited for github? - [ ] Yes, this is suited for github ### To Reproduce I am using mongoose 1. return db client const getDbClient = async () => { const conn = await connectToDatabase(); const client = conn?.connection?.getClient()?.db(DB_ENV.name); if (!client) throw new UnprocessableEntityError('Cannot connect to mongo adapter'); return client; }; 2. pass the db client to mongodbAdapter 3. try to login the account 4. check session stored in database ### Current vs. Expected behavior I am using mongoose, I have set up the "expiresIn" value and "updateAge" but when I logged in, the session's expire time stored in DB is not according to "expiresIn" but always be 1 day and the session not refreshed according to updateAge value for example, I set up expiresIn as 60s, and updateAge as 30s from my understanding, the expires value stored in database should be 60s after created time. when I switch between pages, and call authClient.getSession(), the session stored in database should be auto-refreshed after 30s but it doesn't work at all ### What version of Better Auth are you using? 1.4.1 ### System info ```bash { "system": { "platform": "darwin", "arch": "arm64", "version": "Darwin Kernel Version 25.1.0: Mon Oct 20 19:33:00 PDT 2025; root:xnu-12377.41.6~2/RELEASE_ARM64_T6020", "release": "25.1.0", "cpuCount": 10, "cpuModel": "Apple M2 Pro", "totalMemory": "16.00 GB", "freeMemory": "0.14 GB" }, "node": { "version": "v22.16.0", "env": "development" }, "packageManager": { "name": "npm", "version": "10.9.2" }, "frameworks": null, "databases": null, "betterAuth": { "version": "Unknown", "config": null } } ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript import bcrypt from 'bcryptjs'; import { betterAuth } from 'better-auth'; import { mongodbAdapter } from 'better-auth/adapters/mongodb'; import { APIError } from 'better-auth/api'; import { nextCookies } from 'better-auth/next-js'; import { customSession } from 'better-auth/plugins'; import dayjs from 'dayjs'; import { Config } from '@/config'; import { DB_MODEL_NAMES } from '@/constants'; import i18n from '@/libs/i18n'; import { USER_IDS, type UserAPISchema, UserModel, UserStates } from '@/schemas'; import { accountService, connectToDatabase } from '@/services'; import { getDbClient } from '@/services/database'; const client = await getDbClient(); const auth = betterAuth({ debug: true, database: mongodbAdapter(client), emailAndPassword: { enabled: true, autoSignIn: false, // requireEmailVerification: false, // revokeSessionsOnPasswordReset: true, resetPasswordTokenExpiresIn: Config.resetPasswordExpiration * 60, password: { hash: async (pass) => { return await bcrypt.hash(pass, 10); }, verify: async ({ hash, password }) => { return await bcrypt.compare(password, hash); }, }, }, emailVerification: { autoSignInAfterVerification: false, }, account: { modelName: DB_MODEL_NAMES.ACCOUNT }, user: { modelName: DB_MODEL_NAMES.USER, fields: { email: USER_IDS.EMAIL, password: USER_IDS.PASSWORD, }, additionalFields: { [USER_IDS.ID]: { type: 'string' }, [USER_IDS.FIRST_NAME]: { type: 'string' }, [USER_IDS.LAST_NAME]: { type: 'string' }, [USER_IDS.ROLE]: { type: 'string' }, [USER_IDS.STATE]: { type: 'string', defaultValue: UserStates.PENDING }, }, }, session: { modelName: DB_MODEL_NAMES.SESSIONS, cookieCache: { enabled: false, maxAge: 5 * 60, // Cache duration in seconds }, disableSessionRefresh: false, expiresIn: 60, updateAge: 30, freshAge: 0, }, plugins: [ // Used to return session when GET customSession(async ({ user, session }) => { return { session, user: { ...user, [USER_IDS.ID]: user.id, }, }; }), nextCookies(), ], advanced: { useSecureCookies: process.env.NODE_ENV === 'production', defaultCookieAttributes: { sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax', secure: process.env.NODE_ENV === 'production', httpOnly: true, }, ipAddress: { disableIpTracking: true, }, }, databaseHooks: { user: { create: { after: async (user) => { user[USER_IDS.ID] = user.id; await accountService.sendVerifyEmail(user); }, }, }, session: { create: { before: async (session) => { const userId = session?.userId; await connectToDatabase(); const user = await UserModel.findById(userId).lean<UserAPISchema>(); if (!user) { throw new APIError('BAD_REQUEST', { message: i18n.t('account.userNotFound'), }); } if (user[USER_IDS.STATE] === UserStates.PENDING) { throw new APIError('BAD_REQUEST', { message: i18n.t('account.userNotVerified'), }); } if (user[USER_IDS.STATE] === UserStates.VERIFIED) { throw new APIError('BAD_REQUEST', { message: i18n.t('account.userNotApproved'), }); } if (user[USER_IDS.STATE] === UserStates.DISABLED) { throw new APIError('BAD_REQUEST', { message: i18n.t('account.userDisabled'), }); } return { data: { ...session }, }; }, }, }, }, }); export { auth }; ``` ### Additional context
GiteaMirror added the locked label 2026-04-15 17:53:29 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Nov 25, 2025):

Hi @begonia666! I'm Dosu and I’m helping the better-auth team.

Your session expiration and refresh issues are likely due to two main factors:

  1. Mongoose Integration: Better Auth's mongodbAdapter expects a native MongoDB client, not a Mongoose connection. Using Mongoose can cause subtle issues, especially with ID serialization and session handling, which may result in session expiration logic not working as expected. A common workaround is to disable Better Auth's internal ID generation by setting advanced.database.generateId: false or providing a custom function that returns a Mongoose ObjectId string. However, full compatibility is not guaranteed—using the native MongoDB client is the most reliable fix for session expiration issues with Better Auth and MongoDB reference.

  2. Session Refresh & Cookie Update: Even if the session in the database is updated (i.e., expiresAt is refreshed), the session cookie on the client may not be updated if getSession is called from a server context (like Next.js server components or middleware), because cookies can't be set in those contexts. This causes the user to be logged out when the cookie expires, even if the session in the database is still valid. The recommended workaround is to ensure getSession is called from the client (for example, using a client-side SessionRefresher component that calls authClient.getSession() on navigation or periodically) reference.

Troubleshooting steps:

  • Try switching to the native MongoDB client for the adapter if possible.
  • If you must use Mongoose, set advanced.database.generateId: false in your Better Auth config and ensure all session/user/account documents have valid _id fields.
  • Make sure session refresh is triggered from the client so the cookie is updated. If you're using Next.js, avoid calling getSession in server components for refresh purposes.
  • Double-check that dontRememberMe is not being set, as this will force the session expiration to 1 day regardless of your expiresIn config reference.

If you follow these steps and still see issues, try logging the session creation and refresh logic to verify which code path is being hit and what values are being set for expiresAt in both the database and the cookie.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

<!-- gh-comment-id:3573865881 --> @dosubot[bot] commented on GitHub (Nov 25, 2025): <!-- Greeting --> Hi @begonia666! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> Your session expiration and refresh issues are likely due to two main factors: 1. **Mongoose Integration**: Better Auth's `mongodbAdapter` expects a native MongoDB client, not a Mongoose connection. Using Mongoose can cause subtle issues, especially with ID serialization and session handling, which may result in session expiration logic not working as expected. A common workaround is to disable Better Auth's internal ID generation by setting `advanced.database.generateId: false` or providing a custom function that returns a Mongoose ObjectId string. However, full compatibility is not guaranteed—using the native MongoDB client is the most reliable fix for session expiration issues with Better Auth and MongoDB [reference](https://github.com/better-auth/better-auth/issues/4741). 2. **Session Refresh & Cookie Update**: Even if the session in the database is updated (i.e., `expiresAt` is refreshed), the session cookie on the client may not be updated if `getSession` is called from a server context (like Next.js server components or middleware), because cookies can't be set in those contexts. This causes the user to be logged out when the cookie expires, even if the session in the database is still valid. The recommended workaround is to ensure `getSession` is called from the client (for example, using a client-side `SessionRefresher` component that calls `authClient.getSession()` on navigation or periodically) [reference](https://github.com/better-auth/better-auth/issues/2115). **Troubleshooting steps:** - Try switching to the native MongoDB client for the adapter if possible. - If you must use Mongoose, set `advanced.database.generateId: false` in your Better Auth config and ensure all session/user/account documents have valid `_id` fields. - Make sure session refresh is triggered from the client so the cookie is updated. If you're using Next.js, avoid calling `getSession` in server components for refresh purposes. - Double-check that `dontRememberMe` is not being set, as this will force the session expiration to 1 day regardless of your `expiresIn` config [reference](https://github.com/better-auth/better-auth/blob/cb5c2fc2604090247f8bb9a33eae03a5fdc1ab14/packages/better-auth/src/db/internal-adapter.ts#L33-L526). If you follow these steps and still see issues, try logging the session creation and refresh logic to verify which code path is being hit and what values are being set for `expiresAt` in both the database and the cookie. <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/f45fb32e-cbe3-4690-b4cb-68741814aa1a?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/f45fb32e-cbe3-4690-b4cb-68741814aa1a?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/f45fb32e-cbe3-4690-b4cb-68741814aa1a?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/f45fb32e-cbe3-4690-b4cb-68741814aa1a?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/f45fb32e-cbe3-4690-b4cb-68741814aa1a?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/f45fb32e-cbe3-4690-b4cb-68741814aa1a?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/f45fb32e-cbe3-4690-b4cb-68741814aa1a?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=Your%20session%20expiration%20and%20refresh%20issues%20are%20likely%20due%20to%20two%20main%20factors%3A%0A%0A1.%20%2A%2AMongoose%20Integration%2A%2A%3A%20Better%20Auth%27s%20%60mongodbAdapter%60%20expects%20a%20native%20MongoDB%20client%2C%20not%20a%20Mongoose%20connection.%20Using%20Mongoose%20can%20cause%20subtle%20issues%2C%20especially%20with%20ID%20serialization%20and%20session%20handling%2C%20which%20may%20result%20in%20session%20expiration%20logic%20not%20working%20as%20expected.%20A%20common%20workaround%20is%20to%20disable%20Better%20Auth%27s%20internal%20ID%20generation%20by%20setting%20%60advanced.database.generateId%3A%20false%60%20or%20providing%20a%20custom%20function%20that%20returns%20a%20Mongoose%20ObjectId%20string.%20However%2C%20full%20compatibility%20is%20not%20guaranteed%E2%80%94using%20the%20native%20MongoDB%20client%20is%20the%20most%20reliable%20fix%20for%20session%20expiration%20issues%20with%20Better%20Auth%20and%20MongoDB%C2%A0%5Breference%5D%28https%3A//github.com/better-auth/better-auth/issues/4741%29.%0A%0A2.%20%2A%2ASession%20Refresh%20%26%20Cookie%20Update%2A%2A%3A%20Even%20if%20the%20session%20in%20the%20database%20is%20updated%20%28i.e.%2C%20%60expiresAt%60%20is%20refreshed%29%2C%20the%20session%20cookie%20on%20the%20client%20may%20not%20be%20updated%20if%20%60getSession%60%20is%20called%20from%20a%20server%20context%20%28like%20Next.js%20server%20components%20or%20middleware%29%2C%20because%20cookies%20can%27t%20be%20set%20in%20those%20contexts.%20This%20causes%20the%20user%20to%20be%20logged%20out%20when%20the%20cookie%20expires%2C%20even%20if%20the%20session%20in%20the%20database%20is%20still%20valid.%20The%20recommended%20workaround%20is%20to%20ensure%20%60getSession%60%20is%20called%20from%20the%20client%20%28for%20example%2C%20using%20a%20client-side%20%60SessionRefresher%60%20component%20that%20calls%20%60authClient.getSession%28%29%60%20on%20navigation%20or%20periodically%29%C2%A0%5Breference%5D%28https%3A//github.com/better-auth/better-auth/issues/2115%29.%0A%0A%2A%2ATroubleshooting%20steps%3A%2A%2A%0A-%20Try%20switching%20to%20the%20native%20MongoDB%20client%20for%20the%20adapter%20if%20possible.%0A-%20If%20you%20must%20use%20Mongoose%2C%20set%20%60advanced.database.generateId%3A%20false%60%20in%20your%20Better%20Auth%20config%20and%20ensure%20all%20session/user/account%20documents%20have%20valid%20%60_id%60%20fields.%0A-%20Make%20sure%20session%20refresh%20is%20triggered%20from%20the%20client%20so%20the%20cookie%20is%20updated.%20If%20you%27re%20using%20Next.js%2C%20avoid%20calling%20%60getSession%60%20in%20server%20components%20for%20refresh%20purposes.%0A-%20Double-check%20that%20%60dontRememberMe%60%20is%20not%20being%20set%2C%20as%20this%20will%20force%20the%20session%20expiration%20to%201%20day%20regardless%20of%20your%20%60expiresIn%60%20config%C2%A0%5Breference%5D%28https%3A//github.com/better-auth/better-auth/blob/cb5c2fc2604090247f8bb9a33eae03a5fdc1ab14/packages/better-auth/src/db/internal-adapter.ts%23L33-L526%29.%0A%0AIf%20you%20follow%20these%20steps%20and%20still%20see%20issues%2C%20try%20logging%20the%20session%20creation%20and%20refresh%20logic%20to%20verify%20which%20code%20path%20is%20being%20hit%20and%20what%20values%20are%20being%20set%20for%20%60expiresAt%60%20in%20both%20the%20database%20and%20the%20cookie.)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/6289)
Author
Owner

@begonia666 commented on GitHub (Dec 9, 2025):

I read from source code, when createSession, it passed "dontRememberMe", when this value is true,

expiresAt: dontRememberMe ? getDate(3600 * 24, "sec") : getDate(sessionExpiration, "sec"),

the default session expires time is 24 hours, why there is not config to let us set up the time with/without rememberMe?

Currently, it's so confusing, the document never mentioned it will be set to 24 hours when remember me is false and it provided a config option to setup expiresIn for session, so confusing

<!-- gh-comment-id:3629806275 --> @begonia666 commented on GitHub (Dec 9, 2025): I read from source code, when createSession, it passed "dontRememberMe", when this value is true, expiresAt: dontRememberMe ? getDate(3600 * 24, "sec") : getDate(sessionExpiration, "sec"), the default session expires time is 24 hours, why there is not config to let us set up the time with/without rememberMe? Currently, it's so confusing, the document never mentioned it will be set to 24 hours when remember me is false and it provided a config option to setup expiresIn for session, so confusing
Author
Owner

@dosubot[bot] commented on GitHub (Dec 9, 2025):

You're right—the session expiration for dontRememberMe sessions is hardcoded to 24 hours in the Better Auth codebase, and there isn't a config option to change this. This is intentional: the code treats dontRememberMe as a special case for short-lived, non-persistent sessions, and always sets expiresAt to 1 day, regardless of your session.expiresIn setting. There’s no public or undocumented config to override this behavior—it's baked into the session creation logic and documented in the code comments as the intended design "source".

If you need more control over ephemeral session duration, a common workaround is to use client-side storage (like sessionStorage/localStorage) to track session state and force sign-out when the browser is fully closed, since browser session cookie behavior can be inconsistent "source". Let me know if you want a code example for this approach or have other questions!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

<!-- gh-comment-id:3629811687 --> @dosubot[bot] commented on GitHub (Dec 9, 2025): <!-- Answer --> You're right—the session expiration for dontRememberMe sessions is hardcoded to 24 hours in the Better Auth codebase, and there isn't a config option to change this. This is intentional: the code treats dontRememberMe as a special case for short-lived, non-persistent sessions, and always sets expiresAt to 1 day, regardless of your session.expiresIn setting. There’s no public or undocumented config to override this behavior—it's baked into the session creation logic and documented in the code comments as the intended design ["source"](https://github.com/better-auth/better-auth/blob/b7d3281f910c4131b52a894d3e39b3b8acb5613c/packages/better-auth/src/db/internal-adapter.ts#L36-L375). If you need more control over ephemeral session duration, a common workaround is to use client-side storage (like sessionStorage/localStorage) to track session state and force sign-out when the browser is fully closed, since browser session cookie behavior can be inconsistent ["source"](https://github.com/better-auth/better-auth/issues/3112). Let me know if you want a code example for this approach or have other questions! <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/a0b2605a-29d8-4363-b699-db96ed63f557?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/a0b2605a-29d8-4363-b699-db96ed63f557?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/a0b2605a-29d8-4363-b699-db96ed63f557?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/a0b2605a-29d8-4363-b699-db96ed63f557?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/a0b2605a-29d8-4363-b699-db96ed63f557?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/a0b2605a-29d8-4363-b699-db96ed63f557?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/a0b2605a-29d8-4363-b699-db96ed63f557?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=You%27re%20right%E2%80%94the%20session%20expiration%20for%20dontRememberMe%20sessions%20is%20hardcoded%20to%2024%20hours%20in%20the%20Better%20Auth%20codebase%2C%20and%20there%20isn%27t%20a%20config%20option%20to%20change%20this.%20This%20is%20intentional%3A%20the%20code%20treats%20dontRememberMe%20as%20a%20special%20case%20for%20short-lived%2C%20non-persistent%20sessions%2C%20and%20always%20sets%20expiresAt%20to%201%20day%2C%20regardless%20of%20your%20session.expiresIn%20setting.%20There%E2%80%99s%20no%20public%20or%20undocumented%20config%20to%20override%20this%20behavior%E2%80%94it%27s%20baked%20into%20the%20session%20creation%20logic%20and%20documented%20in%20the%20code%20comments%20as%20the%20intended%20design%20%5B%22source%22%5D%28https%3A//github.com/better-auth/better-auth/blob/b7d3281f910c4131b52a894d3e39b3b8acb5613c/packages/better-auth/src/db/internal-adapter.ts%23L36-L375%29.%0A%0AIf%20you%20need%20more%20control%20over%20ephemeral%20session%20duration%2C%20a%20common%20workaround%20is%20to%20use%20client-side%20storage%20%28like%20sessionStorage/localStorage%29%20to%20track%20session%20state%20and%20force%20sign-out%20when%20the%20browser%20is%20fully%20closed%2C%20since%20browser%20session%20cookie%20behavior%20can%20be%20inconsistent%20%5B%22source%22%5D%28https%3A//github.com/better-auth/better-auth/issues/3112%29.%20Let%20me%20know%20if%20you%20want%20a%20code%20example%20for%20this%20approach%20or%20have%20other%20questions%21)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/6289)
Author
Owner

@github-actions[bot] commented on GitHub (Mar 31, 2026):

This issue has been locked as it was closed more than 7 days ago. If you're experiencing a similar problem or you have additional context, please open a new issue and reference this one.

<!-- gh-comment-id:4165915997 --> @github-actions[bot] commented on GitHub (Mar 31, 2026): This issue has been locked as it was closed more than 7 days ago. If you're experiencing a similar problem or you have additional context, please open a new issue and reference this one.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#19102