Ability to Refresh / Revalidate Session Manually #2741

Closed
opened 2026-03-13 10:16:52 -05:00 by GiteaMirror · 5 comments
Owner

Originally created by @Scholar01 on GitHub (Jan 21, 2026).

Is this suited for github?

  • Yes, this is suited for github

In some real-world setups, the user data is updated outside of better-auth’s built-in adapters, for example:
• Using a custom ORM (e.g. Drizzle)
• Updating the user table manually (role, permissions, profile fields, etc.)
• Enabling secondaryStorage for session caching (Redis, KV, etc.)

In this case:
1. The user record is updated successfully in the database
2. The session stored in secondaryStorage still contains stale user data
3. There is currently no official API to force the session to refresh
4. The application continues to read outdated session.user until:
• the session expires, or
• the user logs out and logs back in

This makes it hard to safely update user state at runtime.

Describe the solution you'd like

’d like better-auth to provide an official way to refresh or revalidate the current session, especially when secondaryStorage is enabled.

Some possible forms this could take:
• A high-level API such as:
• auth.refreshSession()
• auth.revalidateSession()
• Or a more targeted API, for example:
• auth.invalidateSession(sessionId)
• auth.invalidateUserSessions(userId)
• Or an explicit way to bypass / re-fetch user data from the database and update the cached session in secondaryStorage

Describe alternatives you've considered

•	Forcing users to log out and log back in

→ Not acceptable for most applications and breaks UX.
• Shortening session TTL
→ Reduces cache effectiveness and still does not guarantee immediate consistency.
• Manually clearing secondaryStorage entries
→ Requires internal knowledge of better-auth’s storage keys and is fragile / unsupported.
• Avoiding secondaryStorage entirely
→ Not practical for performance-sensitive or distributed systems.

None of these options provide a clean, supported, or reliable solution.

Additional context

As a workaround, I implemented a custom endpoint to manually refresh the session by reloading the user from the database and resetting the session cookie.

Example implementation:


createAuthEndpoint(
  '/super-admin/refresh-user',
  {
    method: 'POST',
  },
  async (ctx) => {
    const session = await getSessionFromCtx(ctx, {
      disableRefresh: true,
    });

    if (!session) {
      return ctx.json({ error: 'Session not found' }, { status: 401 });
    }

    const user = await ctx.context.internalAdapter.findUserById(
      session.user.id,
    );

    await setSessionCookie(ctx, {
      session: session.session,
      user: user!,
    });

    const cookieName = ctx.context.options.advanced?.cookiePrefix
      ? `${ctx.context.options.advanced?.cookiePrefix}.session_data`
      : 'session_data';

    deleteCookie(cookieName);

    return ctx.json({ success: true });
  },
);

This approach works, but it relies on:
• Internal APIs (internalAdapter, setSessionCookie)
• Knowledge of cookie naming and storage behavior
• Manual cache invalidation logic

Which makes it fragile and tightly coupled to better-auth internals.

Having an official, supported session refresh API would allow this behavior to be implemented safely and consistently, without depending on internal details or custom endpoints.

Originally created by @Scholar01 on GitHub (Jan 21, 2026). ### Is this suited for github? - [x] Yes, this is suited for github ### Is your feature request related to a problem? Please describe. In some real-world setups, the user data is updated outside of better-auth’s built-in adapters, for example: • Using a custom ORM (e.g. Drizzle) • Updating the user table manually (role, permissions, profile fields, etc.) • Enabling secondaryStorage for session caching (Redis, KV, etc.) In this case: 1. The user record is updated successfully in the database 2. The session stored in secondaryStorage still contains stale user data 3. There is currently no official API to force the session to refresh 4. The application continues to read outdated session.user until: • the session expires, or • the user logs out and logs back in This makes it hard to safely update user state at runtime. ### Describe the solution you'd like ’d like better-auth to provide an official way to refresh or revalidate the current session, especially when secondaryStorage is enabled. Some possible forms this could take: • A high-level API such as: • auth.refreshSession() • auth.revalidateSession() • Or a more targeted API, for example: • auth.invalidateSession(sessionId) • auth.invalidateUserSessions(userId) • Or an explicit way to bypass / re-fetch user data from the database and update the cached session in secondaryStorage ### Describe alternatives you've considered • Forcing users to log out and log back in → Not acceptable for most applications and breaks UX. • Shortening session TTL → Reduces cache effectiveness and still does not guarantee immediate consistency. • Manually clearing secondaryStorage entries → Requires internal knowledge of better-auth’s storage keys and is fragile / unsupported. • Avoiding secondaryStorage entirely → Not practical for performance-sensitive or distributed systems. None of these options provide a clean, supported, or reliable solution. ⸻ ### Additional context As a workaround, I implemented a custom endpoint to manually refresh the session by reloading the user from the database and resetting the session cookie. Example implementation: ```ts createAuthEndpoint( '/super-admin/refresh-user', { method: 'POST', }, async (ctx) => { const session = await getSessionFromCtx(ctx, { disableRefresh: true, }); if (!session) { return ctx.json({ error: 'Session not found' }, { status: 401 }); } const user = await ctx.context.internalAdapter.findUserById( session.user.id, ); await setSessionCookie(ctx, { session: session.session, user: user!, }); const cookieName = ctx.context.options.advanced?.cookiePrefix ? `${ctx.context.options.advanced?.cookiePrefix}.session_data` : 'session_data'; deleteCookie(cookieName); return ctx.json({ success: true }); }, ); ``` This approach works, but it relies on: • Internal APIs (internalAdapter, setSessionCookie) • Knowledge of cookie naming and storage behavior • Manual cache invalidation logic Which makes it fragile and tightly coupled to better-auth internals. Having an official, supported session refresh API would allow this behavior to be implemented safely and consistently, without depending on internal details or custom endpoints.
GiteaMirror added the enhancement label 2026-03-13 10:16:52 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Jan 21, 2026):

