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



Solution 1:[1]

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 2:[2]

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');
});

Solution 3:[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:[4]

Path needs to be correct. In my case it was a typo in path

Solution 5:[5]

Had a nightmare getting this to work as well this works for me hopefully helps someone.

Express router

router.post('/logout', (req, res) => {
    res.clearCookie('github-token', {
        domain: 'www.example.com',
        path: '/'
    });
    return res.status(200).json({
        status: 'success',
        message: 'Logged out...'
    });
});

React frontend handle logout.

const handleLogout = async () => {
    const logout = await fetch('/logout', {
        method: 'POST',
        credentials: 'include',
    });
    if (logout.status === 200) {
        localStorage.clear();
        alert('Logged out');
    } else {
        alert('Error logging out');
    }
};

I am setting the cookie in my auth call like this.

res.cookie('github-token', token, {
    httpOnly: true,
    domain: 'www.example.com',
    secure: true
});

Import you need to add the path and domain in the clearCookie method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Noob
Solution 2
Solution 3 seanjoyceza
Solution 4 kenodek
Solution 5 user1503606