[GH-ISSUE #5658] Next.js 16 "please_restart_the_process" OAuth error #18946

Closed
opened 2026-04-15 17:40:42 -05:00 by GiteaMirror · 8 comments
Owner

Originally created by @horvatz on GitHub (Oct 29, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/5658

Originally assigned to: @himself65 on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Upgrade Next.js project to version 16
  2. Try to log in with OAuth provider (for example Google)

Current vs. Expected behavior

Expected behavior:
The user should be redirected to the specified authenticated page while already signed in.

Actual behavior:
After clicking “Sign in with Google” (or other OAuth provider), a please_restart_process error appears. However, if I click “Return to application” on the error page, I’m redirected correctly and the user is signed in as expected.

It seems the callback is being triggered twice — the first attempt succeeds, but the second fails and causes the error redirect.

This issue started occurring after upgrading to Next.js 16; everything worked as expected before the upgrade.

What version of Better Auth are you using?

1.4.0-beta.13

System info

📊 Better Auth System Information

==================================================

🖥️  System Information:
  platform: darwin
  arch: arm64
  version: Darwin Kernel Version 24.6.0: Mon Jul 14 11:29:54 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T8122
  release: 24.6.0
  cpuCount: 8
  cpuModel: Apple M3
  totalMemory: 16.00 GB
  freeMemory: 0.13 GB

📦 Node.js:
  version: v20.18.1
  env: development

📦 Package Manager:
  name: bun
  version: 1.3.0

🚀 Frameworks:
  name: next
  version: 16.0.0
  name: react
  version: 19.2.0
  name: hono
  version: ^4.9.7

💾 Database Clients:
  name: pg
  version: ^8.16.3
  name: drizzle
  version: ^0.44.5

🔐 Better Auth:
  Version: 1.4.0-beta.13
  Configuration:
    trustedOrigins: app.astra-ai.co
https://app.astra-ai.co
https://appleid.apple.com
*.vercel.app
*.ngrok.app
*localhost:3000
    rateLimit:
      enabled: false
      window: 10
      max: 500
    emailAndPassword:
      enabled: false
    databaseHooks:
      user:
        create:
          {}
      session:
        create:
          {}
    advanced:
      cookies:
        state:
          attributes:
            sameSite: lax
            secure: false
      database:
        {}
    telemetry:
      enabled: false
    user:
      additionalFields:
        parentEmail:
          type: string
          required: false
        registrationFingerprint:
          type: string
          required: false
        deletedAt:
          type: date
          required: false
    session:
      cookieCache:
        enabled: true
        maxAge: 300
    account:
      accountLinking:
        enabled: true
        trustedProviders: google
apple
    socialProviders:
      google:
        {}
      apple:
        {}
    plugins: name: admin
config:
  id: admin
  hooks:
    after: {}
  endpoints:
    {}
  $ERROR_CODES:
    FAILED_TO_CREATE_USER: Failed to create user
    USER_ALREADY_EXISTS: User already exists.
    USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: User already exists. Use another email.
    YOU_CANNOT_BAN_YOURSELF: You cannot ban yourself
    YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE: You are not allowed to change users role
    YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS: You are not allowed to create users
    YOU_ARE_NOT_ALLOWED_TO_LIST_USERS: You are not allowed to list users
    YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS: You are not allowed to list users sessions
    YOU_ARE_NOT_ALLOWED_TO_BAN_USERS: You are not allowed to ban users
    YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS: You are not allowed to impersonate users
    YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS: You are not allowed to revoke users sessions
    YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS: You are not allowed to delete users
    YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD: [REDACTED]
    BANNED_USER: You have been banned from this application
    YOU_ARE_NOT_ALLOWED_TO_GET_USER: You are not allowed to get user
    NO_DATA_TO_UPDATE: No data to update
    YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS: You are not allowed to update users
    YOU_CANNOT_REMOVE_YOURSELF: You cannot remove yourself
    YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE: You are not allowed to set a non-existent role value
  schema:
    user:
      fields:
        role:
          type: string
          required: false
          input: false
        banned:
          type: boolean
          defaultValue: false
          required: false
          input: false
        banReason:
          type: string
          required: false
          input: false
        banExpires:
          type: date
          required: false
          input: false
    session:
      fields:
        impersonatedBy:
          type: string
          required: false
name: one-tap
config:
  id: one-tap
  endpoints:
    {}
name: anonymous
config:
  id: anonymous
  endpoints:
    {}
  hooks:
    after: {}
  schema:
    user:
      fields:
        isAnonymous:
          type: boolean
          required: false
  $ERROR_CODES:
    FAILED_TO_CREATE_USER: Failed to create user
    COULD_NOT_CREATE_SESSION: Could not create session
    ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY: Anonymous users cannot sign in again anonymously
name: email-otp
config:
  id: email-otp
  endpoints:
    {}
  hooks:
    after: {}
  $ERROR_CODES:
    OTP_EXPIRED: otp expired
    INVALID_OTP: Invalid OTP
    INVALID_EMAIL: Invalid email
    USER_NOT_FOUND: User not found
    TOO_MANY_ATTEMPTS: Too many attempts
  rateLimit: window: 60
max: 3
window: 60
max: 3
window: 60
max: 3
window: 60
max: 3
name: next-cookies
config:
  id: next-cookies
  hooks:
    after: {}

==================================================

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

Client, Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
    provider: 'pg',
    schema: {
      ...schema,
      users: schema.usersDBTable,
      sessions: schema.sessionsDBTable,
    },
    usePlural: true,
  }),
  emailAndPassword: {
    enabled: false,
  },
 socialProviders: {
    google: {
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
    },
....
  },
