[GH-ISSUE #3353] Error with getJwtToken on newSession: TypeError: Cannot read properties of null (reading 'user') #9577

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

Originally created by @izakfilmalter on GitHub (Jul 12, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/3353

I copied the setup @Bekacru did and ran into the same issue: https://github.com/rocicorp/ztunes/pull/9#issuecomment-3026768995

Code:

after: createAuthMiddleware(async ctx => {
  if (ctx.path.indexOf('/callback/') !== -1) {
    const headers = must(ctx.context.responseHeaders);
    const session = ctx.context.newSession;
    const token =
      ctx.context.responseHeaders?.get('set-auth-jwt') ||
      (await getJwtToken(ctx));

    if (session && token) {
      setCookies(headers, {
        userid: session.user.id,
        email: session.user.email,
        jwt: token,
      });
    }
    return;
  }

  if (ctx.path.indexOf('/sign-out') !== -1) {
    const headers = must(ctx.context.responseHeaders);
    setCookies(headers, {
      userid: '',
      email: '',
      jwt: '',
    });
    return;
  }
})

Error:

TypeError: Cannot read properties of null (reading 'user')
    at getJwtToken (file:///Users/izakfilmalter/Projects/FaithBase/openfaith/node_modules/better-auth/dist/plugins/jwt/index.mjs:108:70)
    at async onSome (/Users/izakfilmalter/Projects/FaithBase/openfaith/packages/auth/auth.ts:143:68)
    at async eval (/Users/izakfilmalter/Projects/FaithBase/openfaith/packages/auth/auth.ts:132:7)

Source:
3fed4c0f70/packages/better-auth/src/plugins/jwt/index.ts (L179)

This issue comes from not having session but having newSession. I have done the following to work around the issue for now:

    const session = ctx.context.newSession;
    ctx.context.session = session // Force the newSession as the session so that `getJwtToken` doesn't error.
    const token =
      ctx.context.responseHeaders?.get('set-auth-jwt') ||
      (await getJwtToken(ctx));

Originally created by @izakfilmalter on GitHub (Jul 12, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/3353 I copied the setup @Bekacru did and ran into the same issue: https://github.com/rocicorp/ztunes/pull/9#issuecomment-3026768995 Code: ```ts after: createAuthMiddleware(async ctx => { if (ctx.path.indexOf('/callback/') !== -1) { const headers = must(ctx.context.responseHeaders); const session = ctx.context.newSession; const token = ctx.context.responseHeaders?.get('set-auth-jwt') || (await getJwtToken(ctx)); if (session && token) { setCookies(headers, { userid: session.user.id, email: session.user.email, jwt: token, }); } return; } if (ctx.path.indexOf('/sign-out') !== -1) { const headers = must(ctx.context.responseHeaders); setCookies(headers, { userid: '', email: '', jwt: '', }); return; } }) ``` Error: ``` TypeError: Cannot read properties of null (reading 'user') at getJwtToken (file:///Users/izakfilmalter/Projects/FaithBase/openfaith/node_modules/better-auth/dist/plugins/jwt/index.mjs:108:70) at async onSome (/Users/izakfilmalter/Projects/FaithBase/openfaith/packages/auth/auth.ts:143:68) at async eval (/Users/izakfilmalter/Projects/FaithBase/openfaith/packages/auth/auth.ts:132:7) ``` Source: https://github.com/better-auth/better-auth/blob/3fed4c0f70202bfadda0a0619016a721dacd7312/packages/better-auth/src/plugins/jwt/index.ts#L179 This issue comes from not having `session` but having `newSession`. I have done the following to work around the issue for now: ```ts const session = ctx.context.newSession; ctx.context.session = session // Force the newSession as the session so that `getJwtToken` doesn't error. const token = ctx.context.responseHeaders?.get('set-auth-jwt') || (await getJwtToken(ctx)); ```
GiteaMirror added the lockedbug labels 2026-04-13 05:06:20 -05:00
Author
Owner

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

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

The error happens because getJwtToken only looks for ctx.context.session and doesn't check ctx.context.newSession, so if session is null you'll get a TypeError when it tries to access session.user. Your workaround—assigning newSession to session before calling getJwtToken—is necessary in this flow and matches what the code expects. There isn't a more idiomatic or built-in way to handle this in better-auth right now; the framework expects session to be set when generating a JWT, and doesn't automatically bridge newSession to session for you. This pattern is safe as long as you're sure newSession is valid at that point in the flow, but it's an edge case that could use better documentation or a framework update to make it less error-prone see source.

To reply, just mention @dosu.


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

<!-- gh-comment-id:3065430647 --> @dosubot[bot] commented on GitHub (Jul 12, 2025): <!-- Greeting --> Hi @izakfilmalter! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> The error happens because getJwtToken only looks for ctx.context.session and doesn't check ctx.context.newSession, so if session is null you'll get a TypeError when it tries to access session.user. Your workaround—assigning newSession to session before calling getJwtToken—is necessary in this flow and matches what the code expects. There isn't a more idiomatic or built-in way to handle this in better-auth right now; the framework expects session to be set when generating a JWT, and doesn't automatically bridge newSession to session for you. This pattern is safe as long as you're sure newSession is valid at that point in the flow, but it's an edge case that could use better documentation or a framework update to make it less error-prone [see source](https://github.com/better-auth/better-auth/blob/de20ad60aa7df50d147d8e94f61ee99cb49709a2/packages/better-auth/src/plugins/jwt/index.ts). <!-- 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/057d56e7-f367-4350-ad5c-634475aacd94?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/057d56e7-f367-4350-ad5c-634475aacd94?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/057d56e7-f367-4350-ad5c-634475aacd94?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/057d56e7-f367-4350-ad5c-634475aacd94?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/057d56e7-f367-4350-ad5c-634475aacd94?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/057d56e7-f367-4350-ad5c-634475aacd94?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/057d56e7-f367-4350-ad5c-634475aacd94?feedback_type=other)</sup>&nbsp;&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/3353)
Author
Owner

@NicoToff commented on GitHub (Jul 15, 2025):

Hey @izakfilmalter
That should fix the logic behind the issue, but the typing looks wrong with all these ! assertions. "Bang" or as assertions lead to brittle code, because you're telling the TS compiler you know better.

In this case, a guard clause ensuring that a session is present will allow to catch problems early and ensure a session is passed to the functions that need one.

<!-- gh-comment-id:3072005683 --> @NicoToff commented on GitHub (Jul 15, 2025): Hey @izakfilmalter That should fix the logic behind the issue, but the typing looks wrong with all these `!` assertions. "Bang" or `as` assertions lead to brittle code, because you're telling the TS compiler you know better. In this case, a guard clause ensuring that a session is present will allow to catch problems early and ensure a session is passed to the functions that need one.
Author
Owner

@frectonz commented on GitHub (Sep 8, 2025):

@izakfilmalter Are you still facing this problem? Can you also describe what the problem you are trying to solve is, i think i might be missing some context around the problem. It will also be very helpful if you could set up a minimal reproduction of the issue.

<!-- gh-comment-id:3267046231 --> @frectonz commented on GitHub (Sep 8, 2025): @izakfilmalter Are you still facing this problem? Can you also describe what the problem you are trying to solve is, i think i might be missing some context around the problem. It will also be very helpful if you could set up a minimal reproduction of the issue.
Author
Owner

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

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

Issue Summary:

  • You reported a TypeError when calling getJwtToken because ctx.context.session is null while ctx.context.newSession exists.
  • The current workaround is to assign newSession to session before calling getJwtToken, which I consider safe.
  • The issue highlights a need for better documentation or framework support for this edge case.
  • Maintainer NicoToff suggested adding a guard clause to ensure session presence for more robust TypeScript handling.
  • Another maintainer requested more context or a minimal reproduction to better understand the problem.

Next Steps:

  • Please let me know if this issue is still relevant with the latest version of better-auth by commenting here.
  • If I don’t hear back within 7 days, I will automatically close this issue.

Thanks for your understanding and contribution!

<!-- gh-comment-id:3627771689 --> @dosubot[bot] commented on GitHub (Dec 8, 2025): Hi, @izakfilmalter. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog and am marking this issue as stale. **Issue Summary:** - You reported a TypeError when calling `getJwtToken` because `ctx.context.session` is null while `ctx.context.newSession` exists. - The current workaround is to assign `newSession` to `session` before calling `getJwtToken`, which I consider safe. - The issue highlights a need for better documentation or framework support for this edge case. - Maintainer NicoToff suggested adding a guard clause to ensure `session` presence for more robust TypeScript handling. - Another maintainer requested more context or a minimal reproduction to better understand the problem. **Next Steps:** - Please let me know if this issue is still relevant with the latest version of better-auth by commenting here. - If I don’t hear back within 7 days, I will automatically close this issue. Thanks for your understanding and contribution!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#9577