Cannot delete cookie in express

Pretty simple. I set this cookie in my route /user/login:

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 already set my secret for cookie-parser:

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

Pretty simple stuff. Everything works fine, as I can get everything 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 first, so for the argument "Cookie exists!" always writes to my console if the cookie is valid.

The problem is that I am trying to delete a cookie. I tried res.clearCookie('user'), res.cookie('user', '', { expires: new Date() })and I tried passing in the same flags (that I go to res.cookie()in /user/login). I tried using combinations of these methods, but nothing worked.

, cookie ( "Cookie exists!!" ), - . :

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

, cookie;

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

, cookie .

+5
4

, , cookie...

:

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

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

"credentials:" same-origin "" - , clearCookie . cookie , .

, . , ...

+5

,

/logout, .

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

, , - . , React, Express API. axios, .

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

{ withCredentials: true } , .

-:

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

() , ,

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

.

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

Pay attention to . which is indicated in the cookie because we use it for subdomains (you can use it for subdomains without a dot too, but it's just safer to use it).

TL; DR; You must also specify a domain.

0
source

Source: https://habr.com/ru/post/1648980/


All Articles