[GH-ISSUE #6672] client.getSession returned null, but session exist #10593

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

Originally created by @SokSashaa on GitHub (Dec 10, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6672

Originally assigned to: @bytaesu on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Create a Better Auth Instance

  2. Create function 'getTokens' that puts jwt tokens in cookies.(Based on the response from another issue)

  3. Create a client
    import type {authOptions} from './auth-options'; export const {signIn, signOut, useSession, getSession} = createAuthClient({ plugins: [genericOAuthClient(), customSessionClient<typeof authOptions>()], });

  4. Create a Page
    export default async function HomePage() { const session = await getSession(); console.log(session); return ( <div className={styles.page}> <main className={styles.main}> <h1 className={styles.title}>Hello </h1> <LogoutButton /> </main> </div> ); }

Current vs. Expected behavior

I'm using Next.js 16
I'm using cookies to store jwt tokens based on advice from another issue.

When a session is retrieved, the page returns null, even though the response code is 200 and the session is returned. If you put console.log in a custom session, the session exists

Image Image

What version of Better Auth are you using?

1.4.6

System info

{
  "system": {
    "platform": "win32",
    "arch": "x64",
    "version": "Windows 11 Home Single Language",
    "release": "10.0.26100",
    "cpuCount": 8,
    "cpuModel": "11th Gen Intel(R) Core(TM) i7-11370H @ 3.30GHz",
    "totalMemory": "31.75 GB",
    "freeMemory": "14.47 GB"
  },
  "node": {
    "version": "v24.11.1",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "11.6.2"
  },
  "frameworks": [
    {
      "name": "next",
      "version": "16.0.7"
    },
    {
      "name": "react",
      "version": "19.2.0"
    }
  ],
  "databases": null,
  "betterAuth": {
    "version": "^1.4.6",
    "config": null
  }
}

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

Backend

Auth config (if applicable)

export const authOptions = betterAuth({
    plugins: [
        genericOAuth({
            config: [
                {
                    providerId: 'keycloak',
                    clientId: process.env.CLIENT_ID || '',
                    clientSecret: process.env.CLIENT_SECRET || '',
                    discoveryUrl: process.env.KEYCLOAK_CONFIGURATION_URL,
                    scopes: ['openid', 'email', 'profile'],
                    getToken: async ({code, redirectURI}): Promise<OAuth2Tokens> => {
                        const {access_token, refresh_token} = await getTokens(code, redirectURI);

                        return {
                            accessToken: access_token,
                            refreshToken: refresh_token,
                        };
                    },
                    
                },
            ],
        }),
        customSession(async ({user, session}) => {
            const accessToken = (await getCookies(CookieKeys.AccessToken)) as string;
            const refreshToken = (await getCookies(CookieKeys.RefreshToken)) as string;

            const decodedAccessToken = decodeToken(accessToken);

            const userRoles = (decodedAccessToken?.roles as string[]) || [];

            return {
                user,
                session: {
                    ...session,
                    userRoles,
                    refreshToken,
                    accessToken,
                },
            };
        }),
    ],
    session: {
        expiresIn: 24 * 60 * 60,
    },
    hooks: {
        before: createAuthMiddleware(async (ctx) => {
            if (ctx.path.startsWith('/get-session')) {
                const refreshToken = await getCookies(CookieKeys.RefreshToken);
                if (!refreshToken) {
                    await deleteCookiesByPrefix('better');
                    await deleteCookies(CookieKeys.AccessToken);
                    return;
                }

                const accessToken = await getCookies(CookieKeys.AccessToken);
                await checkExpiresAccessToken(refreshToken, accessToken);
            }
        }),
        after: createAuthMiddleware(async (ctx) => {
            if (ctx.path.startsWith('/get-session')) {
                if (!ctx.context.session) {
                    await deleteCookies(CookieKeys.AccessToken, CookieKeys.RefreshToken);
                }
            }
        }),
    },
});

Additional context

No response

Originally created by @SokSashaa on GitHub (Dec 10, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6672 Originally assigned to: @bytaesu on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Create a Better Auth Instance 2. Create function 'getTokens' that puts jwt tokens in cookies.(Based on the response from another issue) 3. Create a client `import type {authOptions} from './auth-options'; export const {signIn, signOut, useSession, getSession} = createAuthClient({ plugins: [genericOAuthClient(), customSessionClient<typeof authOptions>()], });` 4. Create a Page `export default async function HomePage() { const session = await getSession(); console.log(session); return ( <div className={styles.page}> <main className={styles.main}> <h1 className={styles.title}>Hello </h1> <LogoutButton /> </main> </div> ); }` ### Current vs. Expected behavior I'm using Next.js 16 I'm using cookies to store jwt tokens based on advice from another issue. When a session is retrieved, the page returns null, even though the response code is 200 and the session is returned. If you put console.log in a custom session, the session exists <img width="578" height="65" alt="Image" src="https://github.com/user-attachments/assets/8e2fdcc3-744d-428e-ac78-6a0337f92178" /> <img width="214" height="219" alt="Image" src="https://github.com/user-attachments/assets/a413aa43-2b61-46e2-8698-a722448572e2" /> ### What version of Better Auth are you using? 1.4.6 ### System info ```bash { "system": { "platform": "win32", "arch": "x64", "version": "Windows 11 Home Single Language", "release": "10.0.26100", "cpuCount": 8, "cpuModel": "11th Gen Intel(R) Core(TM) i7-11370H @ 3.30GHz", "totalMemory": "31.75 GB", "freeMemory": "14.47 GB" }, "node": { "version": "v24.11.1", "env": "development" }, "packageManager": { "name": "npm", "version": "11.6.2" }, "frameworks": [ { "name": "next", "version": "16.0.7" }, { "name": "react", "version": "19.2.0" } ], "databases": null, "betterAuth": { "version": "^1.4.6", "config": null } } ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript export const authOptions = betterAuth({ plugins: [ genericOAuth({ config: [ { providerId: 'keycloak', clientId: process.env.CLIENT_ID || '', clientSecret: process.env.CLIENT_SECRET || '', discoveryUrl: process.env.KEYCLOAK_CONFIGURATION_URL, scopes: ['openid', 'email', 'profile'], getToken: async ({code, redirectURI}): Promise<OAuth2Tokens> => { const {access_token, refresh_token} = await getTokens(code, redirectURI); return { accessToken: access_token, refreshToken: refresh_token, }; }, }, ], }), customSession(async ({user, session}) => { const accessToken = (await getCookies(CookieKeys.AccessToken)) as string; const refreshToken = (await getCookies(CookieKeys.RefreshToken)) as string; const decodedAccessToken = decodeToken(accessToken); const userRoles = (decodedAccessToken?.roles as string[]) || []; return { user, session: { ...session, userRoles, refreshToken, accessToken, }, }; }), ], session: { expiresIn: 24 * 60 * 60, }, hooks: { before: createAuthMiddleware(async (ctx) => { if (ctx.path.startsWith('/get-session')) { const refreshToken = await getCookies(CookieKeys.RefreshToken); if (!refreshToken) { await deleteCookiesByPrefix('better'); await deleteCookies(CookieKeys.AccessToken); return; } const accessToken = await getCookies(CookieKeys.AccessToken); await checkExpiresAccessToken(refreshToken, accessToken); } }), after: createAuthMiddleware(async (ctx) => { if (ctx.path.startsWith('/get-session')) { if (!ctx.context.session) { await deleteCookies(CookieKeys.AccessToken, CookieKeys.RefreshToken); } } }), }, }); ``` ### Additional context _No response_
GiteaMirror added the lockedbug labels 2026-04-13 06:50:06 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 10, 2025):

(No response)

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

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3638576853 --> @better-auth-agent[bot] commented on GitHub (Dec 10, 2025): (No response) _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/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

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

This is a common issue in Better Auth and is almost always caused by how cookies are set or sent. Even if your backend session exists and returns 200, getSession will return null if the session cookie is missing, not signed, or not URL-encoded as expected by Better Auth.

Here’s what to check and try:

  • If you’re manually setting cookies with JWT tokens, don’t just set the raw token. Better Auth expects a signed and URL-encoded cookie value. Use the official helper (like authClient.getCookie()) to generate the cookie string, not just the token. Manually setting the cookie with a raw token will cause silent validation failure and getSession will return null, even if the session exists in your DB or backend [source] [source].

  • If you’re using Next.js server components or have frontend/backend on different ports/domains, the server does not automatically have access to browser cookies. You need to explicitly forward the cookie header from the browser to your auth backend. The recommended pattern is to create a custom server action or proxy API route in Next.js that fetches the session from your auth server, passing the cookie header [source] [source].

  • Make sure your cookie settings (sameSite, secure, path, domain) are correct for your environment. For cross-origin, use sameSite: 'none' and secure: true. For local development, secure: false and no __Secure- prefix [source].

  • In Better Auth v1.3.18 and above, getSession relies on the session_data cookie, which is only set/read if session.cookieCache.enabled is true. Make sure you have session: { cookieCache: { enabled: true } } in your config [source].

  • If you’re on an older version, upgrade to the latest Better Auth. There was a bug (fixed in PR #3283, merged 2025-07-26) where mismatched expiresAt timestamps between the cookie and its signature could cause getSession to return null [source].

  • If you use the customSession plugin, be aware it simply wraps getSession and will also return null if the underlying session is missing or invalid. It does not “fix” cookie issues [source].

  • If you’re using Next.js, proxying API calls through Next.js API routes (so they’re on the same domain) can help avoid cross-origin cookie issues [source].

In summary: Always use the official cookie helpers, check your cookie config, forward cookies explicitly in server components, and make sure cookieCache is enabled. If you do all this and still see null, enable debug logging and inspect the actual cookie values being sent and received.

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:3638593406 --> @dosubot[bot] commented on GitHub (Dec 10, 2025): <!-- Answer --> This is a common issue in Better Auth and is almost always caused by how cookies are set or sent. Even if your backend session exists and returns 200, getSession will return null if the session cookie is missing, not signed, or not URL-encoded as expected by Better Auth. Here’s what to check and try: - If you’re manually setting cookies with JWT tokens, don’t just set the raw token. Better Auth expects a signed and URL-encoded cookie value. Use the official helper (like authClient.getCookie()) to generate the cookie string, not just the token. Manually setting the cookie with a raw token will cause silent validation failure and getSession will return null, even if the session exists in your DB or backend [[source]](https://github.com/better-auth/better-auth/issues/3892#issuecomment-3170283606) [[source]](https://github.com/better-auth/better-auth/issues/4517). - If you’re using Next.js server components or have frontend/backend on different ports/domains, the server does not automatically have access to browser cookies. You need to explicitly forward the cookie header from the browser to your auth backend. The recommended pattern is to create a custom server action or proxy API route in Next.js that fetches the session from your auth server, passing the cookie header [[source]](https://github.com/better-auth/better-auth/issues/4188) [[source]](https://github.com/better-auth/better-auth/issues/4044). - Make sure your cookie settings (sameSite, secure, path, domain) are correct for your environment. For cross-origin, use sameSite: 'none' and secure: true. For local development, secure: false and no __Secure- prefix [[source]](https://github.com/better-auth/better-auth/issues/4517). - In Better Auth v1.3.18 and above, getSession relies on the session_data cookie, which is only set/read if session.cookieCache.enabled is true. Make sure you have session: { cookieCache: { enabled: true } } in your config [[source]](https://github.com/better-auth/better-auth/issues/4942). - If you’re on an older version, upgrade to the latest Better Auth. There was a bug (fixed in PR #3283, merged 2025-07-26) where mismatched expiresAt timestamps between the cookie and its signature could cause getSession to return null [[source]](https://github.com/better-auth/better-auth/issues/4517). - If you use the customSession plugin, be aware it simply wraps getSession and will also return null if the underlying session is missing or invalid. It does not “fix” cookie issues [[source]](https://github.com/better-auth/better-auth/blob/e216af8d49dc422cbbe05d170c103bd565250a7c/packages/better-auth/src/plugins/custom-session/index.ts#L15-L135). - If you’re using Next.js, proxying API calls through Next.js API routes (so they’re on the same domain) can help avoid cross-origin cookie issues [[source]](https://github.com/better-auth/better-auth/issues/4044). In summary: Always use the official cookie helpers, check your cookie config, forward cookies explicitly in server components, and make sure cookieCache is enabled. If you do all this and still see null, enable debug logging and inspect the actual cookie values being sent and received. <!-- 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/94e8462d-599b-4553-967f-7c86d2dcc560?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/94e8462d-599b-4553-967f-7c86d2dcc560?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/94e8462d-599b-4553-967f-7c86d2dcc560?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/94e8462d-599b-4553-967f-7c86d2dcc560?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/94e8462d-599b-4553-967f-7c86d2dcc560?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/94e8462d-599b-4553-967f-7c86d2dcc560?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/94e8462d-599b-4553-967f-7c86d2dcc560?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=This%20is%20a%20common%20issue%20in%20Better%20Auth%20and%20is%20almost%20always%20caused%20by%20how%20cookies%20are%20set%20or%20sent.%20Even%20if%20your%20backend%20session%20exists%20and%20returns%20200%2C%20getSession%20will%20return%20null%20if%20the%20session%20cookie%20is%20missing%2C%20not%20signed%2C%20or%20not%20URL-encoded%20as%20expected%20by%20Better%20Auth.%0A%0AHere%E2%80%99s%20what%20to%20check%20and%20try%3A%0A%0A-%20If%20you%E2%80%99re%20manually%20setting%20cookies%20with%20JWT%20tokens%2C%20don%E2%80%99t%20just%20set%20the%20raw%20token.%20Better%20Auth%20expects%20a%20signed%20and%20URL-encoded%20cookie%20value.%20Use%20the%20official%20helper%20%28like%20authClient.getCookie%28%29%29%20to%20generate%20the%20cookie%20string%2C%20not%20just%20the%20token.%20Manually%20setting%20the%20cookie%20with%20a%20raw%20token%20will%20cause%20silent%20validation%20failure%20and%20getSession%20will%20return%20null%2C%20even%20if%20the%20session%20exists%20in%20your%20DB%20or%20backend%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/3892%23issuecomment-3170283606%29%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4517%29.%0A%0A-%20If%20you%E2%80%99re%20using%20Next.js%20server%20components%20or%20have%20frontend/backend%20on%20different%20ports/domains%2C%20the%20server%20does%20not%20automatically%20have%20access%20to%20browser%20cookies.%20You%20need%20to%20explicitly%20forward%20the%20cookie%20header%20from%20the%20browser%20to%20your%20auth%20backend.%20The%20recommended%20pattern%20is%20to%20create%20a%20custom%20server%20action%20or%20proxy%20API%20route%20in%20Next.js%20that%20fetches%20the%20session%20from%20your%20auth%20server%2C%20passing%20the%20cookie%20header%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4188%29%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4044%29.%0A%0A-%20Make%20sure%20your%20cookie%20settings%20%28sameSite%2C%20secure%2C%20path%2C%20domain%29%20are%20correct%20for%20your%20environment.%20For%20cross-origin%2C%20use%20sameSite%3A%20%27none%27%20and%20secure%3A%20true.%20For%20local%20development%2C%20secure%3A%20false%20and%20no%20__Secure-%20prefix%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4517%29.%0A%0A-%20In%20Better%20Auth%20v1.3.18%20and%20above%2C%20getSession%20relies%20on%20the%20session_data%20cookie%2C%20which%20is%20only%20set/read%20if%20session.cookieCache.enabled%20is%20true.%20Make%20sure%20you%20have%20session%3A%20%7B%20cookieCache%3A%20%7B%20enabled%3A%20true%20%7D%20%7D%20in%20your%20config%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4942%29.%0A%0A-%20If%20you%E2%80%99re%20on%20an%20older%20version%2C%20upgrade%20to%20the%20latest%20Better%20Auth.%20There%20was%20a%20bug%20%28fixed%20in%20PR%20%233283%2C%20merged%202025-07-26%29%20where%20mismatched%20expiresAt%20timestamps%20between%20the%20cookie%20and%20its%20signature%20could%20cause%20getSession%20to%20return%20null%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4517%29.%0A%0A-%20If%20you%20use%20the%20customSession%20plugin%2C%20be%20aware%20it%20simply%20wraps%20getSession%20and%20will%20also%20return%20null%20if%20the%20underlying%20session%20is%20missing%20or%20invalid.%20It%20does%20not%20%E2%80%9Cfix%E2%80%9D%20cookie%20issues%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/blob/e216af8d49dc422cbbe05d170c103bd565250a7c/packages/better-auth/src/plugins/custom-session/index.ts%23L15-L135%29.%0A%0A-%20If%20you%E2%80%99re%20using%20Next.js%2C%20proxying%20API%20calls%20through%20Next.js%20API%20routes%20%28so%20they%E2%80%99re%20on%20the%20same%20domain%29%20can%20help%20avoid%20cross-origin%20cookie%20issues%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4044%29.%0A%0AIn%20summary%3A%20Always%20use%20the%20official%20cookie%20helpers%2C%20check%20your%20cookie%20config%2C%20forward%20cookies%20explicitly%20in%20server%20components%2C%20and%20make%20sure%20cookieCache%20is%20enabled.%20If%20you%20do%20all%20this%20and%20still%20see%20null%2C%20enable%20debug%20logging%20and%20inspect%20the%20actual%20cookie%20values%20being%20sent%20and%20received.)&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/6672)
Author
Owner

@Micnubinub commented on GitHub (Dec 18, 2025):

I am getting the same issue with a bun and hono setup. I have a custom adapter (surrealDB)I am logging the findOne and findMany methods and the lib is calling them and getting the response, but in the front end where I am getting null with a 200. Looking through the code in better-auth > src > api > routes > session.ts > getSession the lib just calls return ctx.json(null);. Could we please get better messaging and better codes (400 range)


Found my solution. Seems to have been that I wasn't calling joining the items in the join[] in findOne and findMany. I would have found the issue faster if I had the errors sent i.e. {code 40x, msg: user null/empty/undefined}. Please add errors

<!-- gh-comment-id:3670940907 --> @Micnubinub commented on GitHub (Dec 18, 2025): I am getting the same issue with a `bun` and `hono` setup. I have a custom adapter (surrealDB)I am logging the `findOne` and `findMany` methods and the lib is calling them and getting the response, but in the front end where I am getting `null` with a `200`. Looking through the code in `better-auth > src > api > routes > session.ts > getSession` the lib just calls `return ctx.json(null);`. Could we please get better messaging and better codes (400 range) --- Found my solution. Seems to have been that I wasn't calling joining the items in the `join[]` in `findOne` and `findMany`. I would have found the issue faster if I had the errors sent i.e. `{code 40x, msg: user null/empty/undefined}`. Please add errors
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 19, 2025):

It appears there is a known issue regarding the getSession function returning null even when a session exists. Users have reported that despite receiving a 200 response and confirming the session's existence, the getSession function returns null.

Possible Solutions and Next Steps:

  1. Ensure Proper Configuration: Check your Better Auth configuration to ensure that session management is set up correctly, including proper middleware handling [1].

  2. Debugging Hooks: Utilize the provided hooks (e.g., before and after hooks) to inspect and modify requests and responses. These hooks can help troubleshoot why sessions might not be fetched properly [3].

  3. Using useSession: If you're not already doing so, consider using the useSession hook, which can provide a reactive way to manage session data on the client side [1].

  4. Check Cookie Settings: Verify that the cookies are correctly set and sent with requests, as issues with cookie management could lead to getSession returning null. Focus on the expiration and settings of the cookies being used [2].

  5. Look for Updates: Given that Better Auth is actively maintained, check if you are using the latest version. Improvements and bug fixes occur regularly [4].

If the issue persists after trying these steps, I recommend tagging @bekacru or @ping__ for personalized assistance from the Better Auth team. They may provide insights based on their deep familiarity with the framework.

What specific areas are you having trouble with regarding session management?

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3676284728 --> @better-auth-agent[bot] commented on GitHub (Dec 19, 2025): It appears there is a known issue regarding the `getSession` function returning null even when a session exists. Users have reported that despite receiving a 200 response and confirming the session's existence, the `getSession` function returns null. **Possible Solutions and Next Steps:** 1. **Ensure Proper Configuration:** Check your Better Auth configuration to ensure that session management is set up correctly, including proper middleware handling [[1]](https://www.better-auth.com/docs/basic-usage). 2. **Debugging Hooks:** Utilize the provided hooks (e.g., `before` and `after` hooks) to inspect and modify requests and responses. These hooks can help troubleshoot why sessions might not be fetched properly [[3]](https://github.com/better-auth/better-auth/issues/6530). 3. **Using `useSession`:** If you're not already doing so, consider using the `useSession` hook, which can provide a reactive way to manage session data on the client side [[1]](https://www.better-auth.com/docs/basic-usage). 4. **Check Cookie Settings:** Verify that the cookies are correctly set and sent with requests, as issues with cookie management could lead to `getSession` returning null. Focus on the expiration and settings of the cookies being used [[2]](https://github.com/better-auth/better-auth/pull/4947). 5. **Look for Updates:** Given that Better Auth is actively maintained, check if you are using the latest version. Improvements and bug fixes occur regularly [[4]](https://github.com/better-auth/better-auth/issues/4584). If the issue persists after trying these steps, I recommend tagging @bekacru or @ping__ for personalized assistance from the Better Auth team. They may provide insights based on their deep familiarity with the framework. What specific areas are you having trouble with regarding session management? <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 19, 2025):

The issue of client.getSession returning null even when a session exists has been noted by other users. Here are some potential troubleshooting steps based on similar reports:

  1. Check Cookie Handling: Ensure that cookies are correctly set and sent with requests. The session retrieval may fail if the cookies carrying the session token are not present or are misconfigured. You might want to check the fetchOptions in your client settings to ensure cookies are included in requests [1].

  2. Correct Header Passing: Make sure that the headers are properly passed to the getSession method; this is crucial in frameworks like Next.js. Proper integration often requires passing request headers when calling getSession from server-side components. For example:

    const session = await auth.api.getSession({ headers: req.headers });
    
  3. Session Configuration: Review the configuration of your session management, especially the cookieCache. If cookieCache isn't set correctly or is disabled, it could lead to issues where getSession fails to retrieve valid session data [2].

  4. Version Update: You mentioned version 1.4.7. Make sure you are using the latest version, as updates may include fixes for known issues regarding session management [3].

If you're still facing issues, consider tagging team members such as @bekacru or @ping__ for further assistance. What specific errors or behavior are you observing when attempting to retrieve the session? This could help narrow down the troubleshooting process.

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3676286579 --> @better-auth-agent[bot] commented on GitHub (Dec 19, 2025): The issue of `client.getSession` returning null even when a session exists has been noted by other users. Here are some potential troubleshooting steps based on similar reports: 1. **Check Cookie Handling**: Ensure that cookies are correctly set and sent with requests. The session retrieval may fail if the cookies carrying the session token are not present or are misconfigured. You might want to check the `fetchOptions` in your client settings to ensure cookies are included in requests [[1]](https://www.better-auth.com/docs/basic-usage). 2. **Correct Header Passing**: Make sure that the headers are properly passed to the `getSession` method; this is crucial in frameworks like Next.js. Proper integration often requires passing request headers when calling `getSession` from server-side components. For example: ```javascript const session = await auth.api.getSession({ headers: req.headers }); ``` 3. **Session Configuration**: Review the configuration of your session management, especially the `cookieCache`. If `cookieCache` isn't set correctly or is disabled, it could lead to issues where `getSession` fails to retrieve valid session data [[2]](https://github.com/better-auth/better-auth/pull/4947). 4. **Version Update**: You mentioned version 1.4.7. Make sure you are using the latest version, as updates may include fixes for known issues regarding session management [[3]](https://github.com/better-auth/better-auth/issues/6530). If you're still facing issues, consider tagging team members such as @bekacru or @ping__ for further assistance. What specific errors or behavior are you observing when attempting to retrieve the session? This could help narrow down the troubleshooting process. <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

@surafel58 commented on GitHub (Dec 19, 2025):

@better-auth-agent is this resolved on the new version ? better auth 1.4.7

<!-- gh-comment-id:3676286972 --> @surafel58 commented on GitHub (Dec 19, 2025): @better-auth-agent is this resolved on the new version ? better auth 1.4.7
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 19, 2025):

It seems that you're encountering an issue where client.getSession returns null even though a session exists. This problem may stem from a couple of potential causes:

  1. Session Cache: There could be caching issues if session.cookieCache is not set. Make sure that this configuration option is properly set to avoid returning null due to cached sessions not being updated appropriately [1].

  2. Headers in getSession Call: When calling getSession, it’s crucial to pass the correct headers, as the session might not get retrieved properly without them. For example, ensure that you are using headers: await headers() when making the call in server-side components [2][3].

  3. Using the Correct Version: You mentioned using Better Auth 1.4.6, but checking for updates to 1.4.7 might be worthwhile, as new versions often include bug fixes related to session management [2].

  4. Custom Session Handling: Ensure that your custom session handling (via the customSession plugin) correctly handles the decoding and retrieval of tokens from cookies. If there's an issue in this custom logic, it could lead to incorrectly handling the session state [1].

To troubleshoot further, consider explicitly logging the session retrieval process and checking the cookie settings to ensure that cookies are being sent correctly from the client.

If the problem persists, I recommend engaging with the Better Auth team directly by tagging them (@bekacru or @ping__) for more personalized support.

What specific steps have you already taken to troubleshoot this issue?

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3676287549 --> @better-auth-agent[bot] commented on GitHub (Dec 19, 2025): It seems that you're encountering an issue where `client.getSession` returns null even though a session exists. This problem may stem from a couple of potential causes: 1. **Session Cache**: There could be caching issues if `session.cookieCache` is not set. Make sure that this configuration option is properly set to avoid returning null due to cached sessions not being updated appropriately [[1]](https://www.better-auth.com/docs/basic-usage). 2. **Headers in `getSession` Call**: When calling `getSession`, it’s crucial to pass the correct headers, as the session might not get retrieved properly without them. For example, ensure that you are using `headers: await headers()` when making the call in server-side components [[2]](https://github.com/better-auth/better-auth/pull/4947)[[3]](https://github.com/better-auth/better-auth/issues/6530). 3. **Using the Correct Version**: You mentioned using Better Auth 1.4.6, but checking for updates to 1.4.7 might be worthwhile, as new versions often include bug fixes related to session management [[2]](https://github.com/better-auth/better-auth/pull/4947). 4. **Custom Session Handling**: Ensure that your custom session handling (via the `customSession` plugin) correctly handles the decoding and retrieval of tokens from cookies. If there's an issue in this custom logic, it could lead to incorrectly handling the session state [[1]](https://www.better-auth.com/docs/basic-usage). To troubleshoot further, consider explicitly logging the session retrieval process and checking the cookie settings to ensure that cookies are being sent correctly from the client. If the problem persists, I recommend engaging with the Better Auth team directly by tagging them (@bekacru or @ping__) for more personalized support. What specific steps have you already taken to troubleshoot this issue? <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

@surafel58 commented on GitHub (Dec 19, 2025):

@dosu is this resolved on the new version ? better auth 1.4.7

<!-- gh-comment-id:3676289852 --> @surafel58 commented on GitHub (Dec 19, 2025): @dosu is this resolved on the new version ? better auth 1.4.7
Author
Owner

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

Hi, I'm checking this 🙂

<!-- gh-comment-id:3761147871 --> @bytaesu commented on GitHub (Jan 16, 2026): Hi, I'm checking this 🙂
Author
Owner

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

Since your <HomePage/> is async, it appears to be a Server Component. In that case, you should use auth.api.getSession instead of authClient. getSession.

You can still use authClient, but in a server environment browser cookies are not automatically forwarded, so you’d need to attach the cookies for it to work.

Tip

You may find this implementation helpful as a reference 🙂
https://github.com/bytaesu/better-auth-separate-backend/blob/main/apps/nextjs/lib/auth/auth-server.ts

<!-- gh-comment-id:3761274488 --> @bytaesu commented on GitHub (Jan 16, 2026): Since your `<HomePage/>` is async, it appears to be a Server Component. In that case, you should use `auth.api.getSession` instead of `authClient. getSession`. You can still use authClient, but in a server environment browser cookies are not automatically forwarded, so you’d need to attach the cookies for it to work. > [!TIP] > You may find this implementation helpful as a reference 🙂 > https://github.com/bytaesu/better-auth-separate-backend/blob/main/apps/nextjs/lib/auth/auth-server.ts
Author
Owner

@himself65 commented on GitHub (Jan 21, 2026):

https://www.better-auth.com/docs/reference/faq#getsession-not-working

<!-- gh-comment-id:3781298417 --> @himself65 commented on GitHub (Jan 21, 2026): https://www.better-auth.com/docs/reference/faq#getsession-not-working
Author
Owner

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

There's one thing I noticed is that the getSession only gives the session.data cookie and not the session.token which is required for the requests. I am currently using Hono and React as frontend but I just want to use hono server to interact with the auth api instead of using the authClient as I am having a micro-services setup. Can we do something here so that I get the session.token updated as if we cache it is lives for 5 mins by default and I would like to keep it that way..

<!-- gh-comment-id:3806262125 --> @pranavgoel29 commented on GitHub (Jan 27, 2026): There's one thing I noticed is that the getSession only gives the `session.data` cookie and not the `session.token` which is required for the requests. I am currently using Hono and React as frontend but I just want to use hono server to interact with the auth api instead of using the authClient as I am having a micro-services setup. Can we do something here so that I get the `session.token` updated as if we cache it is lives for 5 mins by default and I would like to keep it that way..
Author
Owner

@github-actions[bot] commented on GitHub (Apr 1, 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:4166561822 --> @github-actions[bot] commented on GitHub (Apr 1, 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#10593