[GH-ISSUE #6009] refreshCache #27723

Closed
opened 2026-04-17 18:53:52 -05:00 by GiteaMirror · 3 comments
Owner

Originally created by @ijmozn on GitHub (Nov 15, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6009

Hi,

my web project is full stack app(hono+nextjs). my betterAuth is in hono but the better authclient is in nextjs.
I am enabling cookieCache to have to have JWE token in cookie to avoid calling getSession on every route in frontend
I works fine until the cookieCache expires in 5 min from login but the cache is not refreshed and got logged out

how can I can refresh the cookieCache in frontend?

// backend/src/lib/auth.ts
export const auth = betterAuth({
    database: drizzleAdapter(db, {
      provider: "pg",
    }),
    secondaryStorage: {
      get: async (key) => await redis.get(key),
      set: async (key, value, ttl) => await redis.set(key, value, "EX", ttl),
      delete: async (key) => await redis.del(key)
  },
    session: {
        cookieCache: {
            enabled: true,
            strategy: "jwe",
            maxAge: 5 * 60,
            refreshCache: true
        }
    }
  ...
});
// frontend/middleware.ts
export default async function middleware(request: NextRequest) {
...
// check session from cache
 const session = await getCookieCache(request, { strategy: "jwe" });
...
}
Originally created by @ijmozn on GitHub (Nov 15, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6009 Hi, my web project is full stack app(hono+nextjs). my betterAuth is in hono but the better authclient is in nextjs. I am enabling cookieCache to have to have JWE token in cookie to avoid calling `getSession` on every route in frontend I works fine until the cookieCache expires in 5 min from login but the cache is not refreshed and got logged out how can I can refresh the cookieCache in frontend? ``` // backend/src/lib/auth.ts export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "pg", }), secondaryStorage: { get: async (key) => await redis.get(key), set: async (key, value, ttl) => await redis.set(key, value, "EX", ttl), delete: async (key) => await redis.del(key) }, session: { cookieCache: { enabled: true, strategy: "jwe", maxAge: 5 * 60, refreshCache: true } } ... }); ``` ``` // frontend/middleware.ts export default async function middleware(request: NextRequest) { ... // check session from cache const session = await getCookieCache(request, { strategy: "jwe" }); ... } ```
GiteaMirror added the locked label 2026-04-17 18:53:52 -05:00
Author
Owner

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

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

To keep the cookieCache refreshed and avoid logout after 5 minutes, you need to trigger a session fetch from the frontend that allows the backend to set a new cookie before the cache expires. With recent better-auth versions, setting refreshCache: true (or using the new freshCache option) enables automatic refresh, but only if the client actually calls getSession or a similar endpoint in time for the backend to send a new Set-Cookie header. This does not happen automatically on the frontend unless you implement it.

The recommended approach is to periodically call getSession (for example, using a React Query interval, a useEffect timer, or a custom hook) from the frontend. This fetch should be made in a context where the response's Set-Cookie header is forwarded to the browser—such as a Next.js API route, middleware, or client-side fetch with credentials included. This will refresh the cookieCache and keep the user logged in without requiring a full session fetch on every route. If you want to force a refresh, you can call getSession with disableCookieCache: true to bypass the cache and update the cookie immediately. Make sure your cookie settings use sameSite: 'none' and secure: true for cross-origin requests, and that your frontend correctly forwards and sets cookies from the backend response.

Example:

  • In a Next.js API route or server action, call your hono backend's getSession endpoint, forward the Set-Cookie header to the client, and trigger this route from the frontend on an interval or when needed.
  • If using the better-auth React client, use the useSession hook and call refetch() periodically to keep the session fresh.

References:

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3536732347 --> @dosubot[bot] commented on GitHub (Nov 15, 2025): <!-- Greeting --> Hi @ibrahimjel! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> To keep the cookieCache refreshed and avoid logout after 5 minutes, you need to trigger a session fetch from the frontend that allows the backend to set a new cookie before the cache expires. With recent better-auth versions, setting refreshCache: true (or using the new freshCache option) enables automatic refresh, but only if the client actually calls getSession or a similar endpoint in time for the backend to send a new Set-Cookie header. This does not happen automatically on the frontend unless you implement it. The recommended approach is to periodically call getSession (for example, using a React Query interval, a useEffect timer, or a custom hook) from the frontend. This fetch should be made in a context where the response's Set-Cookie header is forwarded to the browser—such as a Next.js API route, middleware, or client-side fetch with credentials included. This will refresh the cookieCache and keep the user logged in without requiring a full session fetch on every route. If you want to force a refresh, you can call getSession with disableCookieCache: true to bypass the cache and update the cookie immediately. Make sure your cookie settings use sameSite: 'none' and secure: true for cross-origin requests, and that your frontend correctly forwards and sets cookies from the backend response. Example: - In a Next.js API route or server action, call your hono backend's getSession endpoint, forward the Set-Cookie header to the client, and trigger this route from the frontend on an interval or when needed. - If using the better-auth React client, use the useSession hook and call refetch() periodically to keep the session fresh. References: - [refreshCache and freshCache details, and how automatic refresh works](https://github.com/better-auth/better-auth/pull/5601) - [How to force a refresh with disableCookieCache: true](https://github.com/better-auth/better-auth/issues/1516) - [Why periodic client-side getSession calls are needed](https://github.com/better-auth/better-auth/issues/1862) - [Cross-origin cookie settings and session forwarding](https://github.com/better-auth/better-auth/issues/4188) <!-- 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/42e89c45-49dd-4794-8b5f-2dd1d7b51888?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/42e89c45-49dd-4794-8b5f-2dd1d7b51888?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/42e89c45-49dd-4794-8b5f-2dd1d7b51888?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/42e89c45-49dd-4794-8b5f-2dd1d7b51888?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/42e89c45-49dd-4794-8b5f-2dd1d7b51888?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/42e89c45-49dd-4794-8b5f-2dd1d7b51888?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/42e89c45-49dd-4794-8b5f-2dd1d7b51888?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&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/6009)
Author
Owner

@ijmozn commented on GitHub (Nov 16, 2025):

when creating an authClient, I set the option refetch session every 5 min, assuming it will call get session but no api call is made to refresh the cache cookie, is is a bug?

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_API_URL,
  sessionOptions: {
    refetchInterval: 60 * 5, // 5 minutes
  },
  ...

6c9fe209e2/packages/better-auth/src/client/session-refresh.ts (L85-L96)

<!-- gh-comment-id:3538502472 --> @ijmozn commented on GitHub (Nov 16, 2025): when creating an authClient, I set the option refetch session every 5 min, assuming it will call get session but no api call is made to refresh the cache cookie, is is a bug? ``` export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_API_URL, sessionOptions: { refetchInterval: 60 * 5, // 5 minutes }, ... ``` https://github.com/better-auth/better-auth/blob/6c9fe209e212938c9b624ad718fc43bd6044ad27/packages/better-auth/src/client/session-refresh.ts#L85-L96
Author
Owner

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

Setting refetchInterval in createAuthClient does not trigger an API call to refresh the server-side session cookie—it only updates the local session cache. This is intended behavior, not a bug. To actually refresh the cookie and keep the session alive, you need to explicitly call getSession (or useSession().refetch()) from the client in a context where the Set-Cookie header can be set by the backend and received by the browser (like a client component, API route, or middleware) reference.

If you want to keep the cookieCache fresh, set up a timer or use a React hook to periodically call getSession from the frontend. This will ensure the backend can send a new cookie before the cache expires. The refetchInterval option in the client is for local cache polling and does not perform a server round-trip reference.

Let me know if you want an example of how to implement this in your Next.js app!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3538506131 --> @dosubot[bot] commented on GitHub (Nov 16, 2025): <!-- Answer --> Setting refetchInterval in createAuthClient does not trigger an API call to refresh the server-side session cookie—it only updates the local session cache. This is intended behavior, not a bug. To actually refresh the cookie and keep the session alive, you need to explicitly call getSession (or useSession().refetch()) from the client in a context where the Set-Cookie header can be set by the backend and received by the browser (like a client component, API route, or middleware) [reference](https://github.com/better-auth/better-auth/issues/2115). If you want to keep the cookieCache fresh, set up a timer or use a React hook to periodically call getSession from the frontend. This will ensure the backend can send a new cookie before the cache expires. The refetchInterval option in the client is for local cache polling and does not perform a server round-trip [reference](https://github.com/better-auth/better-auth/issues/1006). Let me know if you want an example of how to implement this in your Next.js app! <!-- 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/f16069c4-8d07-41cf-b143-6f12a3645ae8?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/f16069c4-8d07-41cf-b143-6f12a3645ae8?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/f16069c4-8d07-41cf-b143-6f12a3645ae8?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/f16069c4-8d07-41cf-b143-6f12a3645ae8?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/f16069c4-8d07-41cf-b143-6f12a3645ae8?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/f16069c4-8d07-41cf-b143-6f12a3645ae8?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/f16069c4-8d07-41cf-b143-6f12a3645ae8?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&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/6009)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#27723