Trouble Receiving Subdomain Cookies in Express Backend with CORS and Cookie-Parser

275 Views Asked by At

I'm currently working on a MERN (MongoDB, Express, React, Node.js) application where I'm facing issues with receiving cookies from subdomains in my Express backend. I've set up CORS and cookie handling, and while everything works fine when using a simple localhost origin, I'm encountering difficulties with subdomains.

Here's a summary of the steps I've taken and the problems I'm facing:

Setting up a cookie at time of Login:

res.cookie("token", token, {
    httpOnly: true,
    sameSite: "none",
    path: "/",
    secure: true,
  });

When I try to get this cookie with my cors setting where the origin is :

app.use(
  cors({
    origin: "http://localhost:3000", 
    credentials: true,
  })
);

But for testing when i use subdomain origin like :

app.use(
  cors({
    origin: "http://binbros.localhost:3000",
    credentials: true,
  })
);

There is no error with Cors from frontend and the cookie is created successfully at frontend But when i try to access cookies with this cor setting i don't receive any cookie But with the same method and Cors setting to simple Localhost, i get all the cookies without any problem

console.log(req.cookies);

P.S : when im in localhost and orgin is loclhost and i log cookie i get all the frontend cookie not only the one i created in backend BUT when i am in origin of subdomain i don't even get 1 cookie in backend, Not the one i created neither any one from frontend

1

There are 1 best solutions below

2
mostafa rastegar On

When working with subdomains in a development environment like subdomain.localhost, there can be additional challenges due to browser security policies. Browsers often treat different subdomains as separate origins, which can affect the behavior of cookies and CORS.

secure property in the development environment is better to be false.

res.cookie("token", token, {
    httpOnly: true,
    sameSite: "none",
    path: "/",
    secure: false,
  });

check your system hosts:

127.0.0.1 binbros.localhost

in frontend check is called apis from binbros.localhost domain or not, and end check Access-Control-Allow-Credentials

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials