[GH-ISSUE #3874] Better auth Dockerized authClient Issues #18379

Closed
opened 2026-04-15 16:50:15 -05:00 by GiteaMirror · 13 comments
Owner

Originally created by @Stuart-wdas on GitHub (Aug 8, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/3874

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Set up a better-auth backend inside a Docker container at http://localhost:3001/api/auth

Set up a frontend Next.js app at http://localhost:3000, using createAuthClient from better-auth/react

Configure both backend and frontend with trustedOrigins that include:

http://localhost:3000

http://wdas-admin-portal-frontend:3000

Try to sign in via sign-in/email from the frontend

Observe CORS failure in browser console:

Response to preflight request doesn't pass access control check: 
The 'Access-Control-Allow-Origin' header has a value 'http://admin-portal-frontend:3000' that is not equal to the supplied origin.

Current vs. Expected behavior

Expected:
Since localhost:3000 is explicitly listed in trustedOrigins, I expect requests from that origin to be allowed and the correct CORS headers (Access-Control-Allow-Origin) to match the request origin.

Actual:
The backend responds with a mismatched Access-Control-Allow-Origin (http://wdas-admin-portal-frontend:3000), even though the request is coming from http://localhost:3000. This causes the browser to block the request.

What version of Better Auth are you using?

1.3.4

Provide environment information

OS: MacOS / Windows (affects both)

Browser: Chrome/Edge (latest)

Using Docker: Yes

Frontend running in browser via localhost:3000 from docker desktop build

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

Backend, Client

Auth config (if applicable)

# BACKEND
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { inferAdditionalFields } from 'better-auth/client/plugins';
import { PrismaClient } from './generated/prisma';

const prisma = new PrismaClient();

export const auth = betterAuth({
  database: prismaAdapter(prisma, {
    provider: 'postgresql',
  }),
  emailAndPassword: {
    enabled: true,
    disableSignUp: false,
    requireEmailVerification: false,
    minPasswordLength: 3,
    maxPasswordLength: 20,
    autoSignIn: true,
  },
  plugins: [
    inferAdditionalFields({
      user: {
        role: {
          type: 'string',
        },
      },
    }),
  ],
  trustedOrigins: [
    'http://admin-portal-frontend:3000',
    'http://localhost:3000',
  ],
});

# FRONTEND

export const authClient = createAuthClient({
  baseURL: 'http://localhost:3001/api/auth',
  basePath: 'http://localhost:3001/api/auth',
  trustedOrigins: [
    'http://localhost:3001',
    'http://admin-portal-backend:3001',
  ],
});

Additional context

This issue happens when using localhost for browser testing.

Using the container name (wdas-admin-portal-frontend) doesn't work from the browser due to DNS limitations.

POST http://admin-portal-backend:3001/api/auth/sign-in/email net::ERR_NAME_NOT_RESOLVE

POST http://admin-portal-backend:3001/api/auth/sign-up/email net::ERR_NAME_NOT_RESOLVE

Using localhost works for network routing, but the CORS check on the server side seems to return the wrong origin header, causing a mismatch.

I suspect better-auth internally chooses a preferred trustedOrigin to return in Access-Control-Allow-Origin, instead of echoing back the request origin. And because of the dockerized nature of the app, the auth config is required to point to the docker container but requests are sent from localhost.

Originally created by @Stuart-wdas on GitHub (Aug 8, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/3874 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce Set up a better-auth backend inside a Docker container at http://localhost:3001/api/auth Set up a frontend Next.js app at http://localhost:3000, using createAuthClient from better-auth/react Configure both backend and frontend with trustedOrigins that include: http://localhost:3000 http://wdas-admin-portal-frontend:3000 Try to sign in via sign-in/email from the frontend Observe CORS failure in browser console: ```Access to fetch at 'http://localhost:3001/api/auth/sign-in/email' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://admin-portal-frontend:3000' that is not equal to the supplied origin. ``` ### Current vs. Expected behavior Expected: Since localhost:3000 is explicitly listed in trustedOrigins, I expect requests from that origin to be allowed and the correct CORS headers (Access-Control-Allow-Origin) to match the request origin. Actual: The backend responds with a mismatched Access-Control-Allow-Origin (http://wdas-admin-portal-frontend:3000), even though the request is coming from http://localhost:3000. This causes the browser to block the request. ### What version of Better Auth are you using? 1.3.4 ### Provide environment information ```bash OS: MacOS / Windows (affects both) Browser: Chrome/Edge (latest) Using Docker: Yes Frontend running in browser via localhost:3000 from docker desktop build ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript # BACKEND import { betterAuth } from 'better-auth'; import { prismaAdapter } from 'better-auth/adapters/prisma'; import { inferAdditionalFields } from 'better-auth/client/plugins'; import { PrismaClient } from './generated/prisma'; const prisma = new PrismaClient(); export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: 'postgresql', }), emailAndPassword: { enabled: true, disableSignUp: false, requireEmailVerification: false, minPasswordLength: 3, maxPasswordLength: 20, autoSignIn: true, }, plugins: [ inferAdditionalFields({ user: { role: { type: 'string', }, }, }), ], trustedOrigins: [ 'http://admin-portal-frontend:3000', 'http://localhost:3000', ], }); # FRONTEND export const authClient = createAuthClient({ baseURL: 'http://localhost:3001/api/auth', basePath: 'http://localhost:3001/api/auth', trustedOrigins: [ 'http://localhost:3001', 'http://admin-portal-backend:3001', ], }); ``` ### Additional context This issue happens when using localhost for browser testing. Using the container name (wdas-admin-portal-frontend) doesn't work from the browser due to DNS limitations. POST http://admin-portal-backend:3001/api/auth/sign-in/email net::ERR_NAME_NOT_RESOLVE POST http://admin-portal-backend:3001/api/auth/sign-up/email net::ERR_NAME_NOT_RESOLVE Using localhost works for network routing, but the CORS check on the server side seems to return the wrong origin header, causing a mismatch. I suspect better-auth internally chooses a preferred trustedOrigin to return in Access-Control-Allow-Origin, instead of echoing back the request origin. And because of the dockerized nature of the app, the auth config is required to point to the docker container but requests are sent from localhost.
GiteaMirror added the lockedbug labels 2026-04-15 16:50:16 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Aug 8, 2025):

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

This CORS error happens because better-auth requires the request's Origin header to exactly match one of the entries in trustedOrigins. In Dockerized setups, the backend may see the origin as a container hostname (like http://wdas-admin-portal-frontend:3000) while your browser uses http://localhost:3000. If the backend responds with a different origin than the browser's request, CORS fails.

better-auth does not pick a "preferred" trustedOrigin; it matches the incoming Origin header against trustedOrigins and echoes it back if it matches. If it doesn't match, it may fall back to the first entry or another, causing the mismatch you see. This is usually due to a misconfiguration or a mismatch between what the browser sends and what the backend expects (source).

Common pitfalls:

  • trustedOrigins must be at the top level of your config, not inside advanced (source).
  • Every possible frontend origin (including http://localhost:3000 and any Docker hostnames) must be listed in trustedOrigins (source).
  • Remove unused or Docker-only hostnames from trustedOrigins if your browser never uses them (source).
  • CORS middleware must run before your auth routes (source).
  • For cross-origin cookies, set sameSite: 'none', secure: true, and use credentials: 'include' in frontend fetches (source).

Troubleshooting checklist:

  1. Double-check that trustedOrigins is at the top level and includes exactly the origins your browser uses (protocol, hostname, and port must all match).
  2. Remove any container hostnames from trustedOrigins if your browser never uses them.
  3. Make sure your frontend is actually sending requests from http://localhost:3000 (check the Origin header in browser devtools).
  4. Restart your backend after changing trustedOrigins.
  5. If you use a reverse proxy or custom networking, ensure it doesn't rewrite or strip the Origin header.

If you follow these steps, better-auth should echo the correct Access-Control-Allow-Origin and CORS should work as expected (source).

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:3166880225 --> @dosubot[bot] commented on GitHub (Aug 8, 2025): <!-- Greeting --> Hi @Stuart-wdas! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This CORS error happens because better-auth requires the request's Origin header to exactly match one of the entries in trustedOrigins. In Dockerized setups, the backend may see the origin as a container hostname (like `http://wdas-admin-portal-frontend:3000`) while your browser uses `http://localhost:3000`. If the backend responds with a different origin than the browser's request, CORS fails. better-auth does not pick a "preferred" trustedOrigin; it matches the incoming Origin header against trustedOrigins and echoes it back if it matches. If it doesn't match, it may fall back to the first entry or another, causing the mismatch you see. This is usually due to a misconfiguration or a mismatch between what the browser sends and what the backend expects ([source](https://github.com/better-auth/better-auth/issues/1585)). Common pitfalls: - trustedOrigins must be at the top level of your config, not inside `advanced` ([source](https://github.com/better-auth/better-auth/issues/1585)). - Every possible frontend origin (including `http://localhost:3000` and any Docker hostnames) must be listed in trustedOrigins ([source](https://github.com/better-auth/better-auth/issues/3743)). - Remove unused or Docker-only hostnames from trustedOrigins if your browser never uses them ([source](https://github.com/better-auth/better-auth/issues/3743)). - CORS middleware must run before your auth routes ([source](https://github.com/better-auth/better-auth/pull/3707)). - For cross-origin cookies, set `sameSite: 'none'`, `secure: true`, and use `credentials: 'include'` in frontend fetches ([source](https://github.com/better-auth/better-auth/issues/3470)). Troubleshooting checklist: 1. Double-check that trustedOrigins is at the top level and includes exactly the origins your browser uses (protocol, hostname, and port must all match). 2. Remove any container hostnames from trustedOrigins if your browser never uses them. 3. Make sure your frontend is actually sending requests from `http://localhost:3000` (check the Origin header in browser devtools). 4. Restart your backend after changing trustedOrigins. 5. If you use a reverse proxy or custom networking, ensure it doesn't rewrite or strip the Origin header. If you follow these steps, better-auth should echo the correct Access-Control-Allow-Origin and CORS should work as expected ([source](https://github.com/better-auth/better-auth/issues/3743)). <!-- 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/5116195e-ab3f-44df-9117-ba54ba4981c1?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/5116195e-ab3f-44df-9117-ba54ba4981c1?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/5116195e-ab3f-44df-9117-ba54ba4981c1?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/5116195e-ab3f-44df-9117-ba54ba4981c1?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/5116195e-ab3f-44df-9117-ba54ba4981c1?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/5116195e-ab3f-44df-9117-ba54ba4981c1?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/5116195e-ab3f-44df-9117-ba54ba4981c1?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/3874)
Author
Owner

@himself65 commented on GitHub (Aug 8, 2025):

Similar to #3743

I'm gonna test it locally since there're many people report this

<!-- gh-comment-id:3167051743 --> @himself65 commented on GitHub (Aug 8, 2025): Similar to #3743 I'm gonna test it locally since there're many people report this
Author
Owner

@himself65 commented on GitHub (Aug 11, 2025):

OK, I think I know what's going on here. You might need to modify the CORS plugin's original value. Idk what server framework you are using, but if you are using hono, please do sth like x => x to allow all origins:

app.use(
  '/api/auth/*',
  cors({
    origin: x => x,
    allowHeaders: ['Content-Type', 'Authorization'],
    allowMethods: ['POST', 'GET', 'OPTIONS'],
    exposeHeaders: ['Content-Length'],
    maxAge: 600,
    credentials: true
  })
)
<!-- gh-comment-id:3174413992 --> @himself65 commented on GitHub (Aug 11, 2025): OK, I think I know what's going on here. You might need to modify the CORS plugin's original value. Idk what server framework you are using, but if you are using `hono`, please do sth like `x => x` to allow all origins: ```ts app.use( '/api/auth/*', cors({ origin: x => x, allowHeaders: ['Content-Type', 'Authorization'], allowMethods: ['POST', 'GET', 'OPTIONS'], exposeHeaders: ['Content-Length'], maxAge: 600, credentials: true }) ) ```
Author
Owner

@lord007tn commented on GitHub (Aug 18, 2025):

as @himself65 said this works with my vue app,
but the same implementation in nextjs is not working and always return Cors error below

login:1 Access to fetch at 'https://api-dev.example.com/api/app/auth/sign-in/social' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
in both apps i use hono with same structure, same config, both servers are in docker

edit: i believe this issue is in better-auth and not in hono, because same server with other requests from browser works, only the better-auth related requests have Cors error

<!-- gh-comment-id:3197680150 --> @lord007tn commented on GitHub (Aug 18, 2025): as @himself65 said this works with my vue app, but the same implementation in nextjs is not working and always return Cors error below ` login:1 Access to fetch at 'https://api-dev.example.com/api/app/auth/sign-in/social' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. ` in both apps i use hono with same structure, same config, both servers are in docker edit: i believe this issue is in better-auth and not in hono, because same server with other requests from browser works, only the better-auth related requests have Cors error
Author
Owner

@himself65 commented on GitHub (Aug 18, 2025):

That's great. Thanks for the comment

<!-- gh-comment-id:3197684628 --> @himself65 commented on GitHub (Aug 18, 2025): That's great. Thanks for the comment
Author
Owner

@himself65 commented on GitHub (Aug 18, 2025):

as @himself65 said this works with my vue app, but the same implementation in nextjs is not working and always return Cors error below

login:1 Access to fetch at 'https://api-dev.example.com/api/app/auth/sign-in/social' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. in both apps i use hono with same structure, same config, both servers are in docker

edit: i believe this issue is in better-auth and not in hono, because same server with other requests from browser works, only the better-auth related requests have Cors error

For next.js, I think there need another way to allow all cors

ref: https://stackoverflow.com/questions/65058598/nextjs-cors-issue

<!-- gh-comment-id:3197752179 --> @himself65 commented on GitHub (Aug 18, 2025): > as [@himself65](https://github.com/himself65) said this works with my vue app, but the same implementation in nextjs is not working and always return Cors error below > > `login:1 Access to fetch at 'https://api-dev.example.com/api/app/auth/sign-in/social' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.` in both apps i use hono with same structure, same config, both servers are in docker > > edit: i believe this issue is in better-auth and not in hono, because same server with other requests from browser works, only the better-auth related requests have Cors error For next.js, I think there need another way to allow all cors ref: https://stackoverflow.com/questions/65058598/nextjs-cors-issue
Author
Owner

@himself65 commented on GitHub (Aug 18, 2025):

Are you using better-auth in Next.js backend? Or just use the client api in Next.js.

I'm thinking how we can make this better

@lord007tn

<!-- gh-comment-id:3197864063 --> @himself65 commented on GitHub (Aug 18, 2025): Are you using better-auth in Next.js backend? Or just use the client api in Next.js. I'm thinking how we can make this better @lord007tn
Author
Owner

@lord007tn commented on GitHub (Aug 18, 2025):

Are you using better-auth in Next.js backend? Or just use the client api in Next.js.

I'm thinking how we can make this better

@lord007tn

just the client on NextJS, my backend is on a separate hosted server

also my server is accepting options and return 204, all other requests that are not auth requests pass normally,

the only issue is with auth requests, i have a global cors that basically do

const corsOptions: Parameters<typeof cors>[0] = {
  origin: (origin) => origin,
  allowHeaders: ['Content-Type', 'Authorization'],
  allowMethods: ['POST', 'GET', 'DELETE', 'PUT', 'PATCH', 'OPTIONS'],
  exposeHeaders: ['Content-Length'],
  maxAge: 600,
  credentials: true,
};
<!-- gh-comment-id:3197871031 --> @lord007tn commented on GitHub (Aug 18, 2025): > Are you using better-auth in Next.js backend? Or just use the client api in Next.js. > > I'm thinking how we can make this better > > [@lord007tn](https://github.com/lord007tn) just the client on NextJS, my backend is on a separate hosted server also my server is accepting options and return 204, all other requests that are not auth requests pass normally, the only issue is with auth requests, i have a global cors that basically do ```ts const corsOptions: Parameters<typeof cors>[0] = { origin: (origin) => origin, allowHeaders: ['Content-Type', 'Authorization'], allowMethods: ['POST', 'GET', 'DELETE', 'PUT', 'PATCH', 'OPTIONS'], exposeHeaders: ['Content-Length'], maxAge: 600, credentials: true, }; ```
Author
Owner

@himself65 commented on GitHub (Aug 18, 2025):

Are you willing to give a reproduction code?

<!-- gh-comment-id:3197897763 --> @himself65 commented on GitHub (Aug 18, 2025): Are you willing to give a reproduction code?
Author
Owner

@lord007tn commented on GitHub (Aug 19, 2025):

@himself65 Sorry, I was doing a reproduction code, and when things started to dissolve, I stopped and fixed it. You can see below how

After a lot of hours of debugging and diving into the inner code of Better Auth, the problem was from the Cloudflare proxied domain :), but some other issues were also happening, like:

  • disappearing cookie because the cookie domain was defaulted to baseURL, and that's my server URL.
  • Authentication in production works, but not when I connect the local frontend to the production domain.
  • Authentication in local env works, but not in production.

I don't know why only the auth requests were blocked, though, but there are some concerns to raise in better-auth. It seems that people who use better-auth mainly use it inside NextJS ( client and server parts ).

The lack of examples and docs about having the server in one place and your frontend in another place ( as subdomains or completely different domains ) caused some kind of ambiguity for me on how to set up the cookies.

And also working with better-auth directly inside NextJS frees you from dealing with CORS stuff ( which is not my case, and anyone willing to use better-auth for complex apps ).

From what I understand, this is what finally works.

// your other config
advanced: {
    crossSubDomainCookies: {
      enabled: true,
      domain: keys().NEXT_PUBLIC_COOKIE_DOMAIN,
    },
    useSecureCookies: process.env.NODE_ENV === 'production',
    defaultCookieAttributes: {
      sameSite: process.env.NODE_ENV === 'production' ? 'none': 'lax',
    },
}

And the key point here was the domain in crossSubDomainCookies, it needs to be ".your-domain", so after authentication, the browsers don't transfer it to what baseURL domain is, because if you don't set it, that's the default behavior mentioned here docs.

PS: also don't forget to add this as env vars so you can control them from the Vercel platform and customize them

I believe this should be automatically handled and accepted if the domain is part of the trustedOrigins as mentioned here https://github.com/better-auth/better-auth/issues/1466

As a person who has always built my own auth, the experience of starting with Better-Auth was seamless. The issue is when you go to production, that's why I believe that having a place in docs for production config with better-auth can set a lot of people on the right path.

I want to mention this also https://github.com/better-auth/better-auth/issues/4038, maybe it's the same issue
as this one also https://github.com/better-auth/better-auth/issues/4052.

Also I want to mention this open source project that uses better auth + fastify + Nextjs: https://github.com/rybbit-io/rybbit

I think having a directory of open source products that use better-auth in production can also be a starting point for people to learn and understand how things work

<!-- gh-comment-id:3198999324 --> @lord007tn commented on GitHub (Aug 19, 2025): @himself65 Sorry, I was doing a reproduction code, and when things started to dissolve, I stopped and fixed it. You can see below how After a lot of hours of debugging and diving into the inner code of Better Auth, the problem was from the Cloudflare proxied domain :), but some other issues were also happening, like: - disappearing cookie because the cookie domain was defaulted to baseURL, and that's my server URL. - Authentication in production works, but not when I connect the local frontend to the production domain. - Authentication in local env works, but not in production. I don't know why only the auth requests were blocked, though, but there are some concerns to raise in better-auth. It seems that people who use better-auth mainly use it inside NextJS ( client and server parts ). The lack of examples and docs about having the server in one place and your frontend in another place ( as subdomains or completely different domains ) caused some kind of ambiguity for me on how to set up the cookies. And also working with better-auth directly inside NextJS frees you from dealing with CORS stuff ( which is not my case, and anyone willing to use better-auth for complex apps ). From what I understand, this is what finally works. ``` ts // your other config advanced: { crossSubDomainCookies: { enabled: true, domain: keys().NEXT_PUBLIC_COOKIE_DOMAIN, }, useSecureCookies: process.env.NODE_ENV === 'production', defaultCookieAttributes: { sameSite: process.env.NODE_ENV === 'production' ? 'none': 'lax', }, } ``` And the key point here was the `domain` in crossSubDomainCookies, it needs to be ".your-domain", so after authentication, the browsers don't transfer it to what `baseURL` domain is, because if you don't set it, that's the default behavior mentioned here [docs](https://www.better-auth.com/docs/concepts/cookies#cross-subdomain-cookies). PS: also don't forget to add this as env vars so you can control them from the Vercel platform and customize them I believe this should be automatically handled and accepted if the domain is part of the `trustedOrigins` as mentioned here https://github.com/better-auth/better-auth/issues/1466 As a person who has always built my own auth, the experience of starting with Better-Auth was seamless. The issue is when you go to production, that's why I believe that having a place in docs for `production config with better-auth` can set a lot of people on the right path. I want to mention this also https://github.com/better-auth/better-auth/issues/4038, maybe it's the same issue as this one also https://github.com/better-auth/better-auth/issues/4052. Also I want to mention this open source project that uses better auth + fastify + Nextjs: https://github.com/rybbit-io/rybbit I think having a directory of open source products that use better-auth in production can also be a starting point for people to learn and understand how things work
Author
Owner

@codersaadi commented on GitHub (Aug 22, 2025):

hey,
@lord007tn
does that also work for cross sites ? two different domains (one Nextjs at vercel , second is Hono sever on a vps or something) . like myadmin.vercel.app (or something , ) frontend and anotherdomain.com (and anotherdomain is the hono server which is serving the better auth url )

the thing i have faced is : cookie disappears after sometime , maybe after cache time.
so it is not persisting across domains.
as long as it is in the cache time (which is 5min) it works .

or this solution is only for cross subdomains? not for two different domains .
as far as i have seen browsers do not really allow us to share cookies like that across completely different sites .

<!-- gh-comment-id:3214182799 --> @codersaadi commented on GitHub (Aug 22, 2025): hey, @lord007tn does that also work for cross sites ? two different domains (one Nextjs at vercel , second is Hono sever on a vps or something) . like myadmin.vercel.app (or something , ) frontend and anotherdomain.com (and anotherdomain is the hono server which is serving the better auth url ) the thing i have faced is : cookie disappears after sometime , maybe after cache time. so it is not persisting across domains. as long as it is in the cache time (which is 5min) it works . or this solution is only for cross subdomains? not for two different domains . as far as i have seen browsers do not really allow us to share cookies like that across completely different sites .
Author
Owner

@lord007tn commented on GitHub (Aug 22, 2025):

hey, @lord007tn does that also work for cross sites ? two different domains (one Nextjs at vercel , second is Hono sever on a vps or something) . like myadmin.vercel.app (or something , ) frontend and anotherdomain.com (and anotherdomain is the hono server which is serving the better auth url )

the thing i have faced is : cookie disappears after sometime , maybe after cache time. so it is not persisting across domains. as long as it is in the cache time (which is 5min) it works .

or this solution is only for cross subdomains? not for two different domains . as far as i have seen browsers do not really allow us to share cookies like that across completely different sites .

verify that the domain in corssSite is correct for the frontend app, for you it will be myadmin.vercel.app

to serve it in 2 different domain disable crossSite, and rely on samesite: 'none' and secure cookies using useSecureCookies: true

<!-- gh-comment-id:3214986692 --> @lord007tn commented on GitHub (Aug 22, 2025): > hey, [@lord007tn](https://github.com/lord007tn) does that also work for cross sites ? two different domains (one Nextjs at vercel , second is Hono sever on a vps or something) . like myadmin.vercel.app (or something , ) frontend and anotherdomain.com (and anotherdomain is the hono server which is serving the better auth url ) > > the thing i have faced is : cookie disappears after sometime , maybe after cache time. so it is not persisting across domains. as long as it is in the cache time (which is 5min) it works . > > or this solution is only for cross subdomains? not for two different domains . as far as i have seen browsers do not really allow us to share cookies like that across completely different sites . verify that the domain in corssSite is correct for the frontend app, for you it will be `myadmin.vercel.app` to serve it in 2 different domain disable crossSite, and rely on samesite: 'none' and secure cookies using `useSecureCookies: true`
Author
Owner

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

Hi, @Stuart-wdas. 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 a CORS issue with better-auth 1.3.4 involving a Dockerized backend and Next.js frontend where the Access-Control-Allow-Origin header did not match the browser's origin despite including localhost in trustedOrigins.
  • It was explained that better-auth requires exact Origin header matches, and configuration checks were suggested.
  • Contributors discussed CORS middleware setup, cookie domain settings, and Cloudflare proxying as common causes of such issues.
  • A detailed workaround involving crossSubDomainCookies domain configuration was provided, along with recommendations for better-auth documentation improvements for production setups with separate frontend/backend domains.
  • The issue remains unresolved due to the complexity of cross-origin cookies and CORS in these deployment scenarios.

Next Steps:

  • Please let me know if this issue is still relevant with the latest version of better-auth by commenting here to keep the discussion open.
  • Otherwise, I will automatically close this issue in 7 days.

Thank you for your understanding and contribution!

<!-- gh-comment-id:3563748964 --> @dosubot[bot] commented on GitHub (Nov 21, 2025): Hi, @Stuart-wdas. 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 a CORS issue with better-auth 1.3.4 involving a Dockerized backend and Next.js frontend where the Access-Control-Allow-Origin header did not match the browser's origin despite including localhost in trustedOrigins. - It was explained that better-auth requires exact Origin header matches, and configuration checks were suggested. - Contributors discussed CORS middleware setup, cookie domain settings, and Cloudflare proxying as common causes of such issues. - A detailed workaround involving crossSubDomainCookies domain configuration was provided, along with recommendations for better-auth documentation improvements for production setups with separate frontend/backend domains. - The issue remains unresolved due to the complexity of cross-origin cookies and CORS in these deployment scenarios. **Next Steps:** - Please let me know if this issue is still relevant with the latest version of better-auth by commenting here to keep the discussion open. - Otherwise, I will automatically close this issue 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#18379