...
});

Additional context

No response

Originally created by @horvatz on GitHub (Oct 29, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/5658 Originally assigned to: @himself65 on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Upgrade Next.js project to version 16 2. Try to log in with OAuth provider (for example Google) ### Current vs. Expected behavior **Expected behavior:** The user should be redirected to the specified authenticated page while already signed in. **Actual behavior:** After clicking “Sign in with Google” (or other OAuth provider), a `please_restart_process` error appears. However, if I click “Return to application” on the error page, I’m redirected correctly and the user is signed in as expected. It seems the callback is being triggered twice — the first attempt succeeds, but the second fails and causes the error redirect. This issue started occurring after upgrading to Next.js 16; everything worked as expected before the upgrade. ### What version of Better Auth are you using? 1.4.0-beta.13 ### System info ```bash 📊 Better Auth System Information ================================================== 🖥️ System Information: platform: darwin arch: arm64 version: Darwin Kernel Version 24.6.0: Mon Jul 14 11:29:54 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T8122 release: 24.6.0 cpuCount: 8 cpuModel: Apple M3 totalMemory: 16.00 GB freeMemory: 0.13 GB 📦 Node.js: version: v20.18.1 env: development 📦 Package Manager: name: bun version: 1.3.0 🚀 Frameworks: name: next version: 16.0.0 name: react version: 19.2.0 name: hono version: ^4.9.7 💾 Database Clients: name: pg version: ^8.16.3 name: drizzle version: ^0.44.5 🔐 Better Auth: Version: 1.4.0-beta.13 Configuration: trustedOrigins: app.astra-ai.co https://app.astra-ai.co https://appleid.apple.com *.vercel.app *.ngrok.app *localhost:3000 rateLimit: enabled: false window: 10 max: 500 emailAndPassword: enabled: false databaseHooks: user: create: {} session: create: {} advanced: cookies: state: attributes: sameSite: lax secure: false database: {} telemetry: enabled: false user: additionalFields: parentEmail: type: string required: false registrationFingerprint: type: string required: false deletedAt: type: date required: false session: cookieCache: enabled: true maxAge: 300 account: accountLinking: enabled: true trustedProviders: google apple socialProviders: google: {} apple: {} plugins: name: admin config: id: admin hooks: after: {} endpoints: {} $ERROR_CODES: FAILED_TO_CREATE_USER: Failed to create user USER_ALREADY_EXISTS: User already exists. USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: User already exists. Use another email. YOU_CANNOT_BAN_YOURSELF: You cannot ban yourself YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE: You are not allowed to change users role YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS: You are not allowed to create users YOU_ARE_NOT_ALLOWED_TO_LIST_USERS: You are not allowed to list users YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS: You are not allowed to list users sessions YOU_ARE_NOT_ALLOWED_TO_BAN_USERS: You are not allowed to ban users YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS: You are not allowed to impersonate users YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS: You are not allowed to revoke users sessions YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS: You are not allowed to delete users YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD: [REDACTED] BANNED_USER: You have been banned from this application YOU_ARE_NOT_ALLOWED_TO_GET_USER: You are not allowed to get user NO_DATA_TO_UPDATE: No data to update YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS: You are not allowed to update users YOU_CANNOT_REMOVE_YOURSELF: You cannot remove yourself YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE: You are not allowed to set a non-existent role value schema: user: fields: role: type: string required: false input: false banned: type: boolean defaultValue: false required: false input: false banReason: type: string required: false input: false banExpires: type: date required: false input: false session: fields: impersonatedBy: type: string required: false name: one-tap config: id: one-tap endpoints: {} name: anonymous config: id: anonymous endpoints: {} hooks: after: {} schema: user: fields: isAnonymous: type: boolean required: false $ERROR_CODES: FAILED_TO_CREATE_USER: Failed to create user COULD_NOT_CREATE_SESSION: Could not create session ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY: Anonymous users cannot sign in again anonymously name: email-otp config: id: email-otp endpoints: {} hooks: after: {} $ERROR_CODES: OTP_EXPIRED: otp expired INVALID_OTP: Invalid OTP INVALID_EMAIL: Invalid email USER_NOT_FOUND: User not found TOO_MANY_ATTEMPTS: Too many attempts rateLimit: window: 60 max: 3 window: 60 max: 3 window: 60 max: 3 window: 60 max: 3 name: next-cookies config: id: next-cookies hooks: after: {} ================================================== ``` ### Which area(s) are affected? (Select all that apply) Client, Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ provider: 'pg', schema: { ...schema, users: schema.usersDBTable, sessions: schema.sessionsDBTable, }, usePlural: true, }), emailAndPassword: { enabled: false, }, socialProviders: { google: { clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }, .... }, ... }); ``` ### Additional context _No response_
GiteaMirror added the locked label 2026-04-15 17:40:42 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Oct 29, 2025):

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

