[GH-ISSUE #6252] getAccessToken returns "Account Not Found" with stateless session after sign in with updateAccountOnSignIn set to true #10459

Closed
opened 2026-04-13 06:37:17 -05:00 by GiteaMirror · 6 comments
Owner

Originally created by @makezi on GitHub (Nov 24, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6252

Originally assigned to: @Paola3stefania on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Currently attempting to implement stateless sessions within nextjs 16 app router with the genericOAuth plugin like so:

export const auth = betterAuth({
  session: {
    cookieCache: {
      version: '1'
    }
  },
  plugins: [
    genericOAuth({
      config: [
        {
          providerId: 'custom-provider',
          clientId: REDACTED,
          clientSecret: REDACTED,
          prompt: 'login',
          discoveryUrl:
            'https://REDACTED.well-known/openid-configuration',
          redirectURI: `REDACTED/api/auth/callback/custom-provider`,
          scopes: [
            'claims',
            'profile',
            'email',
            'openid',
            'offline_access'
          ],
          pkce: true
        }
      ]
    }),
    nextCookies()
  ]
});

With the server actions for signing in and out:

export async function signInAction() {
  const response = await auth.api.signInWithOAuth2({
    body: {
      providerId: 'custom-provider`
    }
  });
  redirect(response.url);
}

export async function signOutAction() {
  const response = await auth.api.signOut({
    headers: await headers()
  });
  if (response.success) {
    redirect('/');
  }
}

This works fine as I can sign in and out with the external idp just fine. The issue lies with getAccessToken and account.updateAccountOnSignIn being set to true.

On initial sign the access token is available. However if I were to click the sign out button and then click sign in then I get the "Account Not Found" error. From looking at the source for getAccessToken I noticed that it needs a providerId from accountData that's stored in the session cookie. If you were to sign out then sign in again then providerId no longer exists in accountData - it's undefined.

183d38af00/packages/better-auth/src/api/routes/account.ts (L532)

I noticed that during the /callback/:id endpoint call, a call to handleOAuthUserInfo is made in which if account.updateAccountOnSignIn is true then the accountData is updated WITHOUT providerId. Link: 183d38af00/packages/better-auth/src/oauth2/link-account.ts (L97C4-L107C7).

If I set account.updateAccountOnSignIn to false then providerId is not removed upon sign in.

Current vs. Expected behavior

providerId should be included in the update to accountData.

What version of Better Auth are you using?

1.4.1

System info

{
  "system": {
    "platform": "darwin",
    "arch": "arm64",
    "version": "Darwin Kernel Version 25.1.0: Mon Oct 20 19:34:03 PDT 2025; root:xnu-12377.41.6~2/RELEASE_ARM64_T8112",
    "release": "25.1.0",
    "cpuCount": 8,
    "cpuModel": "Apple M2",
    "totalMemory": "16.00 GB",
    "freeMemory": "0.14 GB"
  },
  "node": {
    "version": "v22.13.1",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "10.9.2"
  },
  "frameworks": [
    {
      "name": "next",
      "version": "16.0.3"
    },
    {
      "name": "react",
      "version": "19.2.0"
    }
  ],
  "databases": null,
  "betterAuth": {
    "version": "^1.4.1",
    "config": null
  }
}

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

Client

Auth config (if applicable)


Additional context

No response

Originally created by @makezi on GitHub (Nov 24, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6252 Originally assigned to: @Paola3stefania on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce Currently attempting to implement stateless sessions within nextjs 16 app router with the `genericOAuth` plugin like so: ```ts export const auth = betterAuth({ session: { cookieCache: { version: '1' } }, plugins: [ genericOAuth({ config: [ { providerId: 'custom-provider', clientId: REDACTED, clientSecret: REDACTED, prompt: 'login', discoveryUrl: 'https://REDACTED.well-known/openid-configuration', redirectURI: `REDACTED/api/auth/callback/custom-provider`, scopes: [ 'claims', 'profile', 'email', 'openid', 'offline_access' ], pkce: true } ] }), nextCookies() ] }); ``` With the server actions for signing in and out: ```ts export async function signInAction() { const response = await auth.api.signInWithOAuth2({ body: { providerId: 'custom-provider` } }); redirect(response.url); } export async function signOutAction() { const response = await auth.api.signOut({ headers: await headers() }); if (response.success) { redirect('/'); } } ``` This works fine as I can sign in and out with the external idp just fine. The issue lies with `getAccessToken` and `account.updateAccountOnSignIn` being set to true. On initial sign the access token is available. However if I were to click the sign out button and then click sign in then I get the "Account Not Found" error. From looking at the source for `getAccessToken` I noticed that it needs a `providerId` from `accountData` that's stored in the session cookie. If you were to sign out then sign in again then `providerId` no longer exists in `accountData` - it's undefined. https://github.com/better-auth/better-auth/blob/183d38af00781ca84f6398c83b9ba9a6b02c3d97/packages/better-auth/src/api/routes/account.ts#L532 I noticed that during the `/callback/:id` endpoint call, a call to `handleOAuthUserInfo` is made in which if `account.updateAccountOnSignIn` is `true` then the `accountData` is updated WITHOUT `providerId`. Link: https://github.com/better-auth/better-auth/blob/183d38af00781ca84f6398c83b9ba9a6b02c3d97/packages/better-auth/src/oauth2/link-account.ts#L97C4-L107C7. If I set `account.updateAccountOnSignIn` to false then `providerId` is not removed upon sign in. ### Current vs. Expected behavior `providerId` should be included in the update to `accountData`. ### What version of Better Auth are you using? 1.4.1 ### System info ```bash { "system": { "platform": "darwin", "arch": "arm64", "version": "Darwin Kernel Version 25.1.0: Mon Oct 20 19:34:03 PDT 2025; root:xnu-12377.41.6~2/RELEASE_ARM64_T8112", "release": "25.1.0", "cpuCount": 8, "cpuModel": "Apple M2", "totalMemory": "16.00 GB", "freeMemory": "0.14 GB" }, "node": { "version": "v22.13.1", "env": "development" }, "packageManager": { "name": "npm", "version": "10.9.2" }, "frameworks": [ { "name": "next", "version": "16.0.3" }, { "name": "react", "version": "19.2.0" } ], "databases": null, "betterAuth": { "version": "^1.4.1", "config": null } } ``` ### Which area(s) are affected? (Select all that apply) Client ### Auth config (if applicable) ```typescript ``` ### Additional context _No response_
GiteaMirror added the lockedbug labels 2026-04-13 06:37:17 -05:00
Author
Owner

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

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

This is a known bug in Better Auth's stateless session flow: when account.updateAccountOnSignIn is true, the code that updates accountData during sign-in omits the providerId field. This happens because the update logic in handleOAuthUserInfo only includes token and expiry fields, not providerId or accountId, so after sign out and re-sign in, the session cookie loses providerId and getAccessToken fails with "Account Not Found" since it requires providerId to match the account data in the cookie and storage (source, source).

This is not intended behavior—updateAccountOnSignIn should refresh account data, not drop essential fields like providerId. The issue is tracked in several threads (#5801, #6188, #2202), and is a limitation of stateless or cookie-cached session modes in v1.4.1 and related betas.

Workarounds: set updateAccountOnSignIn to false to prevent providerId from being removed (though this may not be ideal long-term), or manually patch your flow to ensure providerId is included in the session cookie after sign-in. For production, the recommended approach is to use at least minimal persistent storage for user and session data, or manage token storage and retrieval yourself if you must stay stateless (source).

A recent PR (#6016) improved providerId handling in the generic OAuth flow, but it is unclear if it fully resolves this specific omission when updateAccountOnSignIn is true. Keep an eye on future releases for a complete fix.

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:3568853987 --> @dosubot[bot] commented on GitHub (Nov 24, 2025): <!-- Greeting --> Hi @makezi! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This is a known bug in Better Auth's stateless session flow: when `account.updateAccountOnSignIn` is true, the code that updates `accountData` during sign-in omits the `providerId` field. This happens because the update logic in `handleOAuthUserInfo` only includes token and expiry fields, not `providerId` or `accountId`, so after sign out and re-sign in, the session cookie loses `providerId` and `getAccessToken` fails with "Account Not Found" since it requires `providerId` to match the account data in the cookie and storage ([source](https://github.com/better-auth/better-auth/blob/c69b3da9958fc5359ef8c2a5649bdf04e5bbc87b/packages/better-auth/src/oauth2/link-account.ts#L97-L185), [source](https://github.com/better-auth/better-auth/blob/c69b3da9958fc5359ef8c2a5649bdf04e5bbc87b/packages/better-auth/src/api/routes/account.ts#L439-L617)). This is not intended behavior—`updateAccountOnSignIn` should refresh account data, not drop essential fields like `providerId`. The issue is tracked in several threads ([#5801](https://github.com/better-auth/better-auth/issues/5801), [#6188](https://github.com/better-auth/better-auth/issues/6188), [#2202](https://github.com/better-auth/better-auth/issues/2202)), and is a limitation of stateless or cookie-cached session modes in v1.4.1 and related betas. Workarounds: set `updateAccountOnSignIn` to `false` to prevent `providerId` from being removed (though this may not be ideal long-term), or manually patch your flow to ensure `providerId` is included in the session cookie after sign-in. For production, the recommended approach is to use at least minimal persistent storage for user and session data, or manage token storage and retrieval yourself if you must stay stateless ([source](https://github.com/better-auth/better-auth/issues/6188#issuecomment-3566099182)). A recent PR ([#6016](https://github.com/better-auth/better-auth/pull/6016)) improved providerId handling in the generic OAuth flow, but it is unclear if it fully resolves this specific omission when `updateAccountOnSignIn` is true. Keep an eye on future releases for a complete fix. <!-- 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/954ed2e5-33df-43e2-8573-1711b40ed7e7?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/954ed2e5-33df-43e2-8573-1711b40ed7e7?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/954ed2e5-33df-43e2-8573-1711b40ed7e7?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/954ed2e5-33df-43e2-8573-1711b40ed7e7?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/954ed2e5-33df-43e2-8573-1711b40ed7e7?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/954ed2e5-33df-43e2-8573-1711b40ed7e7?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/954ed2e5-33df-43e2-8573-1711b40ed7e7?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%20known%20bug%20in%20Better%20Auth%27s%20stateless%20session%20flow%3A%20when%20%60account.updateAccountOnSignIn%60%20is%20true%2C%20the%20code%20that%20updates%20%60accountData%60%20during%20sign-in%20omits%20the%20%60providerId%60%20field.%20This%20happens%20because%20the%20update%20logic%20in%20%60handleOAuthUserInfo%60%20only%20includes%20token%20and%20expiry%20fields%2C%20not%20%60providerId%60%20or%20%60accountId%60%2C%20so%20after%20sign%20out%20and%20re-sign%20in%2C%20the%20session%20cookie%20loses%20%60providerId%60%20and%20%60getAccessToken%60%20fails%20with%20%22Account%20Not%20Found%22%20since%20it%20requires%20%60providerId%60%20to%20match%20the%20account%20data%20in%20the%20cookie%20and%20storage%20%28%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/blob/c69b3da9958fc5359ef8c2a5649bdf04e5bbc87b/packages/better-auth/src/oauth2/link-account.ts%23L97-L185%29%2C%20%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/blob/c69b3da9958fc5359ef8c2a5649bdf04e5bbc87b/packages/better-auth/src/api/routes/account.ts%23L439-L617%29%29.%0A%0AThis%20is%20not%20intended%20behavior%E2%80%94%60updateAccountOnSignIn%60%20should%20refresh%20account%20data%2C%20not%20drop%20essential%20fields%20like%20%60providerId%60.%20The%20issue%20is%20tracked%20in%20several%20threads%20%28%5B%235801%5D%28https%3A//github.com/better-auth/better-auth/issues/5801%29%2C%20%5B%236188%5D%28https%3A//github.com/better-auth/better-auth/issues/6188%29%2C%20%5B%232202%5D%28https%3A//github.com/better-auth/better-auth/issues/2202%29%29%2C%20and%20is%20a%20limitation%20of%20stateless%20or%20cookie-cached%20session%20modes%20in%20v1.4.1%20and%20related%20betas.%0A%0AWorkarounds%3A%20set%20%60updateAccountOnSignIn%60%20to%20%60false%60%20to%20prevent%20%60providerId%60%20from%20being%20removed%20%28though%20this%20may%20not%20be%20ideal%20long-term%29%2C%20or%20manually%20patch%20your%20flow%20to%20ensure%20%60providerId%60%20is%20included%20in%20the%20session%20cookie%20after%20sign-in.%20For%20production%2C%20the%20recommended%20approach%20is%20to%20use%20at%20least%20minimal%20persistent%20storage%20for%20user%20and%20session%20data%2C%20or%20manage%20token%20storage%20and%20retrieval%20yourself%20if%20you%20must%20stay%20stateless%20%28%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/6188%23issuecomment-3566099182%29%29.%0A%0AA%20recent%20PR%20%28%5B%236016%5D%28https%3A//github.com/better-auth/better-auth/pull/6016%29%29%20improved%20providerId%20handling%20in%20the%20generic%20OAuth%20flow%2C%20but%20it%20is%20unclear%20if%20it%20fully%20resolves%20this%20specific%20omission%20when%20%60updateAccountOnSignIn%60%20is%20true.%20Keep%20an%20eye%20on%20future%20releases%20for%20a%20complete%20fix.)&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/6252)
Author
Owner

@makezi commented on GitHub (Dec 2, 2025):

I've updated to 1.4.4 and the issue still persists since account.updateAccountOnSignIn removes the providerId from better-auth.account_data cookie. This issue occurs upon cookie deletion (https://github.com/better-auth/better-auth/issues/6188) and/or subsequent logins (https://github.com/better-auth/better-auth/issues/6252).

<!-- gh-comment-id:3604111960 --> @makezi commented on GitHub (Dec 2, 2025): I've updated to `1.4.4` and the issue still persists since `account.updateAccountOnSignIn` removes the `providerId` from `better-auth.account_data` cookie. This issue occurs upon cookie deletion (https://github.com/better-auth/better-auth/issues/6188) and/or subsequent logins (https://github.com/better-auth/better-auth/issues/6252).
Author
Owner

@Paola3stefania commented on GitHub (Jan 9, 2026):

hi @makezi do you still have this issue with lastest version?

<!-- gh-comment-id:3730641932 --> @Paola3stefania commented on GitHub (Jan 9, 2026): hi @makezi do you still have this issue with lastest version?
Author
Owner

@SferaDev commented on GitHub (Jan 10, 2026):

I believe #7216 fixes it, but I haven't confirmed yet myself

npm i https://pkg.pr.new/better-auth/better-auth@7216
<!-- gh-comment-id:3731832357 --> @SferaDev commented on GitHub (Jan 10, 2026): I believe #7216 fixes it, but I haven't confirmed yet myself ``` npm i https://pkg.pr.new/better-auth/better-auth@7216 ```
Author
Owner

