Skip to content
Advertisement

Can’t delete cookie in express

Pretty simple. I set a cookie like so in my /user/login route:

if (rememberMe) {
    console.log('Login will remembered.');
    res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' });
}
else {
    console.log('Login will NOT be remembered.');
}

I’ve already set my secret for cookie-parser:

app.use(cookieParser('shhh!'));

Pretty basic stuff. Everything is working great insofar as I’m able to retrieve whatever I stored in the cookie:

app.use(function (req, res, next) {
    if (req.signedCookies.user) {
        console.log('Cookie exists!');
        req.session.user = req.signedCookies.user;
    }
    else {
        console.log('No cookie found.');
    }

    next();
});

This middleware is called before anything else, so for the sake of the argument “Cookie exists!” is always logged in my console if the cookie is valid.

The problem is when I try to delete the cookie. I’ve tried res.clearCookie('user'), res.cookie('user', '', { expires: new Date() }), and I’ve tried passing in the same flags (that I pass to res.cookie() in /user/login). I’ve attempted to use combinations of these methods, but nothing has worked.

Currently, the only way I am able to clear the cookie (and not receive the “Cookie exists!” log message) is by clearing my browser history. Here is what my logout route looks like:

route.get('/user/logout', function (req, res, next) {
    res.clearCookie('user');
    req.session.destroy();
    util.response.ok(res, 'Successfully logged out.');
});

It seems as though I can’t even modify the cookie value; I put

res.cookie('user', {}, { signed: true, httpOnly: true, path: '/' })

in my logout route, but the cookie value remains unchanged.

Advertisement

Answer

I realized after a long and annoying time that my front end was not sending the cookie to the end point were I was trying to clear the cookie…

On the server:

function logout(req, res) {
  res.clearCookie('mlcl');
  return res.sendStatus(200);
}

And on the front end,

fetch('/logout', { method: 'POST', credentials: 'same-origin' })

adding the “credentials: ‘same-origin'” is what made the clearCookie work for me. If the cookie is not being sent, it has nothing to clear.

I hope this helps. I wish I had found this earlier…

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement