Home > Software engineering >  How to access cookies correctly in express application
How to access cookies correctly in express application

Time:11-30

I have been having trouble on my MERN application I'm building. I am storing a token in cookies when I register/login a user. I am able to access this cookie through my express app fine and when using Postman all works as well.

Now the issue that I am encountering is when I try to access protected routes through my client side that is in React. I'm not sure how to handle this correctly because in my express app I can't get the cookie in the same matter I am doing so when using postman for example. I am using httpOnly: true so that the cookie can only be access from my express app. I want to keep this the way it is with httpOnly for security reasons so I do not want access to the token through my client side.

Here is my code on the express app...

exports.protect = catchAsync(async (req, res, next) => {
  let token;

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer')
  ) {
    token = req.headers.authorization.split(' ')[1];
  }

  console.log(req.headers);

  if (!token) {
    return next(new AppError('No token found!', 401));
  }

  const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
  const freshUser = await User.findById(decoded.id);

  if (!freshUser) {
    return res.status(401).json({
      status: 'fail',
      message: 'This token no longer exists!',
    });
  }

  req.user = freshUser;
  next();
});

When I try to access the token using req.headers.authorization using postman it works but like I mentioned before using my client side react app it doesn't and is undefined. using req.headers I can see cookies though. I feel like I can just access req.headers.cookies then but what should I do when just running my backend without running my client side app? I do not want to have separate code. Please let me know if I need to clarify what I am saying here.

CodePudding user response:

Got some extent of your question. First your node server and your react server won't be running on a same port. So, server cookies won't work like it normally should. You should set domain as well. And if your react server and node server run on that domain and it's domain then they can share the cookie.

Example of sending request to node server with authorization header through axios:


    axios.post("https://<api>.com", {
      headers: {
        Authorization: 'Bearer <your-bearer-token>'
      }
    })

postman sends it this way.

  • Related