The request for an official way to refresh or revalidate the current session in Better Auth is a recognized need. Currently, there isn't an official API to force a session refresh, which can lead to stale user data in scenarios where user information is updated externally.

An open issue exists for this enhancement, which aims to add methods like auth.refreshSession() or auth.revalidateSession(), providing a way to manage sessions more effectively, especially when using secondary storage [1].

While your workaround does work, leveraging internal APIs and session cookies might not be ideal as it can couple your code to Better Auth's internals.

For now, you could keep an eye on any updates regarding this issue or consider tagging members of the Better Auth team like @bekacru and @ping__ for further discussion or suggestions.

What specific use case do you foresee that would benefit the most from an official session refresh API?

If you need more help, tag @better-auth-agent in a comment so I can respond.

DiagramDiscordGitHub

Diagram Join Star

@better-auth-agent[bot] commented on GitHub (Jan 21, 2026): The request for an official way to refresh or revalidate the current session in Better Auth is a recognized need. Currently, there isn't an official API to force a session refresh, which can lead to stale user data in scenarios where user information is updated externally. An open issue exists for this enhancement, which aims to add methods like `auth.refreshSession()` or `auth.revalidateSession()`, providing a way to manage sessions more effectively, especially when using secondary storage [[1]](https://github.com/better-auth/better-auth/pull/6871). While your workaround does work, leveraging internal APIs and session cookies might not be ideal as it can couple your code to Better Auth's internals. For now, you could keep an eye on any updates regarding this issue or consider tagging members of the Better Auth team like @bekacru and @ping__ for further discussion or suggestions. What specific use case do you foresee that would benefit the most from an official session refresh API? _If you need more help, tag @better-auth-agent in a comment so I can respond._ <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@pedro-camaforte commented on GitHub (Feb 6, 2026):

I have the same problem. Need to update user tier after he pays for a subscription. No way to do that right now without forcing him to log out and in.

@pedro-camaforte commented on GitHub (Feb 6, 2026): I have the same problem. Need to update user `tier` after he pays for a subscription. No way to do that right now without forcing him to log out and in.
Author
Owner

@ping-maxwell commented on GitHub (Feb 11, 2026):

The main issue is that session age is a security factor. If the session is under a certain age it can be considered a "fresh session", and fresh sessions are then allowed to perform critical operations (deleting their acc for example).

Issuing a new session without re-authroization is a security issue. It's recommended to re-authenticate to get a new session.

if the user data is out of date on the KV then I recommend either manually updating the KV for that given user (harder) or use our APIs to perform these forms of user updates. For example auth.api.updateUser will also update the KV

@ping-maxwell commented on GitHub (Feb 11, 2026): The main issue is that session age is a security factor. If the session is under a certain *age* it can be considered a "fresh session", and fresh sessions are then allowed to perform critical operations (deleting their acc for example). Issuing a new session without re-authroization is a security issue. It's recommended to re-authenticate to get a new session. if the user data is out of date on the KV then I recommend either manually updating the KV for that given user (harder) or use our APIs to perform these forms of user updates. For example auth.api.updateUser will also update the KV
Author
Owner

@pedro-camaforte commented on GitHub (Feb 11, 2026):

@ping-maxwell as I understand from the docs, you can only use auth.api.updateUser on input: true fields. But in many cases, you don't want the client to have the ability to update those fields, such as a role or tier field. In those cases, you want to do that server side.

And no, we don't want to issue a new session. Would be better to just update the existing one. After that, client could just call a session refresh to get the most recent data and update the cookie.

So right now, better-auth doesn't allow us to do that, because of the input: true limitation. Can't we just have a auth.api.updateUserPrivateFields that updates the user an automatically updates the session?

@pedro-camaforte commented on GitHub (Feb 11, 2026): @ping-maxwell as I understand from the docs, you can only use `auth.api.updateUser` on `input: true` fields. But in many cases, you don't want the client to have the ability to update those fields, such as a `role` or `tier` field. In those cases, you want to do that server side. And no, we don't want to issue a new session. Would be better to just update the existing one. After that, client could just call a session refresh to get the most recent data and update the cookie. So right now, better-auth doesn't allow us to do that, because of the `input: true` limitation. Can't we just have a `auth.api.updateUserPrivateFields` that updates the user an automatically updates the session?
Author
Owner

@ping-maxwell commented on GitHub (Feb 12, 2026):

Oh you're right.
You could use our internal adapter to update the user:

const ctx = await auth.$context;
const internalAdapter= ctx.internalAdapter;

await internalAdapter.updateUser("user-id", {
	// any value
})

This should update secondary storage too

@ping-maxwell commented on GitHub (Feb 12, 2026): Oh you're right. You could use our internal adapter to update the user: ```ts const ctx = await auth.$context; const internalAdapter= ctx.internalAdapter; await internalAdapter.updateUser("user-id", { // any value }) ``` This should update secondary storage too
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#2741