CORS + Auth Worked Perfectly Locally, Then Broke the Moment I Deployed (Here's Why)
I ran into this bug recently and it took me longer to fix than I'd like to admit: my React + Express app worked flawlessly on localhost, but the moment I deployed it, authenticated requests started silently failing. No errors in my own code - just requests that looked like they went out, but the backend never seemed to receive the session/token.
The Setup
- React frontend and Express backend deployed to separate origins (different domains/subdomains)
- Auth relying on a cookie (or JWT sent with credentials) set by the backend
- Locally, both ran on localhost with different ports, which browsers treat more leniently
What Actually Happened
Once frontend and backend were on genuinely different origins in production, a few things I'd gotten away with locally stopped working:
- My CORS config allowed
origin: '*'- which silently breaks anything using credentials, since browsers won't send cookies/auth headers when the origin is a wildcard. - The cookie itself wasn't configured for cross-site use - no
SameSite=None; Secure, which most browsers now require for any cookie sent across origins over HTTPS. - On the frontend, requests weren't explicitly sending credentials (
credentials: 'include'infetch, orwithCredentials: trueinaxios).
Locally, same-origin-ish behavior papered over all three problems at once.
The Fix
- Set CORS to an explicit origin (not
*) andcredentials: trueon the Express side - Set the cookie with
SameSite=None; Secureso browsers allow it cross-site - Explicitly send credentials on every authenticated request from the frontend
Once all three were aligned, everything that had been "randomly failing" in production started working immediately.
Takeaway
If your auth works locally but silently fails after deploy, check CORS origin config, cookie SameSite/Secure attributes, and whether the frontend is actually sending credentials - together, not just one of them.
Comments
No comments yet. Start the discussion.