DEV Community

dev-shubham098
dev-shubham098

Posted on

Need Help πŸ™ unable to delete cookie in Express

Hello everyone πŸ‘‹ I am a newbie working on a full stack web app using node, express and mongodb in the backend for my final semester project.

I am working on an admin portal, when users (admins) sign in a cookie is stored in the browser and a token (using json web tokens here) is stored in the mongodb, but I am unable to delete the cookie during logout.

My logout code is :-

app.get("/logout", auth, async (req, res) => {
  try {

    req.user.tokens = req.user.tokens.filter((currentElement) => {
    return currentElement.token !== req.token })

    res.clearCookie("jwt");
    console.log("Logout Successful");

    await req.user.save();
    res.render("/");

  } catch (error) {
    res.status(500).send(error);
  }
});
Enter fullscreen mode Exit fullscreen mode

Authorization code :-

const auth = async (req, res, next) => {
    try  {
        const token = req.cookies.jwt;
        const verifyUser = jwt.verify(token, process.env.SECRET_KEY);
        console.log(verifyUser);

        const user = Register.findOne({ _id :verifyUser._id});
        console.log(user.firstname);

        req.token = token;
        req.user = user;

        next();     

    } catch (error) {
        res.status(401).send(error);
    }
}
Enter fullscreen mode Exit fullscreen mode

Logout only gives this output :-

Image description

And it seems like
res.clearCookie("jwt")
is not working here πŸ‘‡

Image description

as the jwt cookie is not getting deleted πŸ˜‘ Please help I am stuck from weeks. Unable to figure out how to make it work.

Top comments (4)

Collapse
 
fish1 profile image
Jacob Enders

Does this help any?

expressjs.com/en/api.html#res.clea...

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.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shriekdj profile image
Shrikant Dhayje • Edited

try changing this one line

res.clearCookie("jwt");
Enter fullscreen mode Exit fullscreen mode

to two line

res.cookie("jwt");
res.clearCookie("jwt");
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tqbit profile image
tq-bit

Out of curiousity-couldn't you delete that cookie in the frontend once you receive a 200 - logout response?

Collapse
 
curiousdev profile image
CuriousDev • Edited

I had a look and it seems, like you need to use the same options parameter which you have used for setting the cookie.