[GH-ISSUE #7023] State mismatch error when signing in with social providers in Next.js integration since v1.4.4 #28028

Closed
opened 2026-04-17 19:22:20 -05:00 by GiteaMirror · 25 comments
Owner

Originally created by @Cybermb on GitHub (Dec 27, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/7023

Originally assigned to: @himself65, @bytaesu on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

https://github.com/Cybermb/better-auth-new-nextjs-sso-issue

  1. Clone the reproduction repository.

  2. Set the required environment variables.

  3. Run the development server.

  4. Click the sign-in button.

  5. Authenticate using GitHub (also reproducible with Google and Discord).

  6. Observe the error after redirect.

Current vs. Expected behavior

When signing in using a social provider via the client library (not a server action), an error is thrown during the callback phase:

APIError [Error [APIError]: ] {
  status: 'FOUND',
  body: undefined,
  headers: Headers {
    'set-cookie': '__Secure-better-auth.state=; Max-Age=0; Secure, __Secure-better-auth.session_token=JbFVwakAGlkSJ7Ro5p3e8jXFb6JUzJLe.ymH39VA4gTmnmfWOSVph8GnCh1flVoZ2qrsU9zgPVrs%3D; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=None',
    location: 'http://localhost:3000'
  },
  statusCode: 302
}

The error indicates a state mismatch, even though:

  • The state parameter appears to be present in the callback URL.

  • Authentication ultimately succeeds.

  • A valid session cookie is set.

  • The user is redirected correctly.

Expected behavior:

  • No error should be thrown during a successful OAuth sign-in flow.

  • State validation should pass when using the client-side sign-in API, as it did prior to v1.4.4.

What version of Better Auth are you using?

1.4.4-1.4.9

System info

{
  "system": {
    "platform": "win32",
    "arch": "x64",
  },
  "node": {
    "version": "v22.19.0",
    "env": "production"
  },
  "packageManager": {
    "name": "npm",
    "version": "9.6.6"
  },
  "frameworks": [
    {
      "name": "next",
      "version": "^16.1.1"
    },
    {
      "name": "react",
      "version": "^19.0.0"
    }
  ],
  "databases": [
    {
      "name": "@prisma/client",
      "version": "^6.6.0"
    }
  ],
  "betterAuth": {
    "version": "1.4.4-beta.1",
    "config": null
  }
}

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

Backend

Auth config (if applicable)


Additional context

This issue appears to have been introduced in version 1.4.4. Downgrading to v1.4.3 resolves the problem. Occurs when using the Next.js integration. Sign-in is initiated via the client library, not a server action. Reproducible locally in development. The OAuth flow completes successfully despite the error being thrown.

Reproducible with multiple providers:

  • GitHub
  • Google
  • Discord
Originally created by @Cybermb on GitHub (Dec 27, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/7023 Originally assigned to: @himself65, @bytaesu on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce https://github.com/Cybermb/better-auth-new-nextjs-sso-issue 1. Clone the reproduction repository. 2. Set the required environment variables. 3. Run the development server. 4. Click the sign-in button. 5. Authenticate using GitHub (also reproducible with Google and Discord). 6. Observe the error after redirect. ### Current vs. Expected behavior When signing in using a social provider via the client library (not a server action), an error is thrown during the callback phase: ``` APIError [Error [APIError]: ] { status: 'FOUND', body: undefined, headers: Headers { 'set-cookie': '__Secure-better-auth.state=; Max-Age=0; Secure, __Secure-better-auth.session_token=JbFVwakAGlkSJ7Ro5p3e8jXFb6JUzJLe.ymH39VA4gTmnmfWOSVph8GnCh1flVoZ2qrsU9zgPVrs%3D; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=None', location: 'http://localhost:3000' }, statusCode: 302 } ``` The error indicates a state mismatch, even though: - The state parameter appears to be present in the callback URL. - Authentication ultimately succeeds. - A valid session cookie is set. - The user is redirected correctly. Expected behavior: - No error should be thrown during a successful OAuth sign-in flow. - State validation should pass when using the client-side sign-in API, as it did prior to v1.4.4. ### What version of Better Auth are you using? 1.4.4-1.4.9 ### System info ```bash { "system": { "platform": "win32", "arch": "x64", }, "node": { "version": "v22.19.0", "env": "production" }, "packageManager": { "name": "npm", "version": "9.6.6" }, "frameworks": [ { "name": "next", "version": "^16.1.1" }, { "name": "react", "version": "^19.0.0" } ], "databases": [ { "name": "@prisma/client", "version": "^6.6.0" } ], "betterAuth": { "version": "1.4.4-beta.1", "config": null } } ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript ``` ### Additional context This issue appears to have been introduced in version 1.4.4. Downgrading to v1.4.3 resolves the problem. Occurs when using the Next.js integration. Sign-in is initiated via the client library, not a server action. Reproducible locally in development. The OAuth flow completes successfully despite the error being thrown. Reproducible with multiple providers: - GitHub - Google - Discord
GiteaMirror added the lockedbug labels 2026-04-17 19:22:20 -05:00
Author
Owner

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

It seems you've encountered a "state mismatch" error when trying to sign in with social providers using Better Auth in your Next.js application. This issue has been noted by others in the community and appears to have been introduced with version 1.4.4 of Better Auth.

To tackle this, here are a few suggestions:

  1. Environment Variables: Double-check that your environment variables are correctly configured for the OAuth authentication process. Ensure all required values such as client IDs and secrets are set correctly.

  2. Session Management: Since this issue happens even though authentication succeeds, confirm that session management is aligned with your OAuth flow. Problems can arise if session tokens are not being handled properly.

  3. Error Tracking: Investigate the logs for more detailed error messages during the authentication process. This can help identify if there's a specific point at which things are going wrong.

  4. Downgrade: If possible, try downgrading to version 1.4.3, as it resolves the issue according to your observations and works without throwing errors during the OAuth flow [2].

A community member noted similar experiences and mentioned that they resolved issues by focusing on the session states and ensuring proper integration with their social providers [4].

If you need additional support or if none of the above steps work, I recommend tagging @bekacru or @ping__ for guidance tailored to your specific setup.

Have you had a chance to try any of these approaches, or do you have other details you’d like to explore?

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

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3693950217 --> @better-auth-agent[bot] commented on GitHub (Dec 27, 2025): It seems you've encountered a "state mismatch" error when trying to sign in with social providers using Better Auth in your Next.js application. This issue has been noted by others in the community and appears to have been introduced with version 1.4.4 of Better Auth. To tackle this, here are a few suggestions: 1. **Environment Variables**: Double-check that your environment variables are correctly configured for the OAuth authentication process. Ensure all required values such as client IDs and secrets are set correctly. 2. **Session Management**: Since this issue happens even though authentication succeeds, confirm that session management is aligned with your OAuth flow. Problems can arise if session tokens are not being handled properly. 3. **Error Tracking**: Investigate the logs for more detailed error messages during the authentication process. This can help identify if there's a specific point at which things are going wrong. 4. **Downgrade**: If possible, try downgrading to version 1.4.3, as it resolves the issue according to your observations and works without throwing errors during the OAuth flow [[2]](https://github.com/better-auth/better-auth/issues/5563). A community member noted similar experiences and mentioned that they resolved issues by focusing on the session states and ensuring proper integration with their social providers [[4]](https://github.com/better-auth/better-auth/issues/5243). If you need additional support or if none of the above steps work, I recommend tagging @bekacru or @ping__ for guidance tailored to your specific setup. Have you had a chance to try any of these approaches, or do you have other details you’d like to explore? _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 27, 2025):

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

The "state mismatch" error in Better Auth v1.4.4+ for Next.js integrations is caused by stricter OAuth state cookie validation introduced in that version. The callback now requires the OAuth state cookie to be present and match the state parameter; if not, it throws a state mismatch error—even if authentication succeeds and the session cookie is set. This typically happens when the OAuth sign-in is initiated server-side or from a Next.js Server Component, where the cookie isn't set in the browser and is missing during callback validation. Downgrading to v1.4.3 works because earlier versions did not enforce this check, allowing the flow to succeed even if the cookie was missing or mismatched [issue discussion].

To resolve this in affected versions, initiate OAuth sign-in from a Next.js Client Component using the better-auth client library so the state cookie is set in the browser and available during callback [discussion]. You can also manually configure the state cookie attributes in your Better Auth config to use SameSite=None and Secure=true for better cookie propagation:

advanced: {
  cookies: {
    state: {
      attributes: {
        sameSite: "none",
        secure: true,
      }
    }
  }
}

[issue]

There is a config option skipStateCookieCheck (added in v1.4.4) that bypasses state cookie validation, but this is only recommended for development or staging due to security risks [PR].

If you use the Next.js integration's nextCookies plugin, it can help replay set-cookie headers into Next.js cookies, but it may cause crashes if used outside request scope or in certain monorepo setups [source].

For production, always initiate social sign-in from the client and ensure all app URLs are listed in trustedOrigins to avoid state mismatch errors [issue].

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:3693952211 --> @dosubot[bot] commented on GitHub (Dec 27, 2025): <!-- Greeting --> Hi @Cybermb! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> The "state mismatch" error in Better Auth v1.4.4+ for Next.js integrations is caused by stricter OAuth state cookie validation introduced in that version. The callback now requires the OAuth state cookie to be present and match the state parameter; if not, it throws a state mismatch error—even if authentication succeeds and the session cookie is set. This typically happens when the OAuth sign-in is initiated server-side or from a Next.js Server Component, where the cookie isn't set in the browser and is missing during callback validation. Downgrading to v1.4.3 works because earlier versions did not enforce this check, allowing the flow to succeed even if the cookie was missing or mismatched [[issue discussion](https://github.com/better-auth/better-auth/issues/6535)]. To resolve this in affected versions, initiate OAuth sign-in from a Next.js Client Component using the better-auth client library so the state cookie is set in the browser and available during callback [[discussion](https://github.com/better-auth/better-auth/discussions/6563)]. You can also manually configure the state cookie attributes in your Better Auth config to use `SameSite=None` and `Secure=true` for better cookie propagation: ```typescript advanced: { cookies: { state: { attributes: { sameSite: "none", secure: true, } } } } ``` [[issue](https://github.com/better-auth/better-auth/issues/6483)] There is a config option `skipStateCookieCheck` (added in v1.4.4) that bypasses state cookie validation, but this is only recommended for development or staging due to security risks [[PR](https://github.com/better-auth/better-auth/pull/4991)]. If you use the Next.js integration's `nextCookies` plugin, it can help replay set-cookie headers into Next.js cookies, but it may cause crashes if used outside request scope or in certain monorepo setups [[source](https://github.com/better-auth/better-auth/blob/4d7d7d5a76b5e0e90d42238f00751584ec07afa7/packages/better-auth/src/integrations/next-js.ts#L5-L85)]. For production, always initiate social sign-in from the client and ensure all app URLs are listed in `trustedOrigins` to avoid state mismatch errors [[issue](https://github.com/better-auth/better-auth/issues/6483)]. <!-- 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/7569feea-0393-4e34-bcae-6b8c7109ea25?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/7569feea-0393-4e34-bcae-6b8c7109ea25?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/7569feea-0393-4e34-bcae-6b8c7109ea25?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/7569feea-0393-4e34-bcae-6b8c7109ea25?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/7569feea-0393-4e34-bcae-6b8c7109ea25?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/7569feea-0393-4e34-bcae-6b8c7109ea25?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/7569feea-0393-4e34-bcae-6b8c7109ea25?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=The%20%22state%20mismatch%22%20error%20in%20Better%20Auth%20v1.4.4%2B%20for%20Next.js%20integrations%20is%20caused%20by%20stricter%20OAuth%20state%20cookie%20validation%20introduced%20in%20that%20version.%20The%20callback%20now%20requires%20the%20OAuth%20state%20cookie%20to%20be%20present%20and%20match%20the%20state%20parameter%3B%20if%20not%2C%20it%20throws%20a%20state%20mismatch%20error%E2%80%94even%20if%20authentication%20succeeds%20and%20the%20session%20cookie%20is%20set.%20This%20typically%20happens%20when%20the%20OAuth%20sign-in%20is%20initiated%20server-side%20or%20from%20a%20Next.js%20Server%20Component%2C%20where%20the%20cookie%20isn%27t%20set%20in%20the%20browser%20and%20is%20missing%20during%20callback%20validation.%20Downgrading%20to%20v1.4.3%20works%20because%20earlier%20versions%20did%20not%20enforce%20this%20check%2C%20allowing%20the%20flow%20to%20succeed%20even%20if%20the%20cookie%20was%20missing%20or%20mismatched%20%5B%5Bissue%20discussion%5D%28https%3A//github.com/better-auth/better-auth/issues/6535%29%5D.%0A%0ATo%20resolve%20this%20in%20affected%20versions%2C%20initiate%20OAuth%20sign-in%20from%20a%20Next.js%20Client%20Component%20using%20the%20better-auth%20client%20library%20so%20the%20state%20cookie%20is%20set%20in%20the%20browser%20and%20available%20during%20callback%20%5B%5Bdiscussion%5D%28https%3A//github.com/better-auth/better-auth/discussions/6563%29%5D.%20You%20can%20also%20manually%20configure%20the%20state%20cookie%20attributes%20in%20your%20Better%20Auth%20config%20to%20use%20%60SameSite%3DNone%60%20and%20%60Secure%3Dtrue%60%20for%20better%20cookie%20propagation%3A%0A%0A%60%60%60typescript%0Aadvanced%3A%20%7B%0A%20%20cookies%3A%20%7B%0A%20%20%20%20state%3A%20%7B%0A%20%20%20%20%20%20attributes%3A%20%7B%0A%20%20%20%20%20%20%20%20sameSite%3A%20%22none%22%2C%0A%20%20%20%20%20%20%20%20secure%3A%20true%2C%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A%60%60%60%0A%5B%5Bissue%5D%28https%3A//github.com/better-auth/better-auth/issues/6483%29%5D%0A%0AThere%20is%20a%20config%20option%20%60skipStateCookieCheck%60%20%28added%20in%20v1.4.4%29%20that%20bypasses%20state%20cookie%20validation%2C%20but%20this%20is%20only%20recommended%20for%20development%20or%20staging%20due%20to%20security%20risks%20%5B%5BPR%5D%28https%3A//github.com/better-auth/better-auth/pull/4991%29%5D.%0A%0AIf%20you%20use%20the%20Next.js%20integration%27s%20%60nextCookies%60%20plugin%2C%20it%20can%20help%20replay%20set-cookie%20headers%20into%20Next.js%20cookies%2C%20but%20it%20may%20cause%20crashes%20if%20used%20outside%20request%20scope%20or%20in%20certain%20monorepo%20setups%20%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/blob/4d7d7d5a76b5e0e90d42238f00751584ec07afa7/packages/better-auth/src/integrations/next-js.ts%23L5-L85%29%5D.%0A%0AFor%20production%2C%20always%20initiate%20social%20sign-in%20from%20the%20client%20and%20ensure%20all%20app%20URLs%20are%20listed%20in%20%60trustedOrigins%60%20to%20avoid%20state%20mismatch%20errors%20%5B%5Bissue%5D%28https%3A//github.com/better-auth/better-auth/issues/6483%29%5D.)&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/7023)
Author
Owner

@bytaesu commented on GitHub (Dec 27, 2025):

Hi @Cybermb, I'll look into this!

<!-- gh-comment-id:3694009826 --> @bytaesu commented on GitHub (Dec 27, 2025): Hi @Cybermb, I'll look into this!
Author
Owner

@bytaesu commented on GitHub (Dec 27, 2025):

Hi @Cybermb,

I couldn't reproduce this in the same environment. Could you try again? 🤔

And, you don't need to explicitly specify socialProviders.github.redirectURI

If you run into any blockers, I can help 🙂


https://github.com/user-attachments/assets/9aebab40-b133-4fc7-bd0e-f4f8bb985772

<!-- gh-comment-id:3694150019 --> @bytaesu commented on GitHub (Dec 27, 2025): Hi @Cybermb, I couldn't reproduce this in the same environment. Could you try again? 🤔 And, you don't need to explicitly specify `socialProviders.github.redirectURI` If you run into any blockers, I can help 🙂 --- https://github.com/user-attachments/assets/9aebab40-b133-4fc7-bd0e-f4f8bb985772
Author
Owner

@Cybermb commented on GitHub (Dec 27, 2025):

Hey @bytaesu
I do see you get same error (0:02-0:03) as I do

Image

As noted, the OAuth flow completes successfully despite the error being thrown.

I did not get into this reproduction but one my production apps are appending error=please_restart_the_process in url after user singin. I believe that is caused by this issue. Nevermind, it was unrelated to this issue

<!-- gh-comment-id:3694177649 --> @Cybermb commented on GitHub (Dec 27, 2025): Hey @bytaesu I do see you get same error (0:02-0:03) as I do <img width="2013" height="516" alt="Image" src="https://github.com/user-attachments/assets/9315a926-1bad-4cb1-a948-daf8a8479af6" /> As noted, the OAuth flow completes successfully despite the error being thrown. ~~I did not get into this reproduction but one my production apps are appending `error=please_restart_the_process` in url after user singin. I believe that is caused by this issue.~~ Nevermind, it was unrelated to this issue
Author
Owner

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

Hi @Cybermb,

When using pnpm instead of yarn, the logs disappear.

It seems the filtering that disables logs on HTTP 302 redirects (not actual error) doesn't work correctly with yarn for now 🤔

Will look into this

<!-- gh-comment-id:3694919898 --> @bytaesu commented on GitHub (Dec 28, 2025): Hi @Cybermb, When using `pnpm` instead of `yarn`, the logs disappear. It seems the filtering that disables logs on HTTP 302 redirects (not actual error) doesn't work correctly with `yarn` for now 🤔 Will look into this
Author
Owner

@tjx666 commented on GitHub (Dec 30, 2025):

I use pnpm also occur this when sign with google


⏺ POST /api/auth/sign-in/social 200 in 965ms (compile: 28ms, proxy.ts: 5ms, render: 932ms)
  2025-12-30T09:15:17.252Z ERROR [Better Auth]: APIError [Error [APIError]: ] {
    status: 'FOUND',
    body: undefined,
    headers: Headers {
      'set-cookie': 'better-auth.state=; Max-Age=0, better-auth.session_token=<REDACTED_SESSION_TOKEN>; Max-Age=604800; Path=/; HttpOnly; SameSite=Lax, better-auth.session_data=<REDACTED_SESSION_DATA>; Max-Age=600; Path=/; HttpOnly; SameSite=Lax',
      location: '/'
    },
    statusCode: 302
  }
   GET /api/auth/callback/google?state=<REDACTED_STATE>&code=<REDACTED_CODE>&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=0&prompt=none 302 in 4.3s (compile: 8ms, proxy.ts: 1842µs, render: 4.3s)
  [rewrite] / -> /zh-CN__0__dark
<!-- gh-comment-id:3698801107 --> @tjx666 commented on GitHub (Dec 30, 2025): I use pnpm also occur this when sign with google - "better-auth": "^1.4.6" - repo: https://github.com/lobehub/lobe-chat/tree/dev ```bash ⏺ POST /api/auth/sign-in/social 200 in 965ms (compile: 28ms, proxy.ts: 5ms, render: 932ms) 2025-12-30T09:15:17.252Z ERROR [Better Auth]: APIError [Error [APIError]: ] { status: 'FOUND', body: undefined, headers: Headers { 'set-cookie': 'better-auth.state=; Max-Age=0, better-auth.session_token=<REDACTED_SESSION_TOKEN>; Max-Age=604800; Path=/; HttpOnly; SameSite=Lax, better-auth.session_data=<REDACTED_SESSION_DATA>; Max-Age=600; Path=/; HttpOnly; SameSite=Lax', location: '/' }, statusCode: 302 } GET /api/auth/callback/google?state=<REDACTED_STATE>&code=<REDACTED_CODE>&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=0&prompt=none 302 in 4.3s (compile: 8ms, proxy.ts: 1842µs, render: 4.3s) [rewrite] / -> /zh-CN__0__dark ```
Author
Owner

@tjx666 commented on GitHub (Dec 30, 2025):

After I lock betterauth version to 1.4.6, this error disappear

<!-- gh-comment-id:3698837298 --> @tjx666 commented on GitHub (Dec 30, 2025): After I lock betterauth version to 1.4.6, this error disappear
Author
Owner

@himself65 commented on GitHub (Dec 31, 2025):

After I lock betterauth version to 1.4.6, this error disappear

I will take a look

<!-- gh-comment-id:3702212289 --> @himself65 commented on GitHub (Dec 31, 2025): > After I lock betterauth version to 1.4.6, this error disappear I will take a look
Author
Owner

@ItayElgazar commented on GitHub (Jan 11, 2026):

Is this solved?

<!-- gh-comment-id:3735728899 --> @ItayElgazar commented on GitHub (Jan 11, 2026): Is this solved?
Author
Owner

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

Is this solved?

We are checking this 🧐

<!-- gh-comment-id:3740183320 --> @bytaesu commented on GitHub (Jan 12, 2026): > Is this solved? We are checking this 🧐
Author
Owner

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

I can reproduce this and have listed the detailed solution

There could be two issues here, but not on the better-auth side.

  1. Yarn v1 module resolution issue (maybe other package managers could have a similar issue)
  2. Next.js (turbopack), or Vite bundler module resolution issue

For 1

Please manually install better-call, and add the resolutions section. This will force making better-call to the top level.

 "dependencies": {
    // ...
    "better-call": "^1.1.8",
    // ...
  },
  "resolutions": {
    "better-call": "^1.1.8"
  },

/cc @tjx666 (you are using pnpm, but I think the same, pnpm v9 could have a similar issue, I tried on yarn v3 and pnpm 12, and it works well)

For 2

This is tricky, you can check https://github.com/yjs/yjs/issues/438

Basically, please use resolve.alias for webpack, resolve.dedupe for Vite, or add better-auth in serverExternalPackages for Next.js

There's not only one solution, but what we are doing here is trying to make Bundler resolve the module to the same instance


I'm closing this issue; this will be the final solution. If you believe it's from us, file another issue with a reproducible GitHub repo.

<!-- gh-comment-id:3740635680 --> @himself65 commented on GitHub (Jan 12, 2026): I can reproduce this and have listed the detailed solution There could be two issues here, but not on the better-auth side. 1. Yarn v1 module resolution issue (maybe other package managers could have a similar issue) 2. Next.js (turbopack), or Vite bundler module resolution issue For 1 Please manually install `better-call`, and add the `resolutions` section. This will force making `better-call` to the top level. ```jsonc "dependencies": { // ... "better-call": "^1.1.8", // ... }, "resolutions": { "better-call": "^1.1.8" }, ``` /cc @tjx666 (you are using pnpm, but I think the same, pnpm v9 could have a similar issue, I tried on yarn v3 and pnpm 12, and it works well) For 2 This is tricky, you can check https://github.com/yjs/yjs/issues/438 Basically, please use `resolve.alias` for webpack, `resolve.dedupe` for Vite, or add `better-auth` in `serverExternalPackages` for Next.js There's not only one solution, but what we are doing here is trying to make Bundler resolve the module to the same instance --- I'm closing this issue; this will be the final solution. If you believe it's from us, file another issue with a reproducible GitHub repo.
Author
Owner

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

https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue

<!-- gh-comment-id:3741086399 --> @himself65 commented on GitHub (Jan 13, 2026): https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue
Author
Owner

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

@himself65 Coming from https://github.com/better-auth/better-auth/issues/6613, I've tried the both fixes listed in https://github.com/better-auth/better-auth/issues/7023#issuecomment-3740635680 and https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue but with no avail.

It did fix the Better Auth was already imported. This breaks async local storage instance and will lead to issues! warning, but the

Error: No request state found. Please make sure you are calling this function within a runWithRequestState callback."

error is still there.

I've committed the fixes in my MVCE repo: https://github.com/DarthGigi/better-auth-oauthplugin-mvce

<!-- gh-comment-id:3741153605 --> @DarthGigi commented on GitHub (Jan 13, 2026): @himself65 Coming from https://github.com/better-auth/better-auth/issues/6613, I've tried the both fixes listed in https://github.com/better-auth/better-auth/issues/7023#issuecomment-3740635680 and https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue but with no avail. It did fix the `Better Auth was already imported. This breaks async local storage instance and will lead to issues!` warning, but the > Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback." error is still there. I've committed the fixes in my MVCE repo: https://github.com/DarthGigi/better-auth-oauthplugin-mvce
Author
Owner

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

@himself65 Coming from #6613, I've tried the both fixes listed in #7023 (comment) and https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue but with no avail.

It did fix the Better Auth was already imported. This breaks async local storage instance and will lead to issues! warning, but the

Error: No request state found. Please make sure you are calling this function within a runWithRequestState callback."

error is still there.

I've committed the fixes in my MVCE repo: https://github.com/DarthGigi/better-auth-oauthplugin-mvce

Index: vite.config.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/vite.config.ts b/vite.config.ts
--- a/vite.config.ts	(revision c2d98acd7f498d9b583b54766e9524926f02b3d4)
+++ b/vite.config.ts	(date 1768265762959)
@@ -2,10 +2,14 @@
 import tailwindcss from '@tailwindcss/vite';
 import { defineConfig } from 'vite';
 import devtoolsJson from 'vite-plugin-devtools-json';
 
 export default defineConfig({
 	resolve: {
-		dedupe: ['better-call', 'better-auth', '@better-auth/oauth-provider']
+		external: ['better-auth']
+	},
+	ssr: {
+		external: ['better-auth']
 	},
 	plugins: [tailwindcss(), sveltekit(), devtoolsJson()]
 });

Don't bundle better-auth using Vite. It causes dual module in the runtime, not only build time.

<!-- gh-comment-id:3741287576 --> @himself65 commented on GitHub (Jan 13, 2026): > [@himself65](https://github.com/himself65) Coming from [#6613](https://github.com/better-auth/better-auth/issues/6613), I've tried the both fixes listed in [#7023 (comment)](https://github.com/better-auth/better-auth/issues/7023#issuecomment-3740635680) and https://www.better-auth.com/docs/reference/faq#dual-module-hazard-issue but with no avail. > > It did fix the `Better Auth was already imported. This breaks async local storage instance and will lead to issues!` warning, but the > > > Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback." > > error is still there. > > I've committed the fixes in my MVCE repo: https://github.com/DarthGigi/better-auth-oauthplugin-mvce ```diff Index: vite.config.ts IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/vite.config.ts b/vite.config.ts --- a/vite.config.ts (revision c2d98acd7f498d9b583b54766e9524926f02b3d4) +++ b/vite.config.ts (date 1768265762959) @@ -2,10 +2,14 @@ import tailwindcss from '@tailwindcss/vite'; import { defineConfig } from 'vite'; import devtoolsJson from 'vite-plugin-devtools-json'; export default defineConfig({ resolve: { - dedupe: ['better-call', 'better-auth', '@better-auth/oauth-provider'] + external: ['better-auth'] + }, + ssr: { + external: ['better-auth'] }, plugins: [tailwindcss(), sveltekit(), devtoolsJson()] }); ``` Don't bundle `better-auth` using Vite. It causes dual module in the runtime, not only build time.
Author
Owner

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

Or you can use this setup

Index: vite.config.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/vite.config.ts b/vite.config.ts
--- a/vite.config.ts	(revision c2d98acd7f498d9b583b54766e9524926f02b3d4)
+++ b/vite.config.ts	(date 1768268142605)
@@ -2,10 +2,14 @@
 import tailwindcss from '@tailwindcss/vite';
 import { defineConfig } from 'vite';
 import devtoolsJson from 'vite-plugin-devtools-json';
 
 export default defineConfig({
-	resolve: {
-		dedupe: ['better-call', 'better-auth', '@better-auth/oauth-provider']
+	optimizeDeps: {
+		include: ['better-auth', '@better-auth/oauth-provider']
+	},
+	ssr: {
+		noExternal: ['better-auth', '@better-auth/oauth-provider']
 	},
 	plugins: [tailwindcss(), sveltekit(), devtoolsJson()]
 });

Refer to https://github.com/wakujs/waku/issues/421#issuecomment-3736711094

<!-- gh-comment-id:3741379979 --> @himself65 commented on GitHub (Jan 13, 2026): Or you can use this setup ```diff Index: vite.config.ts IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/vite.config.ts b/vite.config.ts --- a/vite.config.ts (revision c2d98acd7f498d9b583b54766e9524926f02b3d4) +++ b/vite.config.ts (date 1768268142605) @@ -2,10 +2,14 @@ import tailwindcss from '@tailwindcss/vite'; import { defineConfig } from 'vite'; import devtoolsJson from 'vite-plugin-devtools-json'; export default defineConfig({ - resolve: { - dedupe: ['better-call', 'better-auth', '@better-auth/oauth-provider'] + optimizeDeps: { + include: ['better-auth', '@better-auth/oauth-provider'] + }, + ssr: { + noExternal: ['better-auth', '@better-auth/oauth-provider'] }, plugins: [tailwindcss(), sveltekit(), devtoolsJson()] }); ``` Refer to https://github.com/wakujs/waku/issues/421#issuecomment-3736711094
Author
Owner

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

IMO, vite is super hard to debug when there's a diamond dependency or ESM/CJS.

<!-- gh-comment-id:3741381989 --> @himself65 commented on GitHub (Jan 13, 2026): IMO, vite is super hard to debug when there's a diamond dependency or ESM/CJS.
Author
Owner

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

I've tried the first fix you commented and that one seems to solve the issue, at least for me. Thanks a lot 👍🏼

<!-- gh-comment-id:3741385933 --> @DarthGigi commented on GitHub (Jan 13, 2026): I've tried the first fix you commented and that one seems to solve the issue, at least for me. Thanks a lot 👍🏼
Author
Owner

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

@himself65 latest pnpm is v11 alpha, where you test the pnpm v12. I use pnpm v10 local and can reproduce the issue

<!-- gh-comment-id:3741645446 --> @tjx666 commented on GitHub (Jan 13, 2026): @himself65 latest pnpm is v11 alpha, where you test the pnpm v12. I use pnpm v10 local and can reproduce the issue
Author
Owner

@k-urtica commented on GitHub (Jan 13, 2026):

Sorry to comment on a closed issue, but I'm experiencing the same problem with Nuxt and Cloudflare Workers.

I've tried various solutions, including checking related issues and the FAQ section added to the documentation, but I'm still stuck and unable to resolve it.

Could you please help?

Environment:

  • Nuxt: v4.2.2
  • nodejs_compat enabled
  • compatibility_date: 2026-01-10
  • No duplicate better-auth versions

better-auth: This occurs on v1.4.0 and later. It works fine on v1.3.34.

ERROR [Better Auth]: Error Error: No request state found. Please make sure you are calling this function within a runWithRequestState callback.

Reproduction repo: https://github.com/k-urtica/better-auth-nuxt-poc

<!-- gh-comment-id:3744809194 --> @k-urtica commented on GitHub (Jan 13, 2026): Sorry to comment on a closed issue, but I'm experiencing the same problem with Nuxt and Cloudflare Workers. I've tried various solutions, including checking related issues and the FAQ section added to the documentation, but I'm still stuck and unable to resolve it. Could you please help? **Environment:** - Nuxt: v4.2.2 - nodejs_compat enabled - compatibility_date: 2026-01-10 - No duplicate better-auth versions **better-auth:** This occurs on v1.4.0 and later. It works fine on v1.3.34. > ERROR [Better Auth]: Error Error: No request state found. Please make sure you are calling this function within a `runWithRequestState` callback. **Reproduction repo:** https://github.com/k-urtica/better-auth-nuxt-poc
Author
Owner

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

cc @himself65 🙏

<!-- gh-comment-id:3744815221 --> @bytaesu commented on GitHub (Jan 13, 2026): cc @himself65 🙏
Author
Owner

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

@himself65 latest pnpm is v11 alpha, where you test the pnpm v12. I use pnpm v10 local and can reproduce the issue

Sorry, my typo. I mean pnpm v10

<!-- gh-comment-id:3745433708 --> @himself65 commented on GitHub (Jan 13, 2026): > [@himself65](https://github.com/himself65) latest pnpm is v11 alpha, where you test the pnpm v12. I use pnpm v10 local and can reproduce the issue Sorry, my typo. I mean pnpm v10
Author
Owner

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

I think up with a way to completely fix this problem from our side. I will open a PR for that.

<!-- gh-comment-id:3745436014 --> @himself65 commented on GitHub (Jan 13, 2026): I think up with a way to completely fix this problem from our side. I will open a PR for that.
Author
Owner

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

We should fixed this since 1.4.13

<!-- gh-comment-id:3752842363 --> @himself65 commented on GitHub (Jan 15, 2026): We should fixed this since [1.4.13](https://github.com/better-auth/better-auth/commit/d702b88d53ce0b02af1cf9683813b6e61ef18dd4)
Author
Owner

@k-urtica commented on GitHub (Jan 15, 2026):

Thank you, but I'm still getting the same error with v1.4.13.

After digging into it more, I realized this isn't actually a Better-Auth issue — it's a Nuxt (Nitro) config problem. I had to enable the experimental asyncContext flag to use AsyncLocalStorage.

nitro: {
  experimental: {
    asyncContext: true,
  },
  unenv: {
    external: ['node:async_hooks'],
},

https://github.com/nitrojs/nitro/issues/1943#issuecomment-2573016133

This confirms that it functions correctly as it did up to v1.3.34 (verified in v1.4.12 and v1.4.13).
Thanks for your help!

<!-- gh-comment-id:3754159131 --> @k-urtica commented on GitHub (Jan 15, 2026): Thank you, but I'm still getting the same error with v1.4.13. After digging into it more, I realized this isn't actually a Better-Auth issue — it's a Nuxt (Nitro) config problem. I had to enable the experimental `asyncContext` flag to use AsyncLocalStorage. ```ts nitro: { experimental: { asyncContext: true, }, unenv: { external: ['node:async_hooks'], }, ``` https://github.com/nitrojs/nitro/issues/1943#issuecomment-2573016133 This confirms that it functions correctly as it did up to v1.3.34 (verified in v1.4.12 and v1.4.13). Thanks for your help!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#28028