Cross-Domain cookies not being set on production #1719

Closed
opened 2026-03-13 08:58:19 -05:00 by GiteaMirror · 17 comments
Owner

Originally created by @Nishantdd on GitHub (Aug 16, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Create a client-server architecture where better auth server is hosted on backend (domain b.com) and auth client being used in frontend (domain a.com)
  2. Use signInEmail method from authClient
  3. The response contains SetCookie but the cookies are never set in storage

Current vs. Expected behavior

Expected: As it happens in development, the cookie must be set and I should be logged in
Current: The cookie is not set and I'm redirected back to login page

What version of Better Auth are you using?

1.3.4

System info

System:
    OS: Windows 11 10.0.26200
    CPU: (12) x64 AMD Ryzen 5 4600H with Radeon Graphics
    Memory: 5.12 GB / 15.37 GB
  Browsers:
    Edge: Chromium (140.0.3485.11)
    Internet Explorer: 11.0.26100.1

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

Client

Auth config (if applicable)

export const auth = betterAuth({
    baseURL: config.BETTER_AUTH_URL,
    secret: config.BETTER_AUTH_SECRET,
    trustedOrigins: [config.CLIENT_ORIGIN],
    advanced: {
        useSecureCookies: config.NODE_ENV === 'production',
        defaultCookieAttributes: {
            secure: config.NODE_ENV === 'production',
            partitioned: config.NODE_ENV === 'production',
            sameSite: config.NODE_ENV === 'production' ? 'None' : 'Lax'
        }
    },
    emailAndPassword: {
        enabled: true
    },
    database: drizzleAdapter(db, {
        provider: 'pg',
        schema: schema
    })
});

Additional context

I'm using fastify for backend and next.js for frontend.
This is my middleware for checking the existence of cookies in nextjs:

export function middleware(request: NextRequest) {
    const session = getSessionCookie(request);
    const { pathname } = request.nextUrl;

    const isAuthPage = pathname === '/login' || pathname === '/signup';

    if (session) {
        if (isAuthPage) return NextResponse.redirect(new URL('/dashboard', request.url));
        else return NextResponse.next();
    } else {
        if (!isAuthPage) return NextResponse.redirect(new URL('/login', request.url));
        else return NextResponse.next();
    }
}

When I use the signInEmail method and stop the network tab before the re-direction, I can see the SetCookie header in response:

__Secure-better-auth.session_token=random.token; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=None; Partitioned

On successful login, I have set the redirection to /dashboard and that redirect occurs. But then my middleware checks for existence of session cookie and redirects me back to /login.
I check the cookies tab in developer's tool and no cookie is being set.

Originally created by @Nishantdd on GitHub (Aug 16, 2025). ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Create a client-server architecture where better auth server is hosted on backend (domain b.com) and auth client being used in frontend (domain a.com) 2. Use signInEmail method from authClient 3. The response contains SetCookie but the cookies are never set in storage ### Current vs. Expected behavior Expected: As it happens in development, the cookie must be set and I should be logged in Current: The cookie is not set and I'm redirected back to login page ### What version of Better Auth are you using? 1.3.4 ### System info ```bash System: OS: Windows 11 10.0.26200 CPU: (12) x64 AMD Ryzen 5 4600H with Radeon Graphics Memory: 5.12 GB / 15.37 GB Browsers: Edge: Chromium (140.0.3485.11) Internet Explorer: 11.0.26100.1 ``` ### Which area(s) are affected? (Select all that apply) Client ### Auth config (if applicable) ```typescript export const auth = betterAuth({ baseURL: config.BETTER_AUTH_URL, secret: config.BETTER_AUTH_SECRET, trustedOrigins: [config.CLIENT_ORIGIN], advanced: { useSecureCookies: config.NODE_ENV === 'production', defaultCookieAttributes: { secure: config.NODE_ENV === 'production', partitioned: config.NODE_ENV === 'production', sameSite: config.NODE_ENV === 'production' ? 'None' : 'Lax' } }, emailAndPassword: { enabled: true }, database: drizzleAdapter(db, { provider: 'pg', schema: schema }) }); ``` ### Additional context I'm using fastify for backend and next.js for frontend. This is my middleware for checking the existence of cookies in nextjs: ```javascript export function middleware(request: NextRequest) { const session = getSessionCookie(request); const { pathname } = request.nextUrl; const isAuthPage = pathname === '/login' || pathname === '/signup'; if (session) { if (isAuthPage) return NextResponse.redirect(new URL('/dashboard', request.url)); else return NextResponse.next(); } else { if (!isAuthPage) return NextResponse.redirect(new URL('/login', request.url)); else return NextResponse.next(); } } ``` When I use the signInEmail method and stop the network tab before the re-direction, I can see the SetCookie header in response: ```text __Secure-better-auth.session_token=random.token; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=None; Partitioned ``` On successful login, I have set the redirection to `/dashboard` and that redirect occurs. But then my middleware checks for existence of session cookie and redirects me back to `/login`. I check the cookies tab in developer's tool and no cookie is being set.
GiteaMirror added the fastify label 2026-03-13 08:58:19 -05:00
Author
Owner

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

The Set-Cookie header looks correct for cross-domain cookies, but browsers will only set these if a few requirements are met. Make sure your Fastify backend sends the right CORS headers: Access-Control-Allow-Origin must match your frontend domain (not *), and Access-Control-Allow-Credentials must be true [docs]. On the frontend, all authentication requests should use credentials: 'include' [docs]. Both frontend and backend must be served over HTTPS, since Secure cookies won't work over HTTP.

Check your browser console and network tab for any CORS or cookie warnings. If you use a proxy or CDN (like Vercel or Cloudflare), confirm it's not stripping Set-Cookie headers. Also, some browsers/extensions block third-party cookies, especially with SameSite=None and Partitioned attributes—try in an incognito window or a different browser.

If all of these are set up correctly and the issue persists, please share details about your deployment environment or any errors you see in the browser console.

To reply, just mention @dosu.


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

@dosubot[bot] commented on GitHub (Aug 16, 2025): <!-- Answer --> The Set-Cookie header looks correct for cross-domain cookies, but browsers will only set these if a few requirements are met. Make sure your Fastify backend sends the right CORS headers: `Access-Control-Allow-Origin` must match your frontend domain (not `*`), and `Access-Control-Allow-Credentials` must be `true` [[docs](https://better-auth.com/docs/concepts/cookies)]. On the frontend, all authentication requests should use `credentials: 'include'` [[docs](https://better-auth.com/docs/concepts/cookies)]. Both frontend and backend must be served over HTTPS, since Secure cookies won't work over HTTP. Check your browser console and network tab for any CORS or cookie warnings. If you use a proxy or CDN (like Vercel or Cloudflare), confirm it's not stripping Set-Cookie headers. Also, some browsers/extensions block third-party cookies, especially with `SameSite=None` and `Partitioned` attributes—try in an incognito window or a different browser. If all of these are set up correctly and the issue persists, please share details about your deployment environment or any errors you see in the browser console. <!-- 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/1d4e04fd-9ee6-4479-9f08-4256859e6f4e?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/1d4e04fd-9ee6-4479-9f08-4256859e6f4e?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/1d4e04fd-9ee6-4479-9f08-4256859e6f4e?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/1d4e04fd-9ee6-4479-9f08-4256859e6f4e?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/1d4e04fd-9ee6-4479-9f08-4256859e6f4e?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/1d4e04fd-9ee6-4479-9f08-4256859e6f4e?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/1d4e04fd-9ee6-4479-9f08-4256859e6f4e?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/4038)
Author
Owner

@Nishantdd commented on GitHub (Aug 16, 2025):

I have explicitly mentioned my frontend url in access origin and enabled credentials in cors settings.

There are no errors in the browser window regarding cookies or cors.

@Nishantdd commented on GitHub (Aug 16, 2025): I have explicitly mentioned my frontend url in access origin and enabled credentials in cors settings. There are no errors in the browser window regarding cookies or cors.
Author
Owner

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

Since you’re seeing the Set-Cookie header but the cookie isn’t being set, here are the most likely causes and next steps:

  1. HTTPS is required for Secure cookies—double check that both your frontend and backend are served over HTTPS in production. Secure cookies won’t work over HTTP, even if everything else is correct [docs].

  2. Cookie domain config: For cross-domain or cross-subdomain cookies, the domain attribute in your Better Auth config must match your actual backend domain exactly (e.g. use .b.com or the full backend domain, not just b.com or .com). Setting the wrong domain can prevent cookies from being set [issue].

  3. Partitioned attribute: Browser support for Partitioned is limited and can block cookies in cross-domain flows. Try setting partitioned: false in your cookie config and test again [discussion].

  4. Proxy/CDN interference: If you use a proxy, CDN, or middleware (like Vercel, Cloudflare, Nginx), make sure it isn’t stripping or modifying Set-Cookie headers. These intermediaries can silently block cookies.

  5. Next.js integration: If you’re using server actions (like signInEmail), cookies won’t be set automatically unless you use the nextCookies plugin from Better Auth. Without it, Set-Cookie headers in responses won’t result in cookies being stored [docs].

  6. Browser policies: Some browsers (especially Safari) block third-party cookies by default, and public suffix domains (like render.com) can cause issues. Test in Chrome/Edge and avoid public suffixes for production [discussion].

If you can share your full Better Auth cookie config (especially the domain and crossSubDomainCookies settings), your frontend authentication request code, and confirm HTTPS usage, I can help pinpoint the issue 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

@dosubot[bot] commented on GitHub (Aug 16, 2025): <!-- Answer --> Since you’re seeing the Set-Cookie header but the cookie isn’t being set, here are the most likely causes and next steps: 1. **HTTPS is required** for Secure cookies—double check that both your frontend and backend are served over HTTPS in production. Secure cookies won’t work over HTTP, even if everything else is correct [[docs](https://better-auth.com/docs/concepts/cookies)]. 2. **Cookie domain config:** For cross-domain or cross-subdomain cookies, the domain attribute in your Better Auth config must match your actual backend domain exactly (e.g. use `.b.com` or the full backend domain, not just `b.com` or `.com`). Setting the wrong domain can prevent cookies from being set [[issue](https://github.com/better-auth/better-auth/issues/1043)]. 3. **Partitioned attribute:** Browser support for `Partitioned` is limited and can block cookies in cross-domain flows. Try setting `partitioned: false` in your cookie config and test again [[discussion](https://github.com/better-auth/better-auth/discussions/3262#discussioncomment-13665380)]. 4. **Proxy/CDN interference:** If you use a proxy, CDN, or middleware (like Vercel, Cloudflare, Nginx), make sure it isn’t stripping or modifying Set-Cookie headers. These intermediaries can silently block cookies. 5. **Next.js integration:** If you’re using server actions (like signInEmail), cookies won’t be set automatically unless you use the `nextCookies` plugin from Better Auth. Without it, Set-Cookie headers in responses won’t result in cookies being stored [[docs](https://better-auth.com/docs/integrations/next)]. 6. **Browser policies:** Some browsers (especially Safari) block third-party cookies by default, and public suffix domains (like render.com) can cause issues. Test in Chrome/Edge and avoid public suffixes for production [[discussion](https://github.com/better-auth/better-auth/discussions/2826)]. If you can share your full Better Auth cookie config (especially the domain and crossSubDomainCookies settings), your frontend authentication request code, and confirm HTTPS usage, I can help pinpoint the issue 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/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?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/4038)
Author
Owner

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

did you find a solution to this ?

@lord007tn commented on GitHub (Aug 18, 2025): did you find a solution to this ?
Author
Owner

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

did you find a solution to this ?

I did find a workaround but found some weird things.

If I remove the middleware and let the user redirect to dashboard (which is a client component where I explicitly check using useSession whether the user is authenticated) then the user can retrieve all the details and is authenticated. That's weird given the cookies are not set.

So I try on both chrome and firefox while monitoring the cookies tab in developer's tools.
In chrome, it goes the following manner:
When I login using signInEmail on login component, the cookies are set but removed immediately the redirect happens to dashboard and then come back when I authenticate on dashboard and I can see them in cookies tab.
In firefox, the whole time I can't see any cookies being set but the application still works as expected on dashboard. So I check the get-session request better auth does to authenticate user in networks tab and see that request cookies does have better auth session cookie. So for some reason, the cookies exist but I can't view them in cookies tab.

That's why the middleware check fails because cookies don't show up. This behaviour may be due to httpOnly enabled but it's still weird.
I don't know why the cookies disappear and then come back on chrome or can't be seen at all in firefox.

So I just removed the middleware check and implemented auth check in login and signup page as well

@Nishantdd commented on GitHub (Aug 19, 2025): > did you find a solution to this ? > I did find a workaround but found some weird things. If I remove the middleware and let the user redirect to dashboard (which is a client component where I explicitly check using useSession whether the user is authenticated) then the user can retrieve all the details and is authenticated. That's weird given the cookies are not set. So I try on both chrome and firefox while monitoring the cookies tab in developer's tools. In chrome, it goes the following manner: When I login using signInEmail on login component, the cookies are set but removed immediately the redirect happens to dashboard and then come back when I authenticate on dashboard and I can see them in cookies tab. In firefox, the whole time I can't see any cookies being set but the application still works as expected on dashboard. So I check the get-session request better auth does to authenticate user in networks tab and see that request cookies does have better auth session cookie. So for some reason, the cookies exist but I can't view them in cookies tab. That's why the middleware check fails because cookies don't show up. This behaviour may be due to httpOnly enabled but it's still weird. I don't know why the cookies disappear and then come back on chrome or can't be seen at all in firefox. So I just removed the middleware check and implemented auth check in login and signup page as well
Author
Owner

@EmilsValdmanis commented on GitHub (Oct 14, 2025):

Did you ever find a solution? I have run into a similar issue with Express.js and Next.js. No matter what i do, locally it works fine, but in deployment the client (Next.js) doesnt set the cookie from the response.

@EmilsValdmanis commented on GitHub (Oct 14, 2025): Did you ever find a solution? I have run into a similar issue with Express.js and Next.js. No matter what i do, locally it works fine, but in deployment the client (Next.js) doesnt set the cookie from the response.
Author
Owner

@lord007tn commented on GitHub (Oct 14, 2025):

@EmilsValdmanis
check this i already did some workaround that currently used in production app: https://github.com/better-auth/better-auth/issues/3874#issuecomment-3198999324

@lord007tn commented on GitHub (Oct 14, 2025): @EmilsValdmanis check this i already did some workaround that currently used in production app: https://github.com/better-auth/better-auth/issues/3874#issuecomment-3198999324
Author
Owner

@EmilsValdmanis commented on GitHub (Oct 15, 2025):

Managed to fix it! Turns out the issue was that my backend wasn’t yet hosted on the same example.com domain. The cookie just wouldn’t set on example.com, but it was getting set on the default Azure domain for the backend—and of course, it wasn’t accessible on the frontend. I don’t think I misconfigured anything; I’d pretty much tried everything. Once we deployed backend to api.example.com everything worked. Honestly, the better-auth docs could really use more examples for setups where the frontend and backend are on different domains. There was no mention that they have to be on the same domain for cookies to work properly.

@EmilsValdmanis commented on GitHub (Oct 15, 2025): Managed to fix it! Turns out the issue was that my backend wasn’t yet hosted on the same `example.com` domain. The cookie just wouldn’t set on `example.com`, but it was getting set on the default Azure domain for the backend—and of course, it wasn’t accessible on the frontend. I don’t think I misconfigured anything; I’d pretty much tried everything. Once we deployed backend to `api.example.com` everything worked. Honestly, the better-auth docs could really use more examples for setups where the frontend and backend are on different domains. There was no mention that they have to be on the same domain for cookies to work properly.
Author
Owner

@ping-maxwell commented on GitHub (Oct 15, 2025):

Managed to fix it! Turns out the issue was that my backend wasn’t yet hosted on the same example.com domain. The cookie just wouldn’t set on example.com, but it was getting set on the default Azure domain for the backend—and of course, it wasn’t accessible on the frontend. I don’t think I misconfigured anything; I’d pretty much tried everything. Once we deployed backend to api.example.com everything worked. Honestly, the better-auth docs could really use more examples for setups where the frontend and backend are on different domains. There was no mention that they have to be on the same domain for cookies to work properly.

https://www.better-auth.com/docs/concepts/cookies#cross-subdomain-cookies

Image
@ping-maxwell commented on GitHub (Oct 15, 2025): > Managed to fix it! Turns out the issue was that my backend wasn’t yet hosted on the same `example.com` domain. The cookie just wouldn’t set on `example.com`, but it was getting set on the default Azure domain for the backend—and of course, it wasn’t accessible on the frontend. I don’t think I misconfigured anything; I’d pretty much tried everything. Once we deployed backend to `api.example.com` everything worked. Honestly, the better-auth docs could really use more examples for setups where the frontend and backend are on different domains. There was no mention that they have to be on the same domain for cookies to work properly. https://www.better-auth.com/docs/concepts/cookies#cross-subdomain-cookies <img width="743" height="750" alt="Image" src="https://github.com/user-attachments/assets/8e78eb8a-2999-4344-b87d-2bc3b10946d4" />
Author
Owner

@ping-maxwell commented on GitHub (Oct 15, 2025):

There was no mention that they have to be on the same domain for cookies to work properly.

It's a security standard to only allow storing/retrieving cookies on the same domain, the same would apply to any other auth provider. Given how common this is, I assume it's for that reason it's not documented, I'll open a PR to mention this explicitly.

@ping-maxwell commented on GitHub (Oct 15, 2025): > There was no mention that they have to be on the same domain for cookies to work properly. It's a security standard to only allow storing/retrieving cookies on the same domain, the same would apply to any other auth provider. Given how common this is, I assume it's for that reason it's not documented, I'll open a PR to mention this explicitly.
Author
Owner

@ping-maxwell commented on GitHub (Oct 15, 2025):

@Nishantdd Just trying to catch up, is your issue resolved?

@ping-maxwell commented on GitHub (Oct 15, 2025): @Nishantdd Just trying to catch up, is your issue resolved?
Author
Owner

@Ritik1330 commented on GitHub (Oct 31, 2025):

Use this with the success hook for client-side redirection, but it doesn’t work with Google Auto. This is happening because the betterauth callback calls this page before the cookie is set.

const referer = request.headers.get("referer");
console.log("🔍 Middleware - Referer:", referer);

if (
	referer &&
	(referer.includes("/auth/") ||
		referer.includes("google.com") ||
		referer.includes("accounts.google"))
) {
	console.log("✅ Middleware - Skipping check (from auth/OAuth)");
	return NextResponse.next();
}
@Ritik1330 commented on GitHub (Oct 31, 2025): Use this with the success hook for client-side redirection, but it doesn’t work with Google Auto. This is happening because the betterauth callback calls this page before the cookie is set. const referer = request.headers.get("referer"); console.log("🔍 Middleware - Referer:", referer); if ( referer && (referer.includes("/auth/") || referer.includes("google.com") || referer.includes("accounts.google")) ) { console.log("✅ Middleware - Skipping check (from auth/OAuth)"); return NextResponse.next(); }
Author
Owner

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

Based on what you’re describing, here are a few steps to troubleshoot your cross-domain cookie issue:

  1. Verify your domain settings. In a cross-domain setup (backend on b.com and frontend on a.com), if you don’t explicitly set a cookie domain then the browser may reject the cookie when it’s not on the same domain. Even though your current config uses trustedOrigins, try explicitly setting the cookie domain (or use the automatic domain extraction strategy if supported) so the cookie’s domain matches your production requirements [1].

  2. Confirm that your secure attributes are correctly applied. Your response header shows SameSite=None, Secure, HttpOnly, and Partitioned. For cross-site cookies these flags are required, but browsers can still drop cookies if—for example—the domain isn’t aligned with the request or if a redirect interferes with the header [2].

  3. Check your redirect flow. Since the response with the Set-Cookie header is immediately followed by a redirect (which then triggers your middleware), ensure that the browser isn’t stripping the header due to a subsequent cross-domain redirect. Test by temporarily intercepting the redirect (or by manually navigating) to verify the cookie is received in storage [1], [2].

  4. Validate that your frontend fetch requests include credentials. Even though you see the Set-Cookie header in the network tab, the browser will only store the cookie if the request includes credentials (using credentials: 'include' or similar) and if your CORS settings are correctly set up to allow credentials [3].

  5. Regarding the additional snippet that checks the referer and skips auth for certain OAuth-originating requests: double‑check that this condition isn’t inadvertently bypassing the cookie setting when coming from a Google auto flow. It might be helpful to temporarily remove or log those checks to see if the cookie behavior changes [3].

Going through these steps should help narrow down whether the issue is due to the cookie domain, the redirect flow, or the client’s CORS/credentials settings preventing the cookie from being stored. Let me know if you need further assistance!

DiagramDiscordGitHub

Diagram Join Star

@better-auth-agent[bot] commented on GitHub (Oct 31, 2025): Based on what you’re describing, here are a few steps to troubleshoot your cross-domain cookie issue: 1. Verify your domain settings. In a cross-domain setup (backend on b.com and frontend on a.com), if you don’t explicitly set a cookie domain then the browser may reject the cookie when it’s not on the same domain. Even though your current config uses trustedOrigins, try explicitly setting the cookie domain (or use the automatic domain extraction strategy if supported) so the cookie’s domain matches your production requirements [[1]](https://github.com/better-auth/better-auth/issues/4038). 2. Confirm that your secure attributes are correctly applied. Your response header shows SameSite=None, Secure, HttpOnly, and Partitioned. For cross-site cookies these flags are required, but browsers can still drop cookies if—for example—the domain isn’t aligned with the request or if a redirect interferes with the header [[2]](https://github.com/better-auth/better-auth/issues/935). 3. Check your redirect flow. Since the response with the Set-Cookie header is immediately followed by a redirect (which then triggers your middleware), ensure that the browser isn’t stripping the header due to a subsequent cross-domain redirect. Test by temporarily intercepting the redirect (or by manually navigating) to verify the cookie is received in storage [[1]](https://github.com/better-auth/better-auth/issues/4038), [[2]](https://github.com/better-auth/better-auth/issues/935). 4. Validate that your frontend fetch requests include credentials. Even though you see the Set-Cookie header in the network tab, the browser will only store the cookie if the request includes credentials (using credentials: 'include' or similar) and if your CORS settings are correctly set up to allow credentials [[3]](https://github.com/better-auth/better-auth/issues/5672). 5. Regarding the additional snippet that checks the referer and skips auth for certain OAuth-originating requests: double‑check that this condition isn’t inadvertently bypassing the cookie setting when coming from a Google auto flow. It might be helpful to temporarily remove or log those checks to see if the cookie behavior changes [[3]](https://github.com/better-auth/better-auth/issues/5672). Going through these steps should help narrow down whether the issue is due to the cookie domain, the redirect flow, or the client’s CORS/credentials settings preventing the cookie from being stored. Let me know if you need further assistance! <!-- 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 (Oct 31, 2025):

It looks like the cookie isn’t being stored because the auth callback (especially for Google auto login) is causing the redirection to occur before the cookie is actually written. Here are some next steps and troubleshooting tips:

  1. Make sure that both your client and server configurations use the same domain policies. Verify that your trusted origins include the exact frontend URL, that credentials are sent (using credentials: "include" in your fetch options), and that the cookie attributes (SameSite, Secure, and Partitioned) are correctly set for cross-domain usage.

  2. Since you’re seeing the Set-Cookie header but the cookie never makes it into storage, try delaying the redirection. Use a client-side success hook (instead of an immediate redirect) so that the cookie has time to be set before the next page load. This is especially important for OAuth flows where the referer is coming from providers like Google.

  3. Update your middleware to inspect the referer header as a temporary bypass for requests originating from the OAuth callback. However, double-check that the referer check covers all relevant cases. You might need to ensure that the auth callback URL itself isn’t inadvertently triggering a cookie check before the cookie is applied.

  4. Finally, check that no proxy or intermediary (such as Cloudflare, if used) is interfering with the Set-Cookie header, and log the complete server response to confirm that the cookie properties are as expected.

These steps should help resolve why, in production, the cookie isn’t getting stored as expected even though the header is present [1], [2].

DiagramDiscordGitHub

Diagram Join Star

@better-auth-agent[bot] commented on GitHub (Oct 31, 2025): It looks like the cookie isn’t being stored because the auth callback (especially for Google auto login) is causing the redirection to occur before the cookie is actually written. Here are some next steps and troubleshooting tips: 1. Make sure that both your client and server configurations use the same domain policies. Verify that your trusted origins include the exact frontend URL, that credentials are sent (using credentials: "include" in your fetch options), and that the cookie attributes (SameSite, Secure, and Partitioned) are correctly set for cross-domain usage. 2. Since you’re seeing the Set-Cookie header but the cookie never makes it into storage, try delaying the redirection. Use a client-side success hook (instead of an immediate redirect) so that the cookie has time to be set before the next page load. This is especially important for OAuth flows where the referer is coming from providers like Google. 3. Update your middleware to inspect the referer header as a temporary bypass for requests originating from the OAuth callback. However, double-check that the referer check covers all relevant cases. You might need to ensure that the auth callback URL itself isn’t inadvertently triggering a cookie check before the cookie is applied. 4. Finally, check that no proxy or intermediary (such as Cloudflare, if used) is interfering with the Set-Cookie header, and log the complete server response to confirm that the cookie properties are as expected. These steps should help resolve why, in production, the cookie isn’t getting stored as expected even though the header is present [[1]](https://github.com/better-auth/better-auth/issues/4038), [[2]](https://github.com/better-auth/better-auth/issues/935). <!-- 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

@Nishantdd commented on GitHub (Nov 11, 2025):

@Nishantdd Just trying to catch up, is your issue resolved?

I think it can be closed because it's more of a web limitation than a better-auth issue. We simply can't set cross-domain cookies as browsers won't allow it. (Some do regardless, safari does not)

@Nishantdd commented on GitHub (Nov 11, 2025): > [@Nishantdd](https://github.com/Nishantdd) Just trying to catch up, is your issue resolved? I think it can be closed because it's more of a web limitation than a better-auth issue. We simply can't set cross-domain cookies as browsers won't allow it. (Some do regardless, safari does not)
Author
Owner

@OliverFluid commented on GitHub (Feb 6, 2026):

For anyone coming back to this - I have fixed this by forcing cookies to be applied across all token values.

Not sure if theres an issue with the crossSubdomainCookies and/or defaultCookieAttributes as neither of those resolved my issue, but adding in the granular cookies specifically for session_token and session_data fixed the missing Domain= in set-cookie response from the backend installation of better-auth for my frontend.

advanced: {
    cookiePrefix: 'someprefix',
    useSecureCookies: true,
    crossSubdomainCookies: {
      enabled: true,
      domain: '.tld.com',
    },
    cookies: {
      session_token: {
        attributes: {
          domain: '.tld.com',
          secure: true,
          httpOnly: true,
          sameSite: 'lax',
          path: '/'
        }
      },
      session_data: {
        attributes: {
          domain: '.tld.com',
          secure: true,
          httpOnly: true,
          sameSite: 'lax',
          path: '/'
        }
      }
    },
    defaultCookieAttributes: {
      sameSite: "lax",
      secure: true,
      domain: '.tld.com',
    },
  },
@OliverFluid commented on GitHub (Feb 6, 2026): For anyone coming back to this - I have fixed this by forcing cookies to be applied across all token values. Not sure if theres an issue with the `crossSubdomainCookies` and/or `defaultCookieAttributes` as neither of those resolved my issue, but adding in the granular cookies specifically for `session_token` and `session_data` fixed the missing `Domain=` in `set-cookie` response from the backend installation of better-auth for my frontend. ``` advanced: { cookiePrefix: 'someprefix', useSecureCookies: true, crossSubdomainCookies: { enabled: true, domain: '.tld.com', }, cookies: { session_token: { attributes: { domain: '.tld.com', secure: true, httpOnly: true, sameSite: 'lax', path: '/' } }, session_data: { attributes: { domain: '.tld.com', secure: true, httpOnly: true, sameSite: 'lax', path: '/' } } }, defaultCookieAttributes: { sameSite: "lax", secure: true, domain: '.tld.com', }, }, ```
Author
Owner

@rotimi-best commented on GitHub (Feb 15, 2026):

Since you’re seeing the Set-Cookie header but the cookie isn’t being set, here are the most likely causes and next steps:

  1. HTTPS is required for Secure cookies—double check that both your frontend and backend are served over HTTPS in production. Secure cookies won’t work over HTTP, even if everything else is correct [docs].
  2. Cookie domain config: For cross-domain or cross-subdomain cookies, the domain attribute in your Better Auth config must match your actual backend domain exactly (e.g. use .b.com or the full backend domain, not just b.com or .com). Setting the wrong domain can prevent cookies from being set [issue].
  3. Partitioned attribute: Browser support for Partitioned is limited and can block cookies in cross-domain flows. Try setting partitioned: false in your cookie config and test again [discussion].
  4. Proxy/CDN interference: If you use a proxy, CDN, or middleware (like Vercel, Cloudflare, Nginx), make sure it isn’t stripping or modifying Set-Cookie headers. These intermediaries can silently block cookies.
  5. Next.js integration: If you’re using server actions (like signInEmail), cookies won’t be set automatically unless you use the nextCookies plugin from Better Auth. Without it, Set-Cookie headers in responses won’t result in cookies being stored [docs].
  6. Browser policies: Some browsers (especially Safari) block third-party cookies by default, and public suffix domains (like render.com) can cause issues. Test in Chrome/Edge and avoid public suffixes for production [discussion].

If you can share your full Better Auth cookie config (especially the domain and crossSubDomainCookies settings), your frontend authentication request code, and confirm HTTPS usage, I can help pinpoint the issue 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

Step 2, was the solution for me. Thank you, it was driving me crazy.

@rotimi-best commented on GitHub (Feb 15, 2026): > Since you’re seeing the Set-Cookie header but the cookie isn’t being set, here are the most likely causes and next steps: > > 1. **HTTPS is required** for Secure cookies—double check that both your frontend and backend are served over HTTPS in production. Secure cookies won’t work over HTTP, even if everything else is correct [[docs](https://better-auth.com/docs/concepts/cookies)]. > 2. **Cookie domain config:** For cross-domain or cross-subdomain cookies, the domain attribute in your Better Auth config must match your actual backend domain exactly (e.g. use `.b.com` or the full backend domain, not just `b.com` or `.com`). Setting the wrong domain can prevent cookies from being set [[issue](https://github.com/better-auth/better-auth/issues/1043)]. > 3. **Partitioned attribute:** Browser support for `Partitioned` is limited and can block cookies in cross-domain flows. Try setting `partitioned: false` in your cookie config and test again [[discussion](https://github.com/better-auth/better-auth/discussions/3262#discussioncomment-13665380)]. > 4. **Proxy/CDN interference:** If you use a proxy, CDN, or middleware (like Vercel, Cloudflare, Nginx), make sure it isn’t stripping or modifying Set-Cookie headers. These intermediaries can silently block cookies. > 5. **Next.js integration:** If you’re using server actions (like signInEmail), cookies won’t be set automatically unless you use the `nextCookies` plugin from Better Auth. Without it, Set-Cookie headers in responses won’t result in cookies being stored [[docs](https://better-auth.com/docs/integrations/next)]. > 6. **Browser policies:** Some browsers (especially Safari) block third-party cookies by default, and public suffix domains (like render.com) can cause issues. Test in Chrome/Edge and avoid public suffixes for production [[discussion](https://github.com/better-auth/better-auth/discussions/2826)]. > > If you can share your full Better Auth cookie config (especially the domain and crossSubDomainCookies settings), your frontend authentication request code, and confirm HTTPS usage, I can help pinpoint the issue further. > > _To reply, just mention [@dosu](https://go.dosu.dev/dosubot)._ > > How did I do? [Good](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/811d3b01-d340-4e60-aabd-476ac2cb528c?feedback_type=other)  [![Chat with Dosu](https://camo.githubusercontent.com/7c571478962a6b8a5d47cac74b6824c75e4f6731bba52377e6007f9150462923/68747470733a2f2f646f73752e6465762f646f73752d636861742d62616467652e737667)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github) [![Join Discord](https://camo.githubusercontent.com/7d2066700925db1e370d956834f9ea0e5bc92cecbe84963fbd2a363e45091b4e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6a6f696e2d3538363546323f6c6f676f3d646973636f7264266c6f676f436f6c6f723d7768697465266c6162656c3d)](https://go.dosu.dev/discord-bot) [![Share on X](https://camo.githubusercontent.com/a8bd7f3fcf3f5e3bd124eee9ae50ae2ac17b40971726665ac2121d48f9aee155/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f582d73686172652d626c61636b)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/4038) Step 2, was the solution for me. Thank you, it was driving me crazy.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1719