[GH-ISSUE #2020] Cookie caching doesn't renew in SvelteKit #9009

Closed
opened 2026-04-13 04:16:06 -05:00 by GiteaMirror · 11 comments
Owner

Originally created by @elansx on GitHub (Mar 27, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/2020

Originally assigned to: @bytaesu on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Enable cookie caching in server-side for example for 30 seconds
  2. It creates session_data in browser and once it expires, it never renews via server-side api calls.
  3. Call auth.api.getSession() on server and even if we have valid session, session_data cookie never renews on client-side.

So this makes caching work only for the first cycle or until we use $session.refetch() on client side which is unnecessary double check.

Current vs. Expected behavior

no changes

What version of Better Auth are you using?

1.2.5

Provide environment information

- OS: Windows 10

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

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"

export const auth = betterAuth({
    session: {
        cookieCache: {
            enabled: true,
            maxAge: 10 // Cache duration in seconds
        }
    }
});

// so this function should renew session_data if caching is enabled:

const fetchedSession = await auth.api.getSession({
       headers: event.request.headers
});

// we could pass in event.cookies if needed.

Additional context

Maybe I something miss here and I need to call another function, but I think this behavior should be out-of-the-box since we set session caching.

I'm checking for valid session on each hit, so caching for few seconds or minutes would make sense to avoid hitting database each time.

Originally created by @elansx on GitHub (Mar 27, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/2020 Originally assigned to: @bytaesu on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Enable cookie caching in server-side for example for 30 seconds 2. It creates session_data in browser and once it expires, it never renews via server-side api calls. 3. Call auth.api.getSession() on server and even if we have valid session, session_data cookie never renews on client-side. So this makes caching work only for the first cycle or until we use $session.refetch() on client side which is unnecessary double check. ### Current vs. Expected behavior no changes ### What version of Better Auth are you using? 1.2.5 ### Provide environment information ```bash - OS: Windows 10 ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ session: { cookieCache: { enabled: true, maxAge: 10 // Cache duration in seconds } } }); // so this function should renew session_data if caching is enabled: const fetchedSession = await auth.api.getSession({ headers: event.request.headers }); // we could pass in event.cookies if needed. ``` ### Additional context Maybe I something miss here and I need to call another function, but I think this behavior should be out-of-the-box since we set session caching. I'm checking for valid session on each hit, so caching for few seconds or minutes would make sense to avoid hitting database each time.
GiteaMirror added the lockedbug labels 2026-04-13 04:16:06 -05:00
Author
Owner

@Bekacru commented on GitHub (Mar 27, 2025):

Since you're calling getSession on the server, it won't be able to set cookies in the browser unless you manually parse the headers and set the cookie yourself.

<!-- gh-comment-id:2758046647 --> @Bekacru commented on GitHub (Mar 27, 2025): Since you're calling `getSession` on the server, it won't be able to set cookies in the browser unless you manually parse the headers and set the cookie yourself.
Author
Owner

@elansx commented on GitHub (Mar 27, 2025):

// hooks.server.js
export const handle = async ({ event, resolve }) => {
   
  const getSession = await auth.api.getSession({
    headers: event.request.headers
  });

  event.cookies.set('session', 'abc', {
    path: '/',
    httpOnly: true,
    secure: true,
    sameSite: 'lax'
  });

return svelteKitHandler({ event, resolve, auth });
}

This works and the getSession function could accept cookies:

 const getSession = await auth.api.getSession({
    headers: event.request.headers,
    cookies: event.cookies
  });

I mean, I could set the cookie by myself from the session I get back, but I would need to know format on how does Better-Auth store these cached cookies, so basically return cookie object, that I can "manually" set via event.cookies.set.

Caching works on server, so it checks for client-side cookies. It returns session while there is session_data cookie on client-side, so it's checking that cookie from server, shouldn't be that hard to set it back once we fetch again from db and have caching enabled.

<!-- gh-comment-id:2758070790 --> @elansx commented on GitHub (Mar 27, 2025): ``` // hooks.server.js export const handle = async ({ event, resolve }) => { const getSession = await auth.api.getSession({ headers: event.request.headers }); event.cookies.set('session', 'abc', { path: '/', httpOnly: true, secure: true, sameSite: 'lax' }); return svelteKitHandler({ event, resolve, auth }); } ``` This works and the getSession function could accept cookies: ``` const getSession = await auth.api.getSession({ headers: event.request.headers, cookies: event.cookies }); ``` I mean, I could set the cookie by myself from the session I get back, but I would need to know format on how does Better-Auth store these cached cookies, so basically return cookie object, that I can "manually" set via event.cookies.set. **Caching works on server, so it checks for client-side cookies.** It returns session while there is session_data cookie on client-side, so it's checking that cookie from server, shouldn't be that hard to set it back once we fetch again from db and have caching enabled.
Author
Owner

@elansx commented on GitHub (Mar 31, 2025):

Since you're calling getSession on the server, it won't be able to set cookies in the browser unless you manually parse the headers and set the cookie yourself.

Okay, I digged a little deeper and now understand the issue.

Could we make setCookieCache to return encoded session to allow set cookie manually? Something like this:

let encodedSession = await setCookieCache(ctx, session);
if(ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache){
session.encodedSession = encodedSession;
}
return ctx.json(
session
);

And then we could just reset the cookie like this:

const session = await auth.api.getSession({
        headers: event.request.headers
      });

event.cookies.set('session_data', session.encodedSession) 
<!-- gh-comment-id:2766675074 --> @elansx commented on GitHub (Mar 31, 2025): > Since you're calling `getSession` on the server, it won't be able to set cookies in the browser unless you manually parse the headers and set the cookie yourself. Okay, I digged a little deeper and now understand the issue. Could we make setCookieCache to return encoded session to allow set cookie manually? Something like this: ``` let encodedSession = await setCookieCache(ctx, session); if(ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache){ session.encodedSession = encodedSession; } return ctx.json( session ); ``` And then we could just reset the cookie like this: ``` const session = await auth.api.getSession({ headers: event.request.headers }); event.cookies.set('session_data', session.encodedSession) ```
Author
Owner

@Omicrxn commented on GitHub (Apr 16, 2025):

any progress on this? getting the same issue, after login if i refresh the page i get session = null did you solve this? @elansx

<!-- gh-comment-id:2810763564 --> @Omicrxn commented on GitHub (Apr 16, 2025): any progress on this? getting the same issue, after login if i refresh the page i get session = null did you solve this? @elansx
Author
Owner

@elansx commented on GitHub (Apr 22, 2025):

any progress on this? getting the same issue, after login if i refresh the page i get session = null did you solve this? @elansx

Is your problem caching related? Mine was only with caching, that the api / server calls doesn't renew caching cookie, not login session cookie.

<!-- gh-comment-id:2820040949 --> @elansx commented on GitHub (Apr 22, 2025): > any progress on this? getting the same issue, after login if i refresh the page i get session = null did you solve this? @elansx Is your problem caching related? Mine was only with caching, that the api / server calls doesn't renew caching cookie, not login session cookie.
Author
Owner

@dosubot[bot] commented on GitHub (Jul 22, 2025):

Hi, @elansx. I'm Dosu, and I'm helping the better-auth team manage their backlog. I'm marking this issue as stale.

Issue Summary:

  • The issue involves cookie caching in SvelteKit with Better Auth version 1.2.5.
  • Session data does not renew automatically after expiration, requiring manual $session.refetch().
  • Bekacru suggests manually setting cookies in the browser due to getSession being server-side.
  • You proposed returning an encoded session from setCookieCache to allow manual cookie setting.
  • Omicrxn reported a similar issue, but you clarified it is specifically about caching.

Next Steps:

  • Please confirm if this issue is still relevant to the latest version of the better-auth repository by commenting here.
  • If there is no response, the issue will be automatically closed in 7 days.

Thank you for your understanding and contribution!

<!-- gh-comment-id:3103583931 --> @dosubot[bot] commented on GitHub (Jul 22, 2025): Hi, @elansx. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog. I'm marking this issue as stale. **Issue Summary:** - The issue involves cookie caching in SvelteKit with Better Auth version 1.2.5. - Session data does not renew automatically after expiration, requiring manual `$session.refetch()`. - Bekacru suggests manually setting cookies in the browser due to `getSession` being server-side. - You proposed returning an encoded session from `setCookieCache` to allow manual cookie setting. - Omicrxn reported a similar issue, but you clarified it is specifically about caching. **Next Steps:** - Please confirm if this issue is still relevant to the latest version of the better-auth repository by commenting here. - If there is no response, the issue will be automatically closed in 7 days. Thank you for your understanding and contribution!
Author
Owner

@IV2KBMoFxYIA commented on GitHub (Jan 12, 2026):

this still occurs. we need a fix.

<!-- gh-comment-id:3737084908 --> @IV2KBMoFxYIA commented on GitHub (Jan 12, 2026): this still occurs. we need a fix.
Author
Owner

@Bekacru commented on GitHub (Jan 12, 2026):

@bytaesu

<!-- gh-comment-id:3737094446 --> @Bekacru commented on GitHub (Jan 12, 2026): @bytaesu
Author
Owner

@bytaesu commented on GitHub (Jan 12, 2026):

@IV2KBMoFxYIA @Bekacru

Let me check 🙂

<!-- gh-comment-id:3737101385 --> @bytaesu commented on GitHub (Jan 12, 2026): @IV2KBMoFxYIA @Bekacru Let me check 🙂
Author
Owner

@bytaesu commented on GitHub (Jan 13, 2026):

Hi @IV2KBMoFxYIA,

I followed our docs and set everything up from scratch, and the issue doesn't reproduce on my end.

Could you try using svelteKitHandler and sveltekitCookies following guides, and if the problem persists, could you share a reproducible repo? I will take a look 🙂

https://www.better-auth.com/docs/integrations/svelte-kit

<!-- gh-comment-id:3745833867 --> @bytaesu commented on GitHub (Jan 13, 2026): Hi @IV2KBMoFxYIA, I followed our docs and set everything up from scratch, and the issue doesn't reproduce on my end. Could you try using `svelteKitHandler` and `sveltekitCookies` following guides, and if the problem persists, could you share a reproducible repo? I will take a look 🙂 https://www.better-auth.com/docs/integrations/svelte-kit
Author
Owner

@bytaesu commented on GitHub (Jan 27, 2026):

Hi @IV2KBMoFxYIA,

I followed our docs and set everything up from scratch, and the issue doesn't reproduce on my end.

Could you try using svelteKitHandler and sveltekitCookies following guides, and if the problem persists, could you share a reproducible repo? I will take a look 🙂

https://www.better-auth.com/docs/integrations/svelte-kit

I'm closing this issue.
If the issue persists, check this comment and feel free to mention me 🙂

<!-- gh-comment-id:3802901022 --> @bytaesu commented on GitHub (Jan 27, 2026): > Hi [@IV2KBMoFxYIA](https://github.com/IV2KBMoFxYIA), > > I followed our docs and set everything up from scratch, and the issue doesn't reproduce on my end. > > Could you try using `svelteKitHandler` and `sveltekitCookies` following guides, and if the problem persists, could you share a reproducible repo? I will take a look 🙂 > > https://www.better-auth.com/docs/integrations/svelte-kit I'm closing this issue. If the issue persists, check this comment and feel free to mention me 🙂
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#9009