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.
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:
credentials: true
is a must.origin: '*'
won’t work when credentials are involved. Set it to your frontend domain.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);
}
};
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!
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.
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
Set-Cookie
header actually appear? If not, the backend might not be sending it.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