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.
To delete a cookie, use the clearCookie function. For example, if you need to clear a cookie named foo, use the following code. var express = require('express'); var app = express(); app. get('/clear_cookie_foo', function(req, res){ res.
The res. clearCookie() function is used to clear the cookie specified by name. This function is called for clearing the cookies which as already been set. For example if a user cookie is set, then it can be cleared using this function.
Note that a cookie created via HTTP with the httponly attribute cannot be deleted using the JavaScript API.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With