Destroy cookie NodeJs

While one other answer is correct, deleting a cookie from an express.js webapp is done by invocing the following method:

res.clearCookie("key");

But there's a caveat!

Your cookie options (except expires) need to be the same as when you set it. Otherwise browsers will NOT remove the cookie. So use the same domain, security setting etc. (reference: https://expressjs.com/en/4x/api.html#res.clearCookie)


I'm using this with cookie-parser module:

router.get('/logout', function(req, res){
    cookie = req.cookies;
    for (var prop in cookie) {
        if (!cookie.hasOwnProperty(prop)) {
            continue;
        }    
        res.cookie(prop, '', {expires: new Date(0)});
    }
    res.redirect('/');
});

For webapp you can just set cookie in response as :

res.cookie("key", value);

and to delete cookie : Ref: https://expressjs.com/en/api.html#res.clearCookie

res.clearCookie("key");

and don't forget to:

res.end()

to avoid the web request hanging.


There is no way to delete a cookie according to the HTTP specification. To effectively "delete" a cookie, you set the expiration date to some date in the past. Essentially, this would result in the following for you (according to the cookies module documentation):

cookies.set('testtoken', {maxAge: 0});

Or according to the HTTP specification:

cookies.set('testtoken', {expires: Date.now()});

Both of which should work. You can replace Date.now() with new Date(0) for a really old date.