This is a known issue with Better Auth and OAuth flows, especially after upgrading to Next.js 16. The please_restart_the_process error typically happens when the OAuth callback endpoint is triggered twice: the first call consumes the OAuth state and succeeds, but the second fails because the state is already used, resulting in the error redirect. This double-callback behavior is often caused by misconfigured callback URLs, client-side navigation, or redirect loops in your app. You do not need to colocate your UI and backend, but only one app should handle the OAuth callback per flow—let the backend handle the callback and redirect to a user-facing route like /dashboard or / on the frontend, not the API callback endpoint itself [source].

To fix this, make sure:

  • Social sign-in is always initiated from the client using Better Auth's client SDK, and the callbackURL is set to a user-facing route (not the API callback endpoint) [source].
  • All relevant domains (local, preview, production) are included in trustedOrigins and registered as callback URLs with your OAuth provider [source].
  • For cross-site OAuth flows, set your state cookie attributes to SameSite=None and Secure=true, and use a custom domain for both development and production if possible [source].
  • If you want to handle errors gracefully, set onAPIError.errorURL in your Better Auth config to a frontend error page [source].

Recent updates to Better Auth and Next.js 16 mainly affect middleware file naming (proxy.ts instead of middleware.ts) and session cookie handling, but do not directly address this error. The root cause is almost always double-callback or cookie/state misconfiguration. Use browser devtools to confirm the callback sequence and cookie attributes if you need to debug further.

