0

I am trying to set a cookie with Node.js and express but when I check in chrome dev tools there is no cookie. I am obviously doing something wrong but not sure what.

In my loginController.js I have

exports.postLogin = async (req, res) => {
  const { email, password } = req.body;
  const user = await authenticate(email, password);
  if (!user) return res.status(403).send("Invalid email or password");
  const userData = {
    name: user.name,
    email: user.email,
    type: AUTH_USER_TYPE
  };
  res.cookie("token", userData, { httpOnly: true, signed: true });
  res.json(userData);
};

And in app.js I have:

const cookieParser = require("cookie-parser");
app.use(cookieParser(process.env.COOKIE_SECRET));
user10980228
  • 597
  • 1
  • 6
  • 21

1 Answers1

0

You need to define httpOnly: false, like:

res.cookie("token", userData, { maxAge: 1000 * 60 * 10, httpOnly: false });

At client-side you need to send withCredentials: true in request

$http({
    method: 'POST',
    url: 'url, 
    withCredentials: true,
    data : {}
}).then(function(response){
    //response
}, function (response) {
    //response
});

Note: httpOnly : false will not be accessible through document.cookie in the browser. It will still be sent with HTTP requests, and if you check your browsers' dev tools you will most likely find the cookie in Chrome can be found in the Resources tab of the dev tools.

Paresh Barad
  • 1,544
  • 11
  • 18
  • I tried that but get: Access to XMLHttpRequest at 'http://localhost:8000/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. – user10980228 Oct 31 '19 at 19:01
  • @user10980228 Please add `cors` as middleware, you can follow [step](https://stackoverflow.com/a/46988108) – Paresh Barad Nov 01 '19 at 06:25