Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

res.clearCookie function doesn't delete cookies

I am creating an authorization system for my express (with typescript) application and I use JWT and save them into cookies to keep the user logged in. I have a problem with the logout part and res.clearCookie() doesn't delete cookies.

I have used cookie-parser in the index file and I have tried resetting the cookie with an empty value or expiration date of now but it doesn't work for me. As I stated above res.clearCookie("jwt") doesnt work either. All dependencies are up-to-date.

Login and Login Verification works fine and I can set and read [and decode] the JWT properly.

Main Part of Login Code

res.cookie("jwt", token, {
   httpOnly: true,
   expires: new Date(
       Date.now() + 1000 * 86400 * stayLoggedInDays
   )
}).send("Message: Login successful");

Logout Code

router.post(
  "/logout",
  (req, res, next) => {
    res.clearCookie("jwt");
    next();
  },
  (req, res) => {
    console.log(req.cookies);
    res.end("finish");  
  }
);

After Logout I still can see the user profile but if I delete the cookie manually from postman the profile page won't show any information so my conclusion is that express cannot clear cookies.

like image 546
Amirali Amirifar Avatar asked Sep 04 '19 15:09

Amirali Amirifar


1 Answers

I believe your issue is that you are not passing the options parameter into clearCookie() and the client is not clearing the cookie as it is not identical. Per the Express documentation:

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

Also found a GitHub issue on the express repo which states the same and shows an example of passing the domain and path:

res.clearCookie('my_cookie', {domain: COOKIE_DOMAIN, path: COOKIE_PATH});
like image 130
Daniel Bank Avatar answered Oct 12 '22 11:10

Daniel Bank