What went wrong?
When a user logged in on my deployed frontend (https://domainA.app), the credentials succeeded, but they were immediately treated as unauthenticated. Protected endpoints (like /stats/admin/*) failed with a 401 Unauthorized status code.
Crucially, this behavior did not happen on localhost.
Why did it happen?
This is caused by cross-site cookie restrictions enforced by modern web browsers.
- On localhost: The frontend (
http://localhost:5173) and backend (http://localhost:8000) share the same hostname (localhost). Browsers treat different ports on localhost as a secure, shared origin context, meaning cookie exchange works by default without strict rules. - On production: The frontend (
domainA.app) and backend (domainB.app) are hosted on completely different domains (cross-site).
The Cookie Block:
When the backend tries to set the authentication session cookie (better-auth.session_token), the browser blocks and rejects it because the cookie does not have the necessary flags to be sent across different domains:
-
SameSite=None: Tells the browser that this cookie is allowed to be sent on cross-site requests. -
Secure: Enforces that the cross-site cookie is only sent over HTTPS (which is required ifSameSite=Noneis set).
The Result:
Because the browser rejected the cookie, it was never stored. When the frontend made requests to /stats/admin/*, no session cookie was included. The backend session middleware received no credentials and returned a 401 Unauthorized error.
Top comments (0)