Search code examples
node.jsreactjscookiescors

Cookie is not being set in the browser using node and react js


I am creating a cookie in node with express and then sending it to the front end which created with React js. Testing the response from the server with Postman I am getting back the cookie, but in the browser (using Chrome developer tools) I cant see the cookie. I have set the cors and tryed many options based on the info I have found, but none of them work. On the react side I have set the proxy of my the server address in the packagejson, also I am have used Vite to create the app. Current code:

const cookierParser = require("cookie-parser");
const app = express();
const cors = require("cors");
app.use(express.json());
app.use(cookierParser());
app.use(
 cors({
  origin: ["http://127.0.0.1:5173"],
  methods: ["POST", "GET"],
  credentials: true,
 })
);

The cookie in the request:

res.cookie("token", accessToken, {
    httpOnly: true,
    secure: false,
    sameSite: "none",
    maxAge: 3600000,
  });
res.status(200).json({ message: "Logged in" });
  }

Axios in the front-end:

const loginUser = useMutation({
mutationFn: (user: FormData) => {
  return axios.post("http://localhost:5000/login", user, {
    withCredentials: true,
  });
},
});

Solution

  • It seems that the problem was only for Chrome, I have found that you can change some options that allows to accept cookies and then they show up in the local browser:

    chrome://flags/#same-site-by-default-cookies

    chrome://flags/#cookies-without-same-site-must-be-secure

    Since I am using this for development and eventually I will use https the cookies will appear, it didn't appear because of http and Chrome's cookies policies

    Even though cookies are not seen in the developer tools, I can still access them in the back-end, my mistake of not checking that earlier