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 vs railway.app).

  • Cookies with SameSite=None also require Secure 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:

    res.cookie("token", token, { httpOnly: true, secure: true, // HTTPS required sameSite: "Lax", // first-party safe in Safari domain: ".mahisterpieces.in" });
  • Updated CORS:

    app.use(cors({ origin: "https://mahisterpieces.in", credentials: true }));

3. Frontend Configuration

  • Updated VITE_API_URL to:

    https://api.mahisterpieces.in
  • Ensured API requests send cookies:

    axios.post(`${import.meta.env.VITE_API_URL}/login`, data, { withCredentials: true });

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

Popular posts from this blog

What Is Trading? Beginners Guide.

Oasis Infobyte Virtual Internship