Safari Cookies Not Working with Express.js App
Problem
-
The app worked fine in Chrome/Firefox/Edge, but in Safari:
-
Cookies were not being set properly.
-
As a result, protected routes could not be accessed.
-
-
Setup:
-
Frontend: Vercel (
https://mahisterpieces.in
) -
Backend: Railway (
https://mahisterpieces-production.up.railway.app
)
-
Root Cause
Safari enforces stricter cookie rules due to Intelligent Tracking Prevention (ITP):
-
Cookies set across different domains are treated as third-party cookies → blocked in Safari.
-
Our frontend and backend were on different domains (
mahisterpieces.in
vsrailway.app
). -
Cookies with
SameSite=None
also requireSecure
and HTTPS.
Thus, Safari dropped the backend cookies.
Solution
1. Custom Subdomain for Backend
-
Created a subdomain:
api.mahisterpieces.in
-
Added a CNAME record in Vercel DNS pointing
api → m9q66juq.up.railway.app
(Railway’s verification target). -
Verified the domain in Railway → Domains, which issued an SSL cert.
-
Now both frontend and backend share the same root domain → cookies are first-party in Safari.
2. Backend Configuration
-
Updated Express cookie settings:
-
Updated CORS:
3. Frontend Configuration
-
Updated
VITE_API_URL
to: -
Ensured API requests send cookies:
Outcome
-
Cookies are now treated as first-party in Safari.
-
Login + protected routes work across all browsers.
-
Deployment domains are cleaner:
-
Frontend →
mahisterpieces.in
-
Backend →
api.mahisterpieces.in
-
✅ Learning:
When using cookies for auth, always put frontend and backend under the same root domain (e.g., example.com
+ api.example.com
). Safari will block cookies otherwise.
Comments
Post a Comment