Express: res.clearCookie() doesn't work

Created on 3 Jun 2011  路  5Comments  路  Source: expressjs/express

res.clearCookie('');

does nothing for me.

I have worked around it by using:
res.cookie('', '', {expires: new Date(1), path: '/' });
instead, as per: http://groups.google.com/group/express-js/browse_thread/thread/3e680630d3b38603

Most helpful comment

For anyone else running into this, it's not just path that has to match. You have to match the domain too.

res.clearCookie('my_cookie', {domain: COOKIE_DOMAIN, path: COOKIE_PATH});

Pretty obvious why if you look at the source impl for clearCookie:

res.clearCookie = function clearCookie(name, options) {
  var opts = merge({ expires: new Date(1), path: '/' }, options);

  return this.cookie(name, '', opts);

All 5 comments

Nevermind, i see that this has been fixed already

The issue is that the cookie must have the same path as before:
res.clearCookie(cookie, {path:'/'});
works fine.

yeah, it's otherwise defaulted to the path (by the browser), I'm tempted to default it, but '/' might not be proper for all servers

Make sure you are actually sending your credentials to the endpoint.

// Front End
let logOut = () => {

  fetch('logout', {
    method: 'get',
    credentials: 'include' // <--- YOU NEED THIS LINE

  }).then(function(response) {
    if (response.redirected) {
      return window.location.replace(response.url);
    }

  }).catch(function(err) {
    console.log(err);
  });
}


// Back End
app.get('/logout', (req, res) => {
  res.clearCookie('token');
  return res.status(200).redirect('/login');
});

For anyone else running into this, it's not just path that has to match. You have to match the domain too.

res.clearCookie('my_cookie', {domain: COOKIE_DOMAIN, path: COOKIE_PATH});

Pretty obvious why if you look at the source impl for clearCookie:

res.clearCookie = function clearCookie(name, options) {
  var opts = merge({ expires: new Date(1), path: '/' }, options);

  return this.cookie(name, '', opts);

Also, Firefox makes you click the refresh icon in the top-right of DeveloperTools->Storage to show that your cookie was deleted. That threw me for a loop.

You'll also need to refresh the page for the cookie to go away (at least in Firefox). If you delete the cookie dynamically using fetch or something, it won't delete until you refresh or navigate away.

Also the difference between 127.0.0.1 and localhost matters, if you're testing locally. If you set the domain property in clearCookie to localhost, it won't clear 127.0.0.1 and vice versa.

Also on Heroku I had to remove domain: 'whatever' from the passed object to get it to recognize that as the cookie and clear it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nove1398 picture nove1398  路  3Comments

despairblue picture despairblue  路  3Comments

Domiii picture Domiii  路  3Comments

guyisra picture guyisra  路  3Comments

haider0324 picture haider0324  路  3Comments