79497864

Date: 2025-03-10 11:39:51
Score: 4.5
Natty:
Report link

Problem: Fetch Not Sending Cookies After Deployment

Ahh, I’ve been down this rabbit hole before, and I know how annoying this can be. It works fine on localhost, but the moment you deploy, your cookies just vanish into thin air. 😤

This is almost always a CORS + cookie attribute issue. Let’s break it down and fix it step by step.


1. CORS Setup (Server-Side - Node.js/Express)

First, your API needs to explicitly allow credentials (cookies). Without this, your browser refuses to send them. Make sure your cors settings look something like this:

const corsOptions = {
    origin: "https://yourwebsite.com", // Your frontend domain (NO wildcards '*' if using credentials)
    credentials: true,
};

app.use(cors(corsOptions));

🚨 Important:


2. Your Fetch Request (Client-Side - React)

Your request looks mostly correct, but double-check that the api variable actually holds the correct URL. Sometimes, localhost is hardcoded in development but doesn't match in production.

const send = async () => {
    try {
        const res = await fetch(`${api}/api/v1/user/profile`, {
            method: "POST",
            credentials: "include", // 👈 This is needed for cookies!
            headers: {
                "Content-Type": "application/json",
            },
        });

        const data = await res.json();

        if (res.ok) {
            console.log("OK", data);
        } else {
            console.log("Error:", data);
        }
    } catch (error) {
        console.error("Fetch error:", error);
    }
};

3. Cookie Attributes Matter (Server-Side - When Setting Cookies)

Even if CORS is perfect, your cookies might still not work due to missing flags. When setting cookies, make sure your backend sends them like this:

res.cookie("authToken", token, {
    domain: ".yourwebsite.com", // 👈 Needed for subdomains
    path: "/",
    secure: true, // 👈 Must be true for cross-site cookies
    sameSite: "none", // 👈 Required for cross-origin requests
    httpOnly: true, // 👈 Security measure
});

🚨 If you don’t use secure: true, cookies won’t work over HTTPS!


4. Double-Check HTTPS (Must Be Enabled!)

Browsers block cookies with SameSite: 'None' unless you are on HTTPS. So make sure:
✅ Your API is served over HTTPS
✅ Your frontend is served over HTTPS

If your API is http://api.yourwebsite.com but your frontend is https://yourwebsite.com, cookies won’t be sent.


5. Debugging Steps (If It’s Still Not Working)

Alright, if it’s still not working, here’s what I’d do next:

1️⃣ Open DevTools (F12) → Network Tab → Click the Request

2️⃣ Look at the Response Headers

3️⃣ Try Manually Sending a Cookie from the Backend
Run this in your API response to see if cookies even get set:

res.setHeader("Set-Cookie", "testCookie=value; Path=/; Secure; HttpOnly; SameSite=None");

4️⃣ Try Sending a Request Using Postman

Reasons:
  • Blacklisted phrase (0.5): I need
  • Blacklisted phrase (2): Still Not Working
  • Blacklisted phrase (2): still not working
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Naimish Dhorajiya