Can't delete cookie in express

18,393

Solution 1

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...

Solution 2

Even though it's not gonna help the author of this question, i hope this might help someone. I run into the same problem that i could not delete cookies in my React app that was using Express api. I used axios, and after a couple of hours i was finally able to fix it.

await axios.post('http://localhost:4000/api/logout', { } , { withCredentials: true })

{ withCredentials: true } is what made it work for me.

This is my Express code:

 const logOutUser = (req, res) => {
  res.clearCookie('username')
  res.clearCookie('logedIn')
  res.status(200).json('User Logged out')
}

Solution 3

Judging by (an extensive) search and a random thought that popped into my head, the answer is to use

res.clearCookie('<token_name>',{path:'/',domain:'<your domain name which is set in the cookie>'});

i.e.

    res.clearCookie('_random_cookie_name',{path:'/',domain:'.awesomedomain.co'}); 

Note the . which is specified in the cookie, because we use it for subdomains (you can use it for subdomains without the dot too, but it's simply safer to use one).

TLDR; You have to provide a route and domain: in the backend, so that the request is made to the same endpoint in the frontend.

Solution 4

Make sure you are sending your credentials to be cleared

Even though it's only a /logout endpoint, you still need to send credentials.

// FRONT END
let logOut = () => {

  fetch('logout', {
    method: 'get',
    credentials: 'include', // <--- YOU NEED THIS LINE
    redirect: "follow"
  }).then(res => {
    console.log(res);
  }).catch(err => {
    console.log(err);
  });

}


// BACK END
app.get('/logout', (req, res) => {
  res.clearCookie('token');
  return res.status(200).redirect('/login');
});
Share:
18,393
Kenny Worden
Author by

Kenny Worden

Updated on June 03, 2022

Comments

  • Kenny Worden
    Kenny Worden almost 2 years

    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.