Common Auth Domain for Multiple Hosts failing on Social Login with "Error Code: state_mismatch"
I am building an application which will host multiple subdomains. This application allows communities to register their site and login via the central authentication system:
So, for instance:
Central Site: domain.com
Other Site: bobs-community.com
Another Site: freds-community.com
I believe I have CORS figured out, having set trustedOrigins to a function that validates the host against currently registered sites. However, on login I get a "Error Code: state_mismatch" error after the login has returned from a social provider.
Any tips? Happy to provide more information as required.
88 Replies
@Better Auth
Hi there! I noticed you mentioned me—how can I help you with Better Auth today?
Many community members ask questions about common Discord-related features in Better Auth. For instance, some have asked about:
• The new consent option for Discord authentication (added in our recent update) to reduce repeated authorization prompts [1].
• Configuring Discord OAuth without the email scope to address privacy concerns [2].
• Specifying bot permissions via the Discord provider using the new permissions parameter (as enhanced in our updates) [3], [4].
• Troubleshooting issues such as state mismatch errors during Discord login [16] or updating user profile images upon login [21].
Which of these topics or any other aspects of Better Auth are you curious about? Let me know how I can assist further!
Sources:
[1] feat(discord): add consent as an option
[2] feat: Discord Oauth without the email scope
[3] feat: add Discord bot permissions parameter support
[4] feat(discord): allow specification of permissions
[16] Discord Provider throwing
state_mismatch error every time in latest versions
[21] Updating Discord image everytime the user logs in.
— Better Auth is powered by https://clarm.comGitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