@makezi commented on GitHub (Jan 10, 2026):

I haven't had the chance to test again with the latest version but I will give it a go within the next couple days and report back. Thanks!

<!-- gh-comment-id:3731953814 --> @makezi commented on GitHub (Jan 10, 2026): I haven't had the chance to test again with the latest version but I will give it a go within the next couple days and report back. Thanks!
Author
Owner

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

Seems like that PR fixed the Account Not Found issue but now facing a separate issue with refresh tokens similar to that of here and here in which even if auth.api.getAccessToken or auth.api.refreshTokens (via server action or via proxy) is called with new access token / refresh token / expiry it still doesn't property update the cookies and lead to an UNAUTHORIZED error.

<!-- gh-comment-id:3736544191 --> @makezi commented on GitHub (Jan 12, 2026): Seems like that PR fixed the `Account Not Found` issue but now facing a separate issue with refresh tokens similar to that of [here](https://github.com/better-auth/better-auth/discussions/6715#discussioncomment-15271769) and [here](https://github.com/better-auth/better-auth/discussions/5786#discussioncomment-15258921) in which even if `auth.api.getAccessToken` or `auth.api.refreshTokens` (via server action or via proxy) is called with new access token / refresh token / expiry it still doesn't property update the cookies and lead to an `UNAUTHORIZED` error.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#10459