[GH-ISSUE #6188] OAuth2 login fails with “Account not found” after browser cookies are cleared #19067

Closed
opened 2026-04-15 17:51:06 -05:00 by GiteaMirror · 16 comments
Owner

Originally created by @Lqm1 on GitHub (Nov 22, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/6188

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

After setting up authentication using the genericOAuth plugin with OAuth2, logging in with OAuth2 works normally.
However, if the user clears all cookies in the browser after logging in, any subsequent login attempts using the same OAuth2 account result in an “Account not found” error, and the user cannot log in.

Restarting the server temporarily resolves the issue.

Current vs. Expected behavior

⨯ [Error [APIError]: Account not found] {
status: 'BAD_REQUEST',
body: [Object],
headers: {},
statusCode: 400,
digest: '1822514559'
}

What version of Better Auth are you using?

1.4

System info

{
  "system": {
    "platform": "win32",
    "arch": "x64",
    "version": "Windows 11 Home",
    "release": "10.0.26200",
    "cpuCount": 24,
    "cpuModel": "Intel(R) Core(TM) i7-14650HX",
    "totalMemory": "47.71 GB",
    "freeMemory": "23.21 GB"
  },
  "node": {
    "version": "v22.14.0",
    "env": "development"
  },
  "packageManager": {
    "name": "bun",
    "version": "1.3.3"
  },
  "frameworks": [
    {
      "name": "next",
      "version": "^16.0.3"
    },
    {
      "name": "react",
      "version": "^19.2.0"
    }
  ],
  "databases": [
    {
      "name": "@prisma/client",
      "version": "^6.12.0"
    }
  ],
  "betterAuth": {
    "version": "^1.4.0",
    "config": {
      "plugins": [
        {
          "name": "generic-oauth",
          "config": {
            "id": "generic-oauth",
            "endpoints": {},
            "$ERROR_CODES": {
              "INVALID_OAUTH_CONFIGURATION": "Invalid OAuth configuration",
              "TOKEN_URL_NOT_FOUND": "Invalid OAuth configuration. Token URL not found.",
              "PROVIDER_CONFIG_NOT_FOUND": "No config found for provider",
              "PROVIDER_ID_REQUIRED": "Provider ID is required",
              "INVALID_OAUTH_CONFIG": "Invalid OAuth configuration.",
              "SESSION_REQUIRED": "Session is required"
            }
          }
        }
      ]
    }
  }
}

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

Backend, Client

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { genericOAuth } from "better-auth/plugins";
import { env } from "@/lib/env";

export const auth = betterAuth({
	plugins: [
		genericOAuth({
			config: [
				{
					providerId: "example",
					clientId: env.EXAMPLE_CLIENT_ID,
					clientSecret: env.EXAMPLE_CLIENT_SECRET,
					scopes: ["read", "write", "profile", "email"],
					authorizationUrl: `${env.EXAMPLE_BASE_URL}/oauth2/authorize`,
					tokenUrl: `${env.EXAMPLE_API_BASE_URL}/api/v1/oauth2/token`,
					userInfoUrl: `${env.EXAMPLE_API_BASE_URL}/api/v1/oauth2/userinfo`,
				},
			],
		}),
	],
});

Additional context

Analysis:

This appears to be caused by user data being stored both in cookies (client-side) and in memory (server-side) while using stateless authentication. Clearing cookies on the client causes a mismatch between the client state and server memory. Because restarting the server clears the in-memory user data, the issue disappears after a restart.

Request:

When cookies are deleted on the client and new user data is generated, the server should overwrite or refresh the in-memory user data to avoid inconsistencies.

Originally created by @Lqm1 on GitHub (Nov 22, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/6188 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce After setting up authentication using the `genericOAuth` plugin with OAuth2, logging in with OAuth2 works normally. However, if the user clears all cookies in the browser after logging in, any subsequent login attempts using the same OAuth2 account result in an **“Account not found”** error, and the user cannot log in. Restarting the server temporarily resolves the issue. ### Current vs. Expected behavior ``` ⨯ [Error [APIError]: Account not found] { status: 'BAD_REQUEST', body: [Object], headers: {}, statusCode: 400, digest: '1822514559' } ``` ### What version of Better Auth are you using? 1.4 ### System info ```bash { "system": { "platform": "win32", "arch": "x64", "version": "Windows 11 Home", "release": "10.0.26200", "cpuCount": 24, "cpuModel": "Intel(R) Core(TM) i7-14650HX", "totalMemory": "47.71 GB", "freeMemory": "23.21 GB" }, "node": { "version": "v22.14.0", "env": "development" }, "packageManager": { "name": "bun", "version": "1.3.3" }, "frameworks": [ { "name": "next", "version": "^16.0.3" }, { "name": "react", "version": "^19.2.0" } ], "databases": [ { "name": "@prisma/client", "version": "^6.12.0" } ], "betterAuth": { "version": "^1.4.0", "config": { "plugins": [ { "name": "generic-oauth", "config": { "id": "generic-oauth", "endpoints": {}, "$ERROR_CODES": { "INVALID_OAUTH_CONFIGURATION": "Invalid OAuth configuration", "TOKEN_URL_NOT_FOUND": "Invalid OAuth configuration. Token URL not found.", "PROVIDER_CONFIG_NOT_FOUND": "No config found for provider", "PROVIDER_ID_REQUIRED": "Provider ID is required", "INVALID_OAUTH_CONFIG": "Invalid OAuth configuration.", "SESSION_REQUIRED": "Session is required" } } } ] } } } ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { genericOAuth } from "better-auth/plugins"; import { env } from "@/lib/env"; export const auth = betterAuth({ plugins: [ genericOAuth({ config: [ { providerId: "example", clientId: env.EXAMPLE_CLIENT_ID, clientSecret: env.EXAMPLE_CLIENT_SECRET, scopes: ["read", "write", "profile", "email"], authorizationUrl: `${env.EXAMPLE_BASE_URL}/oauth2/authorize`, tokenUrl: `${env.EXAMPLE_API_BASE_URL}/api/v1/oauth2/token`, userInfoUrl: `${env.EXAMPLE_API_BASE_URL}/api/v1/oauth2/userinfo`, }, ], }), ], }); ``` ### Additional context **Analysis:** This appears to be caused by user data being stored both in cookies (client-side) and in memory (server-side) while using stateless authentication. Clearing cookies on the client causes a mismatch between the client state and server memory. Because restarting the server clears the in-memory user data, the issue disappears after a restart. **Request:** When cookies are deleted on the client and new user data is generated, the server should overwrite or refresh the in-memory user data to avoid inconsistencies.
GiteaMirror added the locked label 2026-04-15 17:51:06 -05:00
Author
Owner

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

This happens because Better Auth stores session and account data both in cookies (client-side) and in persistent storage (database), but also may use in-memory cache for performance. When you clear browser cookies, the server tries to fall back to the database to find the account/session, but if the session or user ID is missing or mismatched, you get an "Account not found" error. Restarting the server clears any in-memory cache, so the next login works because everything is rebuilt from scratch, but the underlying issue remains: there's no automatic refresh or overwrite of in-memory state when cookies are deleted and a new OAuth2 login is attempted. This is a known limitation in the current implementation—recent PRs have not addressed this specific scenario [source].

To avoid this, make sure your session and account data are always persisted in the database and that your session/account lookup logic doesn't rely solely on cookies or in-memory state. If you're using any secondary storage or cache, ensure it's configured to fall back to the database when cookies are missing. You might also want to review your session and account cookie strategies, and consider adding hooks to force a refresh or re-link account/session state on new OAuth2 logins after cookies are cleared [source].

This is not unique to your setup—others have reported similar issues, especially in stateless or cookie-cached session modes. There’s currently no built-in mechanism in Better Auth to automatically recover from this state without a server restart [source].

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:3566067606 --> @dosubot[bot] commented on GitHub (Nov 22, 2025): <!-- Answer --> This happens because Better Auth stores session and account data both in cookies (client-side) and in persistent storage (database), but also may use in-memory cache for performance. When you clear browser cookies, the server tries to fall back to the database to find the account/session, but if the session or user ID is missing or mismatched, you get an "Account not found" error. Restarting the server clears any in-memory cache, so the next login works because everything is rebuilt from scratch, but the underlying issue remains: there's no automatic refresh or overwrite of in-memory state when cookies are deleted and a new OAuth2 login is attempted. This is a known limitation in the current implementation—recent PRs have not addressed this specific scenario [[source]](https://github.com/better-auth/better-auth/issues/5801). To avoid this, make sure your session and account data are always persisted in the database and that your session/account lookup logic doesn't rely solely on cookies or in-memory state. If you're using any secondary storage or cache, ensure it's configured to fall back to the database when cookies are missing. You might also want to review your session and account cookie strategies, and consider adding hooks to force a refresh or re-link account/session state on new OAuth2 logins after cookies are cleared [[source]](https://github.com/better-auth/better-auth/blob/9e2b5ce6322e3a36d6a191772fa47389027f5b4e/packages/better-auth/src/api/routes/account.ts#L1-L947). This is not unique to your setup—others have reported similar issues, especially in stateless or cookie-cached session modes. There’s currently no built-in mechanism in Better Auth to automatically recover from this state without a server restart [[source]](https://github.com/better-auth/better-auth/issues/5801). <!-- 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/5593442a-577a-4c03-b8bd-a032088fedad?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/5593442a-577a-4c03-b8bd-a032088fedad?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/5593442a-577a-4c03-b8bd-a032088fedad?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/5593442a-577a-4c03-b8bd-a032088fedad?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/5593442a-577a-4c03-b8bd-a032088fedad?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/5593442a-577a-4c03-b8bd-a032088fedad?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/5593442a-577a-4c03-b8bd-a032088fedad?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%20happens%20because%20Better%20Auth%20stores%20session%20and%20account%20data%20both%20in%20cookies%20%28client-side%29%20and%20in%20persistent%20storage%20%28database%29%2C%20but%20also%20may%20use%20in-memory%20cache%20for%20performance.%20When%20you%20clear%20browser%20cookies%2C%20the%20server%20tries%20to%20fall%20back%20to%20the%20database%20to%20find%20the%20account/session%2C%20but%20if%20the%20session%20or%20user%20ID%20is%20missing%20or%20mismatched%2C%20you%20get%20an%20%22Account%20not%20found%22%20error.%20Restarting%20the%20server%20clears%20any%20in-memory%20cache%2C%20so%20the%20next%20login%20works%20because%20everything%20is%20rebuilt%20from%20scratch%2C%20but%20the%20underlying%20issue%20remains%3A%20there%27s%20no%20automatic%20refresh%20or%20overwrite%20of%20in-memory%20state%20when%20cookies%20are%20deleted%20and%20a%20new%20OAuth2%20login%20is%20attempted.%20This%20is%20a%20known%20limitation%20in%20the%20current%20implementation%E2%80%94recent%20PRs%20have%20not%20addressed%20this%20specific%20scenario%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/5801%29.%0A%0ATo%20avoid%20this%2C%20make%20sure%20your%20session%20and%20account%20data%20are%20always%20persisted%20in%20the%20database%20and%20that%20your%20session/account%20lookup%20logic%20doesn%27t%20rely%20solely%20on%20cookies%20or%20in-memory%20state.%20If%20you%27re%20using%20any%20secondary%20storage%20or%20cache%2C%20ensure%20it%27s%20configured%20to%20fall%20back%20to%20the%20database%20when%20cookies%20are%20missing.%20You%20might%20also%20want%20to%20review%20your%20session%20and%20account%20cookie%20strategies%2C%20and%20consider%20adding%20hooks%20to%20force%20a%20refresh%20or%20re-link%20account/session%20state%20on%20new%20OAuth2%20logins%20after%20cookies%20are%20cleared%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/blob/9e2b5ce6322e3a36d6a191772fa47389027f5b4e/packages/better-auth/src/api/routes/account.ts%23L1-L947%29.%0A%0AThis%20is%20not%20unique%20to%20your%20setup%E2%80%94others%20have%20reported%20similar%20issues%2C%20especially%20in%20stateless%20or%20cookie-cached%20session%20modes.%20There%E2%80%99s%20currently%20no%20built-in%20mechanism%20in%20Better%20Auth%20to%20automatically%20recover%20from%20this%20state%20without%20a%20server%20restart%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/5801%29.)&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/6188)
Author
Owner

@Lqm1 commented on GitHub (Nov 22, 2025):

@dosu Thanks to dosubot, the cause has become clear.
This “Account not found” error is very likely being thrown by the getAccessToken function. However, unlike the previously reported issues, everything works correctly until the cookies are manually deleted.
The previously reported issue appears to have been merged and resolved already, but this problem seems to be an extension of that behavior.
https://github.com/better-auth/better-auth/issues/5801

<!-- gh-comment-id:3566099182 --> @Lqm1 commented on GitHub (Nov 22, 2025): @dosu Thanks to dosubot, the cause has become clear. This “Account not found” error is very likely being thrown by the `getAccessToken` function. However, unlike the previously reported issues, everything works correctly *until the cookies are manually deleted*. The previously reported issue appears to have been merged and resolved already, but this problem seems to be an extension of that behavior. https://github.com/better-auth/better-auth/issues/5801
Author
Owner

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

You're right—the “Account not found” error after manual cookie deletion is thrown by getAccessToken, and it’s an extension of the issue discussed in #5801. The root cause is that Better Auth relies on cookies and persistent storage (like a database) to resolve the user and account. If cookies are deleted and there’s no persistent storage (or the session/userId isn’t supplied), getAccessToken can’t recover the account and throws this error. Restarting the server only helps if you’re using an in-memory adapter, which is meant for development, not production.

There’s currently no built-in mechanism to automatically refresh or overwrite in-memory user/session data when cookies are deleted. In stateless setups, you must either provide a persistent store for user/account data or ensure your client supplies a valid userId/session in requests so the server can look up the account in storage instead of relying on cookies. Without this, manual cookie deletion will break the session/account linkage and cause the error you’re seeing [source] [source].

For production, the recommended workaround is to use at least minimal persistent storage for user and session data. If you want to stay stateless, you’ll need to manage token lifecycles and storage yourself, which means customizing your flow to extract/store tokens securely and supply user identifiers as needed [source].

Let me know if you want example patterns or code for custom recovery logic!

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:3566110460 --> @dosubot[bot] commented on GitHub (Nov 22, 2025): <!-- Answer --> You're right—the “Account not found” error after manual cookie deletion is thrown by `getAccessToken`, and it’s an extension of the issue discussed in #5801. The root cause is that Better Auth relies on cookies and persistent storage (like a database) to resolve the user and account. If cookies are deleted and there’s no persistent storage (or the session/userId isn’t supplied), `getAccessToken` can’t recover the account and throws this error. Restarting the server only helps if you’re using an in-memory adapter, which is meant for development, not production. There’s currently no built-in mechanism to automatically refresh or overwrite in-memory user/session data when cookies are deleted. In stateless setups, you must either provide a persistent store for user/account data or ensure your client supplies a valid userId/session in requests so the server can look up the account in storage instead of relying on cookies. Without this, manual cookie deletion will break the session/account linkage and cause the error you’re seeing [[source](https://github.com/better-auth/better-auth/issues/2202)] [[source](https://github.com/better-auth/better-auth/issues/5801)]. For production, the recommended workaround is to use at least minimal persistent storage for user and session data. If you want to stay stateless, you’ll need to manage token lifecycles and storage yourself, which means customizing your flow to extract/store tokens securely and supply user identifiers as needed [[source](https://github.com/better-auth/better-auth/issues/2202)]. Let me know if you want example patterns or code for custom recovery logic! <!-- 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/5a1e762c-c16c-4b9a-a288-4aa324c7d1dd?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/5a1e762c-c16c-4b9a-a288-4aa324c7d1dd?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/5a1e762c-c16c-4b9a-a288-4aa324c7d1dd?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/5a1e762c-c16c-4b9a-a288-4aa324c7d1dd?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/5a1e762c-c16c-4b9a-a288-4aa324c7d1dd?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/5a1e762c-c16c-4b9a-a288-4aa324c7d1dd?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/5a1e762c-c16c-4b9a-a288-4aa324c7d1dd?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=You%27re%20right%E2%80%94the%20%E2%80%9CAccount%20not%20found%E2%80%9D%20error%20after%20manual%20cookie%20deletion%20is%20thrown%20by%20%60getAccessToken%60%2C%20and%20it%E2%80%99s%20an%20extension%20of%20the%20issue%20discussed%20in%20%235801.%20The%20root%20cause%20is%20that%20Better%20Auth%20relies%20on%20cookies%20and%20persistent%20storage%20%28like%20a%20database%29%20to%20resolve%20the%20user%20and%20account.%20If%20cookies%20are%20deleted%20and%20there%E2%80%99s%20no%20persistent%20storage%20%28or%20the%20session/userId%20isn%E2%80%99t%20supplied%29%2C%20%60getAccessToken%60%20can%E2%80%99t%20recover%20the%20account%20and%20throws%20this%20error.%20Restarting%20the%20server%20only%20helps%20if%20you%E2%80%99re%20using%20an%20in-memory%20adapter%2C%20which%20is%20meant%20for%20development%2C%20not%20production.%0A%0AThere%E2%80%99s%20currently%20no%20built-in%20mechanism%20to%20automatically%20refresh%20or%20overwrite%20in-memory%20user/session%20data%20when%20cookies%20are%20deleted.%20In%20stateless%20setups%2C%20you%20must%20either%20provide%20a%20persistent%20store%20for%20user/account%20data%20or%20ensure%20your%20client%20supplies%20a%20valid%20userId/session%20in%20requests%20so%20the%20server%20can%20look%20up%20the%20account%20in%20storage%20instead%20of%20relying%20on%20cookies.%20Without%20this%2C%20manual%20cookie%20deletion%20will%20break%20the%20session/account%20linkage%20and%20cause%20the%20error%20you%E2%80%99re%20seeing%20%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/2202%29%5D%20%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/5801%29%5D.%0A%0AFor%20production%2C%20the%20recommended%20workaround%20is%20to%20use%20at%20least%20minimal%20persistent%20storage%20for%20user%20and%20session%20data.%20If%20you%20want%20to%20stay%20stateless%2C%20you%E2%80%99ll%20need%20to%20manage%20token%20lifecycles%20and%20storage%20yourself%2C%20which%20means%20customizing%20your%20flow%20to%20extract/store%20tokens%20securely%20and%20supply%20user%20identifiers%20as%20needed%20%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/2202%29%5D.%0A%0ALet%20me%20know%20if%20you%20want%20example%20patterns%20or%20code%20for%20custom%20recovery%20logic%21)&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/6188)
Author
Owner

@makezi commented on GitHub (Nov 24, 2025):

I believe #6253 might fix this.

I've reproduced this by signing in -> deleting cookies then getting the "Account Not Found" error. Applying this fix locally where providerId was missing during the updating of the better-auth.account_datacookie when the defaultupdateAccountOnSignIn` is true seems to have resolved this issue for me. Perhaps see if it does as well for you?

<!-- gh-comment-id:3572364913 --> @makezi commented on GitHub (Nov 24, 2025): I believe #6253 might fix this. I've reproduced this by signing in -> deleting cookies then getting the "Account Not Found" error. Applying this fix locally where `providerId` was missing during the updating of the better-auth.account_data` cookie when the default `updateAccountOnSignIn` is true seems to have resolved this issue for me. Perhaps see if it does as well for you?
Author
Owner

@Lqm1 commented on GitHub (Nov 25, 2025):

I believe #6253 might fix this.

I've reproduced this by signing in -> deleting cookies then getting the "Account Not Found" error. Applying this fix locally where providerId was missing during the updating of the better-auth.account_datacookie when the defaultupdateAccountOnSignIn` is true seems to have resolved this issue for me. Perhaps see if it does as well for you?

I have checked your PR.
This issue was fixed in #6253

Thank you!

<!-- gh-comment-id:3575089184 --> @Lqm1 commented on GitHub (Nov 25, 2025): > I believe [#6253](https://github.com/better-auth/better-auth/pull/6253) might fix this. > > I've reproduced this by signing in -> deleting cookies then getting the "Account Not Found" error. Applying this fix locally where `providerId` was missing during the updating of the better-auth.account_data`cookie when the default`updateAccountOnSignIn` is true seems to have resolved this issue for me. Perhaps see if it does as well for you? I have checked your PR. This issue was fixed in [#6253](https://github.com/better-auth/better-auth/pull/6253) Thank you!
Author
Owner

@dszmaj7 commented on GitHub (Nov 26, 2025):

@dosu I use BetterAuth in the TanStack/React-Start app with the Microsoft provider, and the 'Account not found' error occurs every time I save code changes. After a hot reload, account data is missing and I have to sign the user in again. Having to reauthenticate after every save is annoying.

export const auth = betterAuth({
  socialProviders: {
    microsoft: {
      clientId: process.env.MICROSOFT_CLIENT_ID,
      clientSecret: process.env.MICROSOFT_CLIENT_SECRET,
      tenantId: process.env.MICROSOFT_TENANT_ID,
      redirectUri: process.env.MICROSOFT_REDIRECT_URI,
      authority: 'https://login.microsoftonline.com',
      scope: ['openid', 'profile', 'email', 'offline_access', 'User.Read'],
      prompt: 'select_account',
    },
  },
  session: {
    cookieCache: {
      enabled: true,
      maxAge: 7 * 24 * 60 * 60,
      strategy: 'jwe',
      refreshCache: true,
      version: '1',
    },
  },
  account: {
    storeStateStrategy: 'cookie',
    storeAccountCookie: true,
    updateAccountOnSignIn: true,
  },
  plugins: [tanstackStartCookies()],
});

export const authMiddleware = createMiddleware().server(async ({ next }) => {
  const headers = getRequestHeaders();

  const { data: session } = await getSession({
    fetchOptions: {
      headers,
    },
  });

  if (!session) {
    throw redirect({ to: '/sign-in' });
  }

  let token: string = '';

  try {
    const { idToken } = await auth.api.getAccessToken({
      body: {
        providerId: 'microsoft',
        userId: session.session.userId,
      },
    });
    if (idToken) {
      token = idToken;
    }
  } catch {
    await signOut(
      {},
      {
        onSuccess: () => {
          throw redirect({ to: '/sign-in' });
        },
      },
    );
  }

  return next({
    context: {
      session: {
        userId: session.user.id,
        name: session.user.name,
        idToken: token,
      },
      apiClient: createApiClient(token, session.session.userId),
    },
  });
});
<!-- gh-comment-id:3581699482 --> @dszmaj7 commented on GitHub (Nov 26, 2025): @dosu I use BetterAuth in the TanStack/React-Start app with the Microsoft provider, and the 'Account not found' error occurs every time I save code changes. After a hot reload, account data is missing and I have to sign the user in again. Having to reauthenticate after every save is annoying. ``` export const auth = betterAuth({ socialProviders: { microsoft: { clientId: process.env.MICROSOFT_CLIENT_ID, clientSecret: process.env.MICROSOFT_CLIENT_SECRET, tenantId: process.env.MICROSOFT_TENANT_ID, redirectUri: process.env.MICROSOFT_REDIRECT_URI, authority: 'https://login.microsoftonline.com', scope: ['openid', 'profile', 'email', 'offline_access', 'User.Read'], prompt: 'select_account', }, }, session: { cookieCache: { enabled: true, maxAge: 7 * 24 * 60 * 60, strategy: 'jwe', refreshCache: true, version: '1', }, }, account: { storeStateStrategy: 'cookie', storeAccountCookie: true, updateAccountOnSignIn: true, }, plugins: [tanstackStartCookies()], }); ``` ``` export const authMiddleware = createMiddleware().server(async ({ next }) => { const headers = getRequestHeaders(); const { data: session } = await getSession({ fetchOptions: { headers, }, }); if (!session) { throw redirect({ to: '/sign-in' }); } let token: string = ''; try { const { idToken } = await auth.api.getAccessToken({ body: { providerId: 'microsoft', userId: session.session.userId, }, }); if (idToken) { token = idToken; } } catch { await signOut( {}, { onSuccess: () => { throw redirect({ to: '/sign-in' }); }, }, ); } return next({ context: { session: { userId: session.user.id, name: session.user.name, idToken: token, }, apiClient: createApiClient(token, session.session.userId), }, }); }); ```
Author
Owner

@SferaDev commented on GitHub (Dec 4, 2025):

Any updates on this? We're trying to migrate from next-auth to the better-auth with the stateless cookies and we hit this "Account not found" issue all the time

<!-- gh-comment-id:3611857834 --> @SferaDev commented on GitHub (Dec 4, 2025): Any updates on this? We're trying to migrate from `next-auth` to the `better-auth` with the stateless cookies and we hit this "Account not found" issue all the time
Author
Owner

@Blitz2145 commented on GitHub (Dec 9, 2025):

I can confirm we are also getting this "Account not found" error using stateless mode in our testing envs, which is blocking our migration off of next-auth. Fwiw, the account_data cookie is being set, but the error still occurs.

<!-- gh-comment-id:3633740173 --> @Blitz2145 commented on GitHub (Dec 9, 2025): I can confirm we are also getting this "Account not found" error using stateless mode in our testing envs, which is blocking our migration off of next-auth. Fwiw, the `account_data` cookie is being set, but the error still occurs.
Author
Owner

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

Having the same issue sporadically. It seems that setting updateAccountOnSignIn: false helps somewhat mitigate it however it sometimes occurs after app rebuild and sometimes just randomly. I am using stateless auth. Would be great to have all related PRs merged and to have them released to see if the issue gets fixed after that

<!-- gh-comment-id:3673620942 --> @Nikitakun commented on GitHub (Dec 19, 2025): Having the same issue sporadically. It seems that setting `updateAccountOnSignIn: false` helps somewhat mitigate it however it sometimes occurs after app rebuild and sometimes just randomly. I am using stateless auth. Would be great to have all related PRs merged and to have them released to see if the issue gets fixed after that
Author
Owner

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

Initially, I thought this issue would be closed by PR https://github.com/better-auth/better-auth/pull/6253 , but it appears that PR https://github.com/better-auth/better-auth/pull/6253 was left unmerged and unresolved, and the issue was instead fixed by the newly created PR https://github.com/better-auth/better-auth/issues/6770 .

I temporarily used a version of Better-Auth with PR #6770 applied, and today v1.4.8-beta.1 was released as the first version that includes PR https://github.com/better-auth/better-auth/issues/6770 .

Could you try updating to v1.4.8-beta.1 instead of v1.4.7 and see whether this issue still occurs?

In my environment, the issue was resolved, so temporarily switching to v1.4.8-beta.1 may be a good option.

<!-- gh-comment-id:3674004086 --> @Lqm1 commented on GitHub (Dec 19, 2025): Initially, I thought this issue would be closed by PR https://github.com/better-auth/better-auth/pull/6253 , but it appears that PR https://github.com/better-auth/better-auth/pull/6253 was left unmerged and unresolved, and the issue was instead fixed by the newly created PR https://github.com/better-auth/better-auth/issues/6770 . I temporarily used a version of Better-Auth with PR [#6770](https://github.com/better-auth/better-auth/issues/6770) applied, and today **v1.4.8-beta.1** was released as the first version that includes PR https://github.com/better-auth/better-auth/issues/6770 . Could you try updating to **v1.4.8-beta.1** instead of **v1.4.7** and see whether this issue still occurs? In my environment, the issue was resolved, so temporarily switching to **v1.4.8-beta.1** may be a good option.
Author
Owner

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

Issue seems to still reproduce after clearing the cookies and reloading the page

<!-- gh-comment-id:3674717474 --> @ZilvinasAbr commented on GitHub (Dec 19, 2025): Issue seems to still reproduce after clearing the cookies and reloading the page
Author
Owner

@Nikitakun commented on GitHub (Dec 23, 2025):

Been better in 1.4.8 but still reproduces randomly after refreshing the page or rebuilding the app somehow

<!-- gh-comment-id:3686572897 --> @Nikitakun commented on GitHub (Dec 23, 2025): Been better in 1.4.8 but still reproduces randomly after refreshing the page or rebuilding the app somehow
Author
Owner

@Lqm1 commented on GitHub (Dec 24, 2025):

Been better in 1.4.8 but still reproduces randomly after refreshing the page or rebuilding the app somehow

I updated to the official version of 1.4.8, but there are many errors during hot reload during development.
It is solved for production use after building.

I implemented secondary storage to resolve this issue, but it didn't work in my environment

<!-- gh-comment-id:3688600515 --> @Lqm1 commented on GitHub (Dec 24, 2025): > Been better in 1.4.8 but still reproduces randomly after refreshing the page or rebuilding the app somehow I updated to the official version of 1.4.8, but there are many errors during hot reload during development. It is solved for production use after building. I implemented secondary storage to resolve this issue, but it didn't work in my environment
Author
Owner

@Nikitakun commented on GitHub (Dec 24, 2025):

Been better in 1.4.8 but still reproduces randomly after refreshing the page or rebuilding the app somehow

I updated to the official version of 1.4.8, but there are many errors during hot reload during development. It is solved for production use after building.

I implemented secondary storage to resolve this issue, but it didn't work in my environment

After clearing cookies once in dev, haven't seen it reproduced again yet, but expecting it to pop up anytime. In production build the problem was a different error saying "invalid_grant", not sure whether it's related, but haven't run into "Account not found" in prod build just yet.

<!-- gh-comment-id:3688868678 --> @Nikitakun commented on GitHub (Dec 24, 2025): > > Been better in 1.4.8 but still reproduces randomly after refreshing the page or rebuilding the app somehow > > I updated to the official version of 1.4.8, but there are many errors during hot reload during development. It is solved for production use after building. > > I implemented secondary storage to resolve this issue, but it didn't work in my environment After clearing cookies once in dev, haven't seen it reproduced again yet, but expecting it to pop up anytime. In production build the problem was a different error saying "invalid_grant", not sure whether it's related, but haven't run into "Account not found" in prod build just yet.
Author
Owner

@Nikitakun commented on GitHub (Dec 28, 2025):

Unfortunately, have indeed run into "Account not found" in production build as well in Safari. Not even sure how to debug this issue. Seems that for now might be better to switch to other alternatives for those needing stateless auth

<!-- gh-comment-id:3694948497 --> @Nikitakun commented on GitHub (Dec 28, 2025): Unfortunately, have indeed run into "Account not found" in production build as well in Safari. Not even sure how to debug this issue. Seems that for now might be better to switch to other alternatives for those needing stateless auth
Author
Owner

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

Hello everyone,

I’ve fixed the part that’s likely causing this issue today, and you can test it with the version below before the next release. If the issue persists, feel free to reopen it or mention me 🙂

npm i https://pkg.pr.new/better-auth/better-auth@7216
<!-- gh-comment-id:3728273910 --> @bytaesu commented on GitHub (Jan 9, 2026): Hello everyone, I’ve fixed the part that’s likely causing this issue today, and you can test it with the version below before the next release. If the issue persists, feel free to reopen it or mention me 🙂 ``` npm i https://pkg.pr.new/better-auth/better-auth@7216 ``` - https://github.com/better-auth/better-auth/pull/7216
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#19067