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);
}
});
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);
}
}
Logout only gives this output :-
And it seems like
res.clearCookie("jwt")
is not working here π
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)
Does this help any?
expressjs.com/en/api.html#res.clea...
try changing this one line
to two line
Out of curiousity-couldn't you delete that cookie in the frontend once you receive a 200 - logout response?
I had a look and it seems, like you need to use the same options parameter which you have used for setting the cookie.