To reply, just mention @dosu.


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

<!-- gh-comment-id:3460671625 --> @dosubot[bot] commented on GitHub (Oct 29, 2025): <!-- Greeting --> Hi @horvatz! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This is a known issue with Better Auth and OAuth flows, especially after upgrading to Next.js 16. The `please_restart_the_process` error typically happens when the OAuth callback endpoint is triggered twice: the first call consumes the OAuth state and succeeds, but the second fails because the state is already used, resulting in the error redirect. This double-callback behavior is often caused by misconfigured callback URLs, client-side navigation, or redirect loops in your app. You do not need to colocate your UI and backend, but only one app should handle the OAuth callback per flow—let the backend handle the callback and redirect to a user-facing route like `/dashboard` or `/` on the frontend, not the API callback endpoint itself [[source](https://github.com/better-auth/better-auth/issues/4275#issuecomment-3233637993)]. To fix this, make sure: - Social sign-in is always initiated from the client using Better Auth's client SDK, and the callbackURL is set to a user-facing route (not the API callback endpoint) [[source](https://github.com/better-auth/better-auth/issues/5478)]. - All relevant domains (local, preview, production) are included in `trustedOrigins` and registered as callback URLs with your OAuth provider [[source](https://github.com/better-auth/better-auth/issues/5563)]. - For cross-site OAuth flows, set your state cookie attributes to `SameSite=None` and `Secure=true`, and use a custom domain for both development and production if possible [[source](https://github.com/better-auth/better-auth/issues/5563)]. - If you want to handle errors gracefully, set `onAPIError.errorURL` in your Better Auth config to a frontend error page [[source](https://github.com/better-auth/better-auth/issues/4694)]. Recent updates to Better Auth and Next.js 16 mainly affect middleware file naming (`proxy.ts` instead of `middleware.ts`) and session cookie handling, but do not directly address this error. The root cause is almost always double-callback or cookie/state misconfiguration. Use browser devtools to confirm the callback sequence and cookie attributes if you need to debug further. <!-- 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/098da9b3-92a5-43a4-acd3-58c553fe9012?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/098da9b3-92a5-43a4-acd3-58c553fe9012?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/098da9b3-92a5-43a4-acd3-58c553fe9012?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/098da9b3-92a5-43a4-acd3-58c553fe9012?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/098da9b3-92a5-43a4-acd3-58c553fe9012?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/098da9b3-92a5-43a4-acd3-58c553fe9012?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/098da9b3-92a5-43a4-acd3-58c553fe9012?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&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/5658)
Author
Owner

@tjazsilovsek commented on GitHub (Oct 29, 2025):

All of that is configured correctly.

  1. Triggering from the client, callback url is user facing.
  2. Yes
  3. Cookies are configured in such a way

So there must be some other issue

@dosu

<!-- gh-comment-id:3464015467 --> @tjazsilovsek commented on GitHub (Oct 29, 2025): All of that is configured correctly. 1. Triggering from the client, callback url is user facing. 2. Yes 3. Cookies are configured in such a way So there must be some other issue [@dosu](https://go.dosu.dev/dosubot)
Author
Owner

@umrashrf commented on GitHub (Nov 2, 2025):

I have added this and the error changed to state_mismatch

advanced: {
    defaultCookieAttributes: {
        sameSite: "none",
        secure: true,
        httpOnly: true,
    },
    crossSubDomainCookies: {
        enabled: true,
        domain: "http://localhost",
    },
},
Image
<!-- gh-comment-id:3478382613 --> @umrashrf commented on GitHub (Nov 2, 2025): I have added this and the error changed to `state_mismatch` ``` advanced: { defaultCookieAttributes: { sameSite: "none", secure: true, httpOnly: true, }, crossSubDomainCookies: { enabled: true, domain: "http://localhost", }, }, ``` <img width="491" height="457" alt="Image" src="https://github.com/user-attachments/assets/c747f3c0-c18a-471b-9b49-44807480480c" />
Author
Owner

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

Based on your description, it seems the upgrade to Next.js 16 and the custom cookie settings are causing the OAuth callback to be triggered twice. The initial “please_restart_the_process” error appeared because the callback was fired twice, and after adding your custom advanced cookie settings the error changed to “state_mismatch,” which usually indicates that the OAuth state returned by the provider doesn’t match the one stored in your cookies.

Next steps to troubleshoot:

  1. Verify your cookie settings. In your advanced configuration, make sure that the cookie domain is set properly without including the protocol. For example, instead of using "http://localhost" for crossSubDomainCookies.domain, try setting it to just "localhost" (or your actual domain in production) so that both the state saved and the state returned are compared correctly [1].

  2. Double-check the consistency of your cookie attributes (sameSite, secure, httpOnly) between the OAuth request and the callback. Inconsistent settings might cause the state to be lost or altered between requests—for instance, securing the cookies only in production environments might be necessary if testing on localhost [1].

  3. Add logging around your OAuth callback to confirm if it’s indeed being triggered twice. If you identify that the callback function inadvertently fires an extra time, adjust your logic (or middleware) to only process the first successful invocation.

  4. If the issue persists, especially with Next.js 16 involved, confirm there are no changes in the framework’s request handling or routing affecting cookies. This might point to an incompatibility or a need for a minor update in Better Auth’s integration with Next.js [1].

These steps should help narrow down the cause of your OAuth state mismatch error. Please update the configuration and share any additional logs if further troubleshooting is needed.

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3478382784 --> @better-auth-agent[bot] commented on GitHub (Nov 2, 2025): Based on your description, it seems the upgrade to Next.js 16 and the custom cookie settings are causing the OAuth callback to be triggered twice. The initial “please_restart_the_process” error appeared because the callback was fired twice, and after adding your custom advanced cookie settings the error changed to “state_mismatch,” which usually indicates that the OAuth state returned by the provider doesn’t match the one stored in your cookies. Next steps to troubleshoot: 1. Verify your cookie settings. In your advanced configuration, make sure that the cookie domain is set properly without including the protocol. For example, instead of using "http://localhost" for crossSubDomainCookies.domain, try setting it to just "localhost" (or your actual domain in production) so that both the state saved and the state returned are compared correctly [[1]](https://github.com/better-auth/better-auth/issues/5658). 2. Double-check the consistency of your cookie attributes (sameSite, secure, httpOnly) between the OAuth request and the callback. Inconsistent settings might cause the state to be lost or altered between requests—for instance, securing the cookies only in production environments might be necessary if testing on localhost [[1]](https://github.com/better-auth/better-auth/issues/5658). 3. Add logging around your OAuth callback to confirm if it’s indeed being triggered twice. If you identify that the callback function inadvertently fires an extra time, adjust your logic (or middleware) to only process the first successful invocation. 4. If the issue persists, especially with Next.js 16 involved, confirm there are no changes in the framework’s request handling or routing affecting cookies. This might point to an incompatibility or a need for a minor update in Better Auth’s integration with Next.js [[1]](https://github.com/better-auth/better-auth/issues/5658). These steps should help narrow down the cause of your OAuth state mismatch error. Please update the configuration and share any additional logs if further troubleshooting is needed. <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

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

Based on your description, the “please_restart_the_process” error was originally caused by the callback being triggered twice. Now that you’re seeing a “state_mismatch” error after updating the cookie configuration, it suggests that the OAuth state parameter isn’t matching what’s stored on your end. Here are some troubleshooting steps:

  1. Verify your cookie settings. The “state_mismatch” indicates that the OAuth state token (stored in a cookie) isn’t being correctly maintained between requests. In your current configuration, the cross-subdomain cookies are enabled with a domain value of "http://localhost". Since cookie domains should not include a protocol, try removing the “http://” so that the domain is simply "localhost". This step can help ensure that the cookie is set and sent consistently [1].

  2. Review your sameSite and secure attributes. For a development environment on localhost, you might try temporarily setting sameSite to “lax” (or even “strict”) and secure to false (if you’re not using HTTPS) to rule out mismatches in how cookies are sent [1], [2].

  3. Clear any stale cookies in your development browser. If your state cookie was set with previous (or conflicting) settings, it could lead to mismatches between the stored state and the state returned from Google.

  4. Double-check that Next.js 16 hasn’t introduced any behavior changes affecting where or how cookies are read. Since your setup worked fine before upgrading, reviewing the Next.js cookie or routing changes (or reverting your advanced cookie configurations temporarily) might isolate the issue.

  5. If possible, test your OAuth flow without the crossSubDomainCookies config enabled. This can help narrow down whether the issue is solely due to the custom cookie settings.

Following these steps should help resolve the “state_mismatch” error by ensuring your OAuth state is stored and retrieved consistently across the authentication flow [1], [2].

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3478383130 --> @better-auth-agent[bot] commented on GitHub (Nov 2, 2025): Based on your description, the “please_restart_the_process” error was originally caused by the callback being triggered twice. Now that you’re seeing a “state_mismatch” error after updating the cookie configuration, it suggests that the OAuth state parameter isn’t matching what’s stored on your end. Here are some troubleshooting steps: 1. Verify your cookie settings. The “state_mismatch” indicates that the OAuth state token (stored in a cookie) isn’t being correctly maintained between requests. In your current configuration, the cross-subdomain cookies are enabled with a domain value of "http://localhost". Since cookie domains should not include a protocol, try removing the “http://” so that the domain is simply "localhost". This step can help ensure that the cookie is set and sent consistently [[1]](https://github.com/better-auth/better-auth/issues/5658). 2. Review your sameSite and secure attributes. For a development environment on localhost, you might try temporarily setting sameSite to “lax” (or even “strict”) and secure to false (if you’re not using HTTPS) to rule out mismatches in how cookies are sent [[1]](https://github.com/better-auth/better-auth/issues/5658), [[2]](https://github.com/better-auth/better-auth/issues/4386). 3. Clear any stale cookies in your development browser. If your state cookie was set with previous (or conflicting) settings, it could lead to mismatches between the stored state and the state returned from Google. 4. Double-check that Next.js 16 hasn’t introduced any behavior changes affecting where or how cookies are read. Since your setup worked fine before upgrading, reviewing the Next.js cookie or routing changes (or reverting your advanced cookie configurations temporarily) might isolate the issue. 5. If possible, test your OAuth flow without the crossSubDomainCookies config enabled. This can help narrow down whether the issue is solely due to the custom cookie settings. Following these steps should help resolve the “state_mismatch” error by ensuring your OAuth state is stored and retrieved consistently across the authentication flow [[1]](https://github.com/better-auth/better-auth/issues/5658), [[2]](https://github.com/better-auth/better-auth/issues/4386). <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@himself65 commented on GitHub (Nov 13, 2025):

I have added this and the error changed to state_mismatch

advanced: {
    defaultCookieAttributes: {
        sameSite: "none",
        secure: true,
        httpOnly: true,
    },
    crossSubDomainCookies: {
        enabled: true,
        domain: "http://localhost",
    },
},
Image

Please see https://canary.better-auth.com/docs/errors/state_mismatch

<!-- gh-comment-id:3529452485 --> @himself65 commented on GitHub (Nov 13, 2025): > I have added this and the error changed to `state_mismatch` > > ``` > advanced: { > defaultCookieAttributes: { > sameSite: "none", > secure: true, > httpOnly: true, > }, > crossSubDomainCookies: { > enabled: true, > domain: "http://localhost", > }, > }, > ``` > > <img alt="Image" width="491" height="457" src="https://private-user-images.githubusercontent.com/652326/508752741-c747f3c0-c18a-471b-9b49-44807480480c.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NjMwNjM1NDMsIm5iZiI6MTc2MzA2MzI0MywicGF0aCI6Ii82NTIzMjYvNTA4NzUyNzQxLWM3NDdmM2MwLWMxOGEtNDcxYi05YjQ5LTQ0ODA3NDgwNDgwYy5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUxMTEzJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MTExM1QxOTQ3MjNaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT0zOTgzOWZkNmJmZjFiYzM3Y2E4ZWVmOTQ5ODIxZjE3MTE0OGI0NjQ4ZTIwYmE3Y2FhM2M0Y2FkZGZiZTEzYjlkJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.677WQ9-T4AHwN8xg0vGLFPoPZ8UuyqdKS_rdxCjpw3k"> Please see https://canary.better-auth.com/docs/errors/state_mismatch
Author
Owner

@mfyuu commented on GitHub (Nov 17, 2025):

If you're getting an error when trying to sign in with Server Functions, you might be able to fix it by adding a plugin.

see: https://www.better-auth.com/docs/integrations/next#server-action-cookies

import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";

export const auth = betterAuth({
	socialProviders: {
		google: {
			clientId: env.GOOGLE_CLIENT_ID,
			clientSecret: env.GOOGLE_CLIENT_SECRET,
		},
	},
	// You’ll need this plugin to use Server Functions.
	plugins: [nextCookies()],
});
<!-- gh-comment-id:3540076809 --> @mfyuu commented on GitHub (Nov 17, 2025): If you're getting an error when trying to sign in with `Server Functions`, you might be able to fix it by adding a plugin. see: https://www.better-auth.com/docs/integrations/next#server-action-cookies ```ts import { betterAuth } from "better-auth"; import { nextCookies } from "better-auth/next-js"; export const auth = betterAuth({ socialProviders: { google: { clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }, }, // You’ll need this plugin to use Server Functions. plugins: [nextCookies()], }); ```
Author
Owner

@dosubot[bot] commented on GitHub (Feb 16, 2026):

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

Issue Summary

  • You reported an OAuth login error after upgrading to Next.js 16, where the callback fires twice causing a "please_restart_process" error, though sign-in eventually succeeds.
  • The root cause was identified as double OAuth callbacks or misconfigured cookies and state handling.
  • Troubleshooting involved verifying callback URLs, cookie domain settings (removing protocols), and cookie attributes.
  • I recommended adding the nextCookies plugin for Server Functions in Next.js 16 to properly handle cookies and prevent state mismatches.
  • The issue was resolved by applying these fixes to ensure correct OAuth flow and cookie management.

Next Steps

  • Please confirm if this issue is still relevant with the latest version of better-auth; if so, you can keep the discussion open by commenting here.
  • Otherwise, this issue will be automatically closed in 7 days.

Thank you for your understanding and contribution!

<!-- gh-comment-id:3909323576 --> @dosubot[bot] commented on GitHub (Feb 16, 2026): Hi, @horvatz. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog and am marking this issue as stale. **Issue Summary** - You reported an OAuth login error after upgrading to Next.js 16, where the callback fires twice causing a "please_restart_process" error, though sign-in eventually succeeds. - The root cause was identified as double OAuth callbacks or misconfigured cookies and state handling. - Troubleshooting involved verifying callback URLs, cookie domain settings (removing protocols), and cookie attributes. - I recommended adding the nextCookies plugin for Server Functions in Next.js 16 to properly handle cookies and prevent state mismatches. - The issue was resolved by applying these fixes to ensure correct OAuth flow and cookie management. **Next Steps** - Please confirm if this issue is still relevant with the latest version of better-auth; if so, you can keep the discussion open by commenting here. - Otherwise, this issue will be automatically closed in 7 days. Thank you for your understanding and contribution!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#18946