GitHub
Discord Provider throwing
state_mismatch error every time in late...Is this suited for github? Yes, this is suited for github To Reproduce Set up a new, or use an existing Better Auth project using the latest version Setup your Discord provider according to the doc...
@Better Auth I am attempting to use one domain for authentication for multiple other domains. When the callback returns from discord, I am getting the error state_mismatch.
It looks like you’re hitting the classic state mismatch issue when trying to use a centralized authentication domain across multiple other domains with Discord. The state mismatch error often occurs when the state cookie isn’t correctly sent back during the OAuth flow. In your case this could be due to the cookie’s domain settings not matching between your auth domain and your client domains.
A couple of points to consider:
1. In one reported case with the Discord provider [1], users experienced the state_mismatch error in version 1.3.24, and downgrading to version 1.3.0 resolved it. If you aren’t already on the most appropriate version, you might want to try that as a temporary workaround.
2. When using a single authenticator domain for multiple domains, it’s important to set up your cookie configuration so that the state cookie is available when the callback is received. You could look into using or verifying settings like cross-subdomain cookie options or configuring your default cookie attributes (for example, setting the correct “domain” value) so that cookies are shared or correctly scoped across your domains (see a related discussion in Document 6 [6]).
Could you share a bit about how you’ve configured your cookie domain or your trustedOrigins? That extra detail could help pinpoint the issue further.
Sources:
[1] Discord Provider throwing
state_mismatch error every time in latest versions
[6] Automatically Set Cookie Domain from callbackURL (if in trustedOrigins)
— Better Auth is powered by https://clarm.comGitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
Discord Provider throwing
state_mismatch error every time in late...Is this suited for github? Yes, this is suited for github To Reproduce Set up a new, or use an existing Better Auth project using the latest version Setup your Discord provider according to the doc...
GitHub
Automatically Set Cookie Domain from callbackURL (if in trustedOrig...
Is this suited for github? Yes, this is suited for github Is your feature request related to a problem? Please describe. Currently, better-auth requires manually setting crossSubDomainCookies.domai...
@Better Auth How should I setup cookies for using a centralized authentication domain across multiple other domains?
When using a centralized authentication domain with Better Auth, you have a couple of options:
1. If your environments can be arranged as subdomains (for example, having auth.example.com, app.example.com, etc.), you can configure Better Auth to share cookies by enabling cross‐subdomain support. In your auth configuration, set the crossSubDomainCookies option to true and choose the appropriate domain (e.g., ".example.com"). This approach allows cookies to be shared seamlessly across subdomains [7].
2. If you need to work across completely different top-level domains (a true cross-domain scenario), you’ll have to enable advanced cross-origin cookie support. In this case, configure the advanced.crossOriginCookies option, which sets the cookies with SameSite set to "none" and forces them to be Secure. Make sure you also add all your target domains to the trustedOrigins list so that each request’s Origin is validated by Better Auth [10][4]. Note that modern browsers impose strict controls on cross-domain cookies, so this setup might require additional workarounds like using proxies or token-based authentication in some scenarios.
Which approach aligns with your requirements—managing subdomains or supporting completely separate domains?
Sources:
[4] Security | Better Auth
[7] Cookies | Better Auth
[10] feat: support cross-domain cookie
— Better Auth is powered by https://clarm.com
Security | Better Auth
Better Auth security features.
Cookies | Better Auth
Learn how cookies are used in Better Auth.
GitHub
feat: support cross-domain cookie by HenriqueBragaMoreira · Pull R...
This PR is based on the excellent work done by @RikhiSingh in PR #3030
.
The implementation itself was already correct, but the related documentation contained some inconsistencies.
In this PR I’ve...
@Better Auth advanced.crossOriginCookies does not seem to be available in release 1.3.34. Do I need to update to the current beta?
It looks like the advanced.crossOriginCookies option was introduced in our recent changes [1][2] and may not be available in the 1.3.34 release. To use this new feature (with options like autoSecure and allowLocalhostUnsecure), you'll need to update to the current beta or a later release that includes these changes.
Are you targeting a particular cross-domain setup or scenario? Let me know if you have any more questions or need help with the upgrade!
Sources:
[1] docs: add cross domain cookies solution
[2] feat: support cross-domain cookie
— Better Auth is powered by https://clarm.com
GitHub
docs: add cross domain cookies solution by HenriqueBragaMoreira · ...
Summary by cubic
Add first-class cross-domain cookie support with a new crossOriginCookies option and stricter SameSite=None handling. Updates include docs, tests, and safer defaults to prevent mis...
GitHub
feat: support cross-domain cookie by HenriqueBragaMoreira · Pull R...
This PR is based on the excellent work done by @RikhiSingh in PR #3030
.
The implementation itself was already correct, but the related documentation contained some inconsistencies.
In this PR I’ve...
@Better Auth How do I upgrade to the current beta?
Hi there! To upgrade to the current beta version of Better Auth, you’ll want to update your package dependencies to the beta release. For example, if you're using npm you can run:
If you’re using yarn or pnpm, just replace the command accordingly. Make sure to update both your server and client parts if your project is split, and don’t forget to check if any associated plugins (like the Stripe or organization plugins) require an update as well. It’s also a good idea to review any migration instructions in our documentation or CLI guides to ensure that database schemas or configurations are up-to-date [1], [21].
Are you having a specific issue during the upgrade, or would you like additional details on updating a particular plugin or running migrations after the upgrade?
Sources:
[1] Stripe | Better Auth
[21] CLI | Better Auth
— Better Auth is powered by https://clarm.com
Stripe | Better Auth
Stripe plugin for Better Auth to manage subscriptions and payments.
CLI | Better Auth
Built-in CLI for managing your project.
@Better Auth It looks like this change was reverted in https://github.com/better-auth/better-auth/commit/22b78cfe7223374f80a50409167dbeadc890d416. Was there an issue found with this?
Hi there! I couldn’t find any detailed documentation or issue related to the revert of that specific commit (22b78cfe7223374f80a50409167dbeadc890d416) in our context [1]. It’s possible that the revert was made to address a regression or conflict, but unfortunately there isn’t enough publicly available information in our current documents to clarify the exact reason.
Could you tag @bekacru or @ping__ on Discord so they can provide more insight on this change? Is there anything else you’re curious about regarding our authentication framework or any other practices you're working with?
Sources:
[1] v1.3.13 failed to release
— Better Auth is powered by https://clarm.com
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
v1.3.13 failed to release · Issue #4772 · better-auth/better-auth
To Reproduce https://github.com/better-auth/better-auth/actions/runs/17848983106 Sounds like the commit it not present on main, somehow. @himself65 Current vs. Expected behavior Expected last npm t...
@bekacru @Max I think there is a chance that the crossOriginCookies option may be my solution. However, I see that PR was reverted a few days after it was merged. Is there a chance it will be reintroduced?
If not, can you provide any guidance on how to make a centralized authentication domain work with various external domains?
Note that I should have the trustedOrigins sorted out via a function which retrieves valid domains from the database (caching them or performance).
Apologies for the ping, but better-auth told me to do so! 😄
You should look into the SSO plugin.
Oh interesting, never seen that before! 😂
You're fine to ping me anytime.
You're fine to ping me anytime.
Okie dokie
I will look into that tomorrow and come back if I have more questions. Thanks @Max!
My goal is for all domains hosted on my platform to be able to login via a variety of social providers, and for users to be able to connect their accounts to other social providers.
For instance:
Main Site:
- domain.com
Hosted Sites:
- otherdomain.com
- somethingelse.com
Initial login on any of the sites might be via Discord (or Google, Apple, etc). Then once logged in, I will provide a "connect my accounts" page (on each site) that allows other social providers to be connected (i.e. whatever they didn't login to originally).
@Max Will the SSO plugin allow for this implementation?
For a little more complexity, site will also be accessible via subdomain.domain.com on the main site domain. However, I figure that once I get cross domain authentication working, the subdomains will work too.
yeah
That's beautiful. I can't wait to try it out tomorrow!!
Thanks again
@Better Auth How do I use the SSO plugin to create a centralized authentication site which allows login via various social providers from multiple other domains that are a part of my application. Can you provide me with a walkthrough for implementing this?
Here's a walkthrough based on what Better Auth supports for SSO:
1. Set up a centralized SSO server:
• Configure your Better Auth instance with the SSO plugin on a dedicated domain. In your auth configuration (e.g., auth.ts), include the SSO plugin and define your social providers there. This site will act as the identity provider for your other domains [2].
• For example, register each social provider (like Google, GitHub, etc.) using the SSO plugin’s provider registration endpoints. The provider configuration automatically generates the correct redirect URLs (e.g. /api/auth/sso/callback/{providerId}) [2]. 2. Register your providers and tenants:
• Use the API endpoint (registerSSOProvider) to register each SSO provider with its associated configuration details, such as providerId, issuer, domain, and callback URLs. This lets you link the provider configuration to specific tenant domains. You can also optionally enable whitelabel or custom CNAME redirection by configuring options like useProviderDomain if needed [1], [2].
3. Configure client applications:
• On each client application (even if they run under different domains), call signIn.sso using the auth client. You can specify the provider explicitly or use email/domain matching to determine which provider to use. For instance, calling authClient.signIn.sso({ provider: "google", callbackURL: "/dashboard" }) triggers the SSO flow with that provider [2].
• Make sure that the client apps are set to redirect back to your centralized SSO server’s callback endpoint when the authentication process is complete. If using cookies, check the
• Configure your Better Auth instance with the SSO plugin on a dedicated domain. In your auth configuration (e.g., auth.ts), include the SSO plugin and define your social providers there. This site will act as the identity provider for your other domains [2].
• For example, register each social provider (like Google, GitHub, etc.) using the SSO plugin’s provider registration endpoints. The provider configuration automatically generates the correct redirect URLs (e.g. /api/auth/sso/callback/{providerId}) [2]. 2. Register your providers and tenants:
• Use the API endpoint (registerSSOProvider) to register each SSO provider with its associated configuration details, such as providerId, issuer, domain, and callback URLs. This lets you link the provider configuration to specific tenant domains. You can also optionally enable whitelabel or custom CNAME redirection by configuring options like useProviderDomain if needed [1], [2].
3. Configure client applications:
• On each client application (even if they run under different domains), call signIn.sso using the auth client. You can specify the provider explicitly or use email/domain matching to determine which provider to use. For instance, calling authClient.signIn.sso({ provider: "google", callbackURL: "/dashboard" }) triggers the SSO flow with that provider [2].
• Make sure that the client apps are set to redirect back to your centralized SSO server’s callback endpoint when the authentication process is complete. If using cookies, check the
cross-domain settings (e.g. via crossOriginCookies) so that session data and the last login method propagate correctly [6].
4. Handle the callback flow:
• Once a user authenticates on the centralized SSO site, Better Auth’s SSO plugin directs the user back to the specified client callback URL.
• Optionally, if you have multiple applications, you can follow the architecture pattern similar to how Google’s accounts work, where the SSO server verifies the authentication and then issues a token that the client application can validate [7]. This centralized approach lets you leverage multiple social providers while keeping the sign-in flow consistent across all domains in your application. Does this address your setup needs, or would you like more details on configuring cross-domain sessions and cookie settings? Sources: [1] feat(sso): Multi Tenant - use the provider domain for redirect and tokenResponse [2] Single Sign-On (SSO) | Better Auth [6] Last Login Method | Better Auth [7] Help with SSO Authentication for Multiple Applications, Single Account (Similar to Google Accounts) — Better Auth is powered by https://clarm.com
• Once a user authenticates on the centralized SSO site, Better Auth’s SSO plugin directs the user back to the specified client callback URL.
• Optionally, if you have multiple applications, you can follow the architecture pattern similar to how Google’s accounts work, where the SSO server verifies the authentication and then issues a token that the client application can validate [7]. This centralized approach lets you leverage multiple social providers while keeping the sign-in flow consistent across all domains in your application. Does this address your setup needs, or would you like more details on configuring cross-domain sessions and cookie settings? Sources: [1] feat(sso): Multi Tenant - use the provider domain for redirect and tokenResponse [2] Single Sign-On (SSO) | Better Auth [6] Last Login Method | Better Auth [7] Help with SSO Authentication for Multiple Applications, Single Account (Similar to Google Accounts) — Better Auth is powered by https://clarm.com
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
feat(sso): Multi Tenant - use the provider domain for redirect and ...
Feature for SSO Plugin
Optional use of provider (authorization) domain for redirect and token response endpoints to support white‑label / custom CNAME auth domains.
Problem Currently the library al...
Single Sign-On (SSO) | Better Auth
Integrate Single Sign-On (SSO) with your application.
Last Login Method | Better Auth
Track and display the last authentication method used by users
@Max Is that a pretty reasonable set of instructions from the bot?
@Better Auth Can you give me an example of how to configure my google and discord social providers in my sso plugin on my better auth instance?
Below is an example of how you can configure Google and Discord as social providers while also using the SSO plugin in your Better Auth instance. Note that you define your OAuth providers under the socialProviders key (which is used for native sign‐on flows) and then add the SSO plugin to your plugins array. For example:
In this setup, the socialProviders configuration (see [1], [4]) handles the individual OAuth settings for each provider, while the SSO plugin (see [3]) ensures that the SSO-specific endpoints and logic are available.
Does this help answer your question, or would you like more details on any part of the configuration?
Sources:
[1] Options | Better Auth
[3] Single Sign-On (SSO) | Better Auth
[4] OAuth | Better Auth
— Better Auth is powered by https://clarm.com
Options | Better Auth
Better Auth configuration options reference.
Single Sign-On (SSO) | Better Auth
Integrate Single Sign-On (SSO) with your application.
@Better Auth Can you provide me with an example registerSSOProvider request for registering discord as an SSO provider?
Below is an example using our OIDC configuration (as shown in Document 1) to register Discord as an SSO provider. Note that you’ll need to supply your own client credentials and adjust endpoints if necessary:
In this example, the configuration mirrors our OIDC provider setup from Document 1. We’re specifying the Discord endpoints and mapping the received fields (such as Discord’s “id” and “username”) to our internal user model. Feel free to tweak the mapping and pkce settings based on your specific needs.
Does this example cover what you were looking for, or would you like more details on handling additional Discord-specific nuances?
— Better Auth is powered by https://clarm.com
@Better Auth Why do I need to provide the clientId and clientSecret when they are already provided in my better auth configuration?
Better Auth requires that each social provider's configuration explicitly includes its own clientId and clientSecret. This design ensures that each provider’s OAuth flow is handled with the proper, validated credentials rather than relying on a global fallback. In other words, even if you have set these values in your overall auth configuration, each provider (like Google or GitHub) needs to securely have its own clientId/clientSecret provided so that type safety and the expected OAuth flow are maintained [3], [10].
Are you configuring a specific provider like Google or GitHub, or is there any other part of the setup you need help with?
Sources:
[3] OAuth | Better Auth
[10] fix: set clientId in ProviderOptions to
unknown by default
— Better Auth is powered by https://clarm.comGitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

OAuth | Better Auth
How Better Auth handles OAuth
GitHub
fix: set clientId in ProviderOptions to
unknown by default by him...Fixes: https://github.com/better-auth/better-auth/pull/4583/files#r2342548852
Summary by cubic
Make clientId in ProviderOptions optional and typed as unknown. Require a string clientId in each so...
@Better Auth Can you provide me with an example registerSSOProvider request for registering Google as an SSO provider?
Below is an example of how you might use the registerSSOProvider endpoint to register Google as an OIDC provider. This example follows the guidelines from the SSO documentation for Better Auth [4]:
This sample request demonstrates setting up Google as an SSO provider by specifying the issuer and a unique providerId [4]. Adjust or expand the configuration based on your environment and specific requirements.
Does this help clarify your setup, or do you have any further questions about configuring SSO providers for Better Auth?
Sources:
[4] Single Sign-On (SSO) | Better Auth
— Better Auth is powered by https://clarm.com
Single Sign-On (SSO) | Better Auth
Integrate Single Sign-On (SSO) with your application.
@Better Auth Can you provide me with an example registerSSOProvider request in JSON for registering Google as an SSO provider?
Below is an example JSON request formatted for registering Google as an SSO provider using Better Auth’s OIDC configuration. This example is based on our documentation that outlines the fields required for OIDC SSO providers [2] and on the recent work for pre-configured SSO providers [1]:
This JSON registers Google as an OIDC provider. It uses the discovery endpoint to automatically fetch necessary configuration details, and it includes a mapping to translate Google’s user attributes to your internal fields [2]. The format is similar to examples used for configuring pre-defined SSO providers during initialization [1].
Does this example meet your needs, or would you like more details on any specific configuration options?
Sources:
[1] WIP: feat(sso): add support for pre-configured SSO providers during initilization
[2] Single Sign-On (SSO) | Better Auth
— Better Auth is powered by https://clarm.com
Single Sign-On (SSO) | Better Auth
Integrate Single Sign-On (SSO) with your application.
GitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

GitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

GitHub
WIP: feat(sso): add support for pre-configured SSO providers during...
Description
This PR adds support for pre-configured SSO providers during initialization.
Instead of always relying on registerSSOProvider (which requires a logged-in session and persists providers ...
@Better Auth I am getting a state_mismatch error when using SSO and logging in from an application hosted on a separate domain. I am using Discord as my SSO provider.
Hi there! The state_mismatch error generally means that the state value stored in your cookie during the OAuth flow isn’t matching the state returned by Discord. In your case—since your application is hosted on a separate domain—it’s important to double-check two things:
1. Ensure that your Discord callback URL exactly matches both your Discord Developer Portal setup and your Better Auth configuration. Any unseen discrepancies (including subdomain differences) can lead to state mismatches [1].
2. Verify that your cookie settings (like the cookie domain or prefix, if you’re using advanced configurations) properly support cross-domain authentication. When your client and callback are on different domains, the cookie might not carry over correctly between requests. Some users have noticed that downgrading to version 1.3.0 resolved similar issues, hinting that there might be a regression or a configuration nuance in later versions [1].
Have you reviewed your cookie configuration and tried testing with version 1.3.0 to see if that resolves the issue? Let me know if you need further assistance or if there are other specific configuration details you’re working with!
Sources:
[1] Discord Provider throwing
state_mismatch error every time in latest versions
— Better Auth is powered by https://clarm.comGitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
Discord Provider throwing
state_mismatch error every time in late...Is this suited for github? Yes, this is suited for github To Reproduce Set up a new, or use an existing Better Auth project using the latest version Setup your Discord provider according to the doc...
@Ping I got SSO working today for my main domain. However, when I try to login from another domain, I get a state_mismatch. Any tips?
@Better Auth I was using Better Auth in MERN stack project for Google account based Authentication, it works perfectly locally but on deployment of the frontend on Vercel and the backend on Render, I get state mismatch error. I checked the Google Client authorised URIs, the .env on Render and Vercel, there is nothing wrong with it. Can you help me?\

It sounds like the state mismatch error in production is likely related to how the temporary PKCE data (the state and code challenge) is being stored and validated. In local development the cookies are issued on localhost, but when deploying on different origins (Vercel for the frontend and Render for the backend) the cookie settings (especially SameSite and Secure flags) may not be applying as expected. This causes Better Auth to fail retrieving the stored state during the OAuth callback, resulting in a state mismatch error [1], [2].
A few things to check in your production setup:
• Ensure that your Better Auth configuration includes proper cookie settings for production. Explicitly configuring SameSite (usually set to "None" along with Secure) can help maintain persistence across the different domains.
• Verify that your production base URLs, trusted origins, and callback URIs are correctly set up so that the cookies get attached and retrieved correctly between your frontend and backend.
• If you’re using any proxy plugins (like oAuthProxy), note that there have been reports of the automatic handling of the state cookie check not working as expected in non-local environments. Double-check that this isn’t interfering with the OAuth flow.
Could you let me know if you’ve set any explicit cookie configuration options in your Better Auth setup for production? If not, trying that might resolve the issue. Also, have you checked whether your deployed domains are being properly whitelisted in your configuration?
Sources:
[1] oAuthProxy plugin doesn't work
[2] OAuth state mismatch error with oAuthProxy plugin on Vercel preview deployments despite skipStateCookieCheck configuration
— Better Auth is powered by https://clarm.com
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
oAuthProxy plugin doesn't work · Issue #4953 · better-auth/better...
Is this suited for github? Yes, this is suited for github To Reproduce When initializing auth flow with oAuthProxy plugin enabled from localhost or any preview environment hosted in Vercel (random ...
GitHub
OAuth state mismatch error with oAuthProxy plugin on Vercel preview...
Is this suited for github? Yes, this is suited for github To Reproduce Set up Better Auth with oAuthProxy plugin for Vercel deployments Configure GitHub OAuth provider with production callback URL ...
@Better Auth this is my config
Hi there! Your configuration looks well-structured and follows our recommended practices for setting up Better Auth on both the backend and frontend. A few things to note:
• Your backend config uses the mongodbAdapter with custom secure cookie settings and trusted origins, which is similar to the patterns we show in our documentation [3]. Just make sure your environment variables (like SERVER, CLIENT, GOOGLE_CLIENT_ID, etc.) are set correctly in your production environment.
• The session settings (expiresIn, updateAge, and cookieCache with a defined maxAge) look properly configured to handle user sessions reliably. Defining secure cookie attributes (sameSite "none" and secure true) under the advanced settings is a great way to ensure your cookies work as expected across origins [15].
• On the frontend, you’re correctly including credentials in your fetchOptions and using createAuthClient from the react client—this aligns with our best practices for client configuration [15].
Everything appears to be in order. Are you encountering any specific issues with sign-ins, session persistence, or redirections? Let me know what challenges you're facing so I can help further!
Sources:
[3] Options | Better Auth
[15] Client | Better Auth
— Better Auth is powered by https://clarm.com
Options | Better Auth
Better Auth configuration options reference.
Client | Better Auth
Better Auth client library for authentication.
That's kind of expected, the main purpose is to ensure you start and end on the same domain as a security measure. I believe you can disable this auth config
advanced.oauthConfig.skipStateCookieCheckI'll give this a try tomorrow if I have time
Without using this parameter, how would my solution even work, with or without the SSO plugin?
And if I use this parameter to disable this check, what security vulnerabilities am I introducing?
Alas, I am still getting the state_mismatch error with this enabled.
@Max Would you or another member of the better-auth staff be interested in some paid work to help me sort this out? I have a feeling there is something more fundamentally wrong I am doing. I would love to find someone here I could pay to help me get this working.
Let me post that in #job-posting
no im sure we can find it out without spending money
let me go check our code, since the state mismatch thing is very new even I'm not super familiar with it
Can you share your auth config?
Yep, for the server side, right?
And on the client side:
When I get this working I plan to do a proper write-up as to how to implement this. 😄
Again, the requirement is:
Central API/Auth Site on Domain:
- domain.com/api
- domain.com/auth
There will be logins and API requests coming from that domain for the main platform site:
- domain.com (and paths)
Users of the platform will create their community on the site that can be available on a subdomain and/or a hosted domain.
For instance:
- captbunzo.domain.com
- captbunzo.net
Both of these two should authenticate via domain.com/auth.
The goal is to have a centralized authentication domain which allows users to login via social providers and then get redirected back to the client sites (captbunzo.domain.com or captbunzo.net) once authentication is complete. Then requests to the api (domain.com/api) should be authorized by the auth with domain.com/auth.
My preference would be for sessions to be distinct for the site that a user is visiting:
1. domain.com
2. captbunzo.domain.com
3. captbunzo.net
I want to be able to register ONCE for the platform with Google, Discord, Apple, Facebook, etc for Oauth and not to have to set it up for every hosted community.
your config looks right, you shouldn't be getting the state mismatch error after enabling
skipStateCookieCheck, I wonder if it's a version issue. What version are you on?1.3.34
I think it's an error on Better-Auth side
Can you try any beta version?
That would be relieving 😄
I have been beating my head against this for a month!
Any particular version suggested?
I think I was going to try a beta version, but ran into an issue with my database provider (@hedystia/better-auth-typeorm) not being built on the beta and everything blew up.
I might have to build my own copy of it to try the beta, which would be fine.
v1.4.0-beta.20 maybe?
oh interesting
yeah if you can
otherwise I'll try to push something to latest, but not sure if it can be release today
Ok. Let's see how this goes. I merged my backend (elysia with bun) and frontend (tanstack start/router/query with pnpm) into a pnpm monorepo recently and have been having some issue with getting all of it cooperating nicely.
I just started learning full-stack stuff about 4-5 months ago
Can I ask a basic question? Is it acceptable to just update the version in the package.json files to v1.4.0-beta.20 and then do a "bun install" and "pnpm install" in each of the backend and frontend projects?
what do you mean acceptable, what would be the issue?
Lol, I mean is that the right way to change and test the version.
Or should I be using some bun/pnpm update or something command.
😄
Trying this
updating package.json or just using
bun install pacakge-name@some-version should both work the sameTa
https://komunifi.dev <- this still works on the beta
https://captbunzo.komunifi.dev/
These are my live domains for dev
ah
Holy moly, the state mismatch error did not return with the beta. But my app did not find the session. Looks from the frontend that it is not actually logged in.
That might be an error in my code as I never got past state_mismatch before.
Notably, this did not happen, so maybe that was a mistake on my part or with a previous beta I tried. Dunno.
@Max You are welcome to click about on things.
I tried logging in to captbunzo.net and got a new session in my session table, but also not being found by my frontend
@bekacru might be able to help you out
can you give me an overview your setup? do you have your backend and frontend running on a differnt domain?
The main platform (for dev) is running on https://komunifi.dev. The platform website will allow users to setup their communities there. My goal also is for that domain to host the backend. So these paths will map to the api and auth part of the api:
https://komunifi.dev/api
https://komunifi.dev/auth
Users will be able to register a community and give it a handle (subdomain). They can also give it a full domain if they have one. Those communities hosted on subdomains or full other domains should authenticate and use the API from the main platform domain.
So subdomain - https://captbunzo.komunifi.dev
And domain - https://captbunzo.net
Should be able to authenticate via https://komunifi.dev (https://komunifi.dev/auth) and then access the api (https://komunifi.dev/api) with the credentials from that login.
Note that the same platform will host communities for multiple users (content creators, influencers, whatever). So there could be https://bobthetrucker.komunifi.dev or https://bobthetrucker.com. When they first register with us, they will immediately be able to start building their site/community using their subdomain and then add a domain if they have one or later.
That's probably a lot more info than you needed. 😄
Does that all make sense @bekacru?
@bekacru sorry to bother you, but can you take a look over at my response and see if you have any thoughts?
The offer also still stands to pay for some time for somebody to help with this. I appreciate all the hard work you do on better-auth!
wait so you want subdomains to share auth or to have their own auth per subdomain?
I tried to read it back but it's a bit confusing
Auth will all be handled by one common domain:
https://komunifi.com/auth
And then all of these web frontends will use that for authentication / authorization.
https://komunifi.com
https://captbunzo.komunifi.com
https://captbunzo.net
Noting that captbunzo (either as the subdomain or as a full other domain) will be any number of other subdomains / domains based on communities that users host with my platform.
@bekacru does that clear things up at all?
there are 2 ways to do it
1. setup proxy so each domain set cookie for itself. basically each domain runs a server that set forwards and set the cookies
2. use localstorage to store tokens (this requires a lot of work around for social signons)
Are there details anywhere for how to do both of the options?
As I work through implementing this, I'm happy to document to benefit others later.
same issue for me
Sorry to be a bother @Max and @bekacru, but any details on how to implement the two options above? Any links maybe?
@Taesu can you work on here providing more details on how to configure proxy for setting cookies in thie scenrio
Thanks!!!
Hello @captbunzo, I’ve read through the conversation, and I have a few questions.
Thanks for your time. What are your questions?
- You mentioned you recently started full-stack development, are you currently building this service from scratch?
- From what I understand, you’re setting up multi-tenancy for each community and assigning subdomains to each again, is this right? 🤔
1. Yes, I am building this service from scratch. I've been working on it for 4-5 months.
2. Subdomains and/or domains
For now, I want to discuss whether assigning entirely separate domains is necessary, since it feels more like a large enterprise setup rather than just subdomains
A community will by default get a subdomain. However, if they have their own domain, they can configure it and use it too.
Yes, providing for our users to be able to configure and use their own domains is a core feature we're offering.
And yes, this is intended to be an enterprise level offering.
Since browser cookies can be set per domain (e.g., .domain.com), implementing a cookie-based auth flow across multiple domains gets quite complex. There is an OAuth proxy plugin that works in dev/preview environments, but it’s designed for development/preview use only.
Fully proxying cookies across multiple TLDs and their subdomains would be very complicated 🤔
Our expectation is to be able to bring on dozens of content creators in the first year, and expand to hundreds in the second.
Some may not have their own domain and just use a subdomain. But when they have a domain, we want them to be able to use it.
But it's possible, correct?
Speaking from my experience doing several indie projects, how about I make a suggestion from a different angle??
The fallback plan is for each domain to host their own auth. But that significantly complicated setup for new domains.
Absolutely
Securing a short, catchy domain and building the multi-tenant service on its subdomains would be advantageous for initial development and brand recognition.
We're doing that, yep
The issue seems to be caused by cookies not being shared across completely different TLDs, which could "technically" be handled with a proxy. However, I think this would be quite complex for initial development, so I wanted to make this suggestion.
But part of our vision is for the platform to be about our users, not about itself. We have good contacts with major creators who are, quite frankly, looking for something better than current offerings.
I appreciate your suggestion.
However....
I've been hearing here for the last month that this is doable. And I've seen a number of people ask about similar capabilities.
If I can get help working this out, I'm quite happy to do the build for this part in an open source project that others can use with better-auth.
I may be fairly new to full stack development, but I've been coding professionally for several decades. So I'm confident that if I can understand the technical details required, I can get it built.
I think it would be a fantastic offering for better-auth users.
I’m suggesting this because building on subdomains first -> adding custom domain support later seems like a leaner way to make the service successful 🙂
From my perspective, here is the core problem
---
Because the domains are completely different, cookies don’t carry over to the user’s original login location during the OAuth callback.
Well, to be fair, I haven't actually been able to get it working with subdomains either.
It should work fully on subdomains. I’ve used Better Auth before, and it worked properly there.
I am building all the core capabilities, regardless of this problem.
Is cookie set on browser??
I'll have to investigate that tomorrow or sometime soon as it's 1:38 am here and I really can't be pulling my laptop back out again 😂
Assuming I get subdomains working, that is a path for further development and a possible lean go live.
However, I'd really like to understand:
1. Can this be done for different TLDs in a secure manner
2. If so, how that would work and what I need to build
I’m asking because there are many potential points of failure.
- Cookies aren’t set at all
- Cookies are set, but the browser can’t read them because the request is server-side
- Whether the state is correctly stored in the verification table during the OAuth flow
Yeah, it's challenging to debug indeed.
I'll turn my attention first to getting subdomains working, since that seems an easier problem to solve.
Actually, if it’s just subdomains, I can support perfectly. I’ve built services like that before.
I’ve never actually built a full enterprise-grade multi-tenant system from scratch, so I can’t guarantee I’m 100% correct for different TLDs.
I don't know if our timezones will align right, but I'll reach out when I can get to this. I think I'll have some time during my lunch break from my day job.
I deeply appreciate all the help from the experts here and love the platform. Switching my backend a couple months back from Express to Elysia and Better Auth was like coming into the modern era it seemed.
This message suggests the full multi-tenant solution with full-time separate domains is possible.
Thank you for your time tonight @Taesu.
I better get to sleep.
good night @captbunzo!
If you share the frameworks you’re using and your basic setup, I can try to help. Leave a message 😁

