Destroy cookie NodeJs - node.js

I am using Cookies module for setting cookie. Here is following my code:
var options = {
maxAge: ALMOST_ONE_HOUR_MS,
domain: '.test.com',
expires: new Date(Date.now() + ALMOST_ONE_HOUR_MS)
};
var value = userInfo.token;
cookies.set("testtoken", value, options);
But in documentation I haven't found how to destroy this cookie.
Any suggestion would be appreciated.

For webapp you can just set cookie in response as :
res.cookie("key", value);
and to delete cookie :
Ref: https://expressjs.com/en/api.html#res.clearCookie
res.clearCookie("key");
and don't forget to:
res.end()
to avoid the web request hanging.

There is no way to delete a cookie according to the HTTP specification. To effectively "delete" a cookie, you set the expiration date to some date in the past. Essentially, this would result in the following for you (according to the cookies module documentation):
cookies.set('testtoken', {maxAge: 0});
Or according to the HTTP specification:
cookies.set('testtoken', {expires: Date.now()});
Both of which should work. You can replace Date.now() with new Date(0) for a really old date.

While one other answer is correct, deleting a cookie from an express.js webapp is done by invocing the following method:
res.clearCookie("key");
But there's a caveat!
Your cookie options (except expires) need to be the same as when you set it. Otherwise browsers will NOT remove the cookie. So use the same domain, security setting etc. (reference: https://expressjs.com/en/4x/api.html#res.clearCookie)

I'm using this with cookie-parser module:
router.get('/logout', function(req, res){
cookie = req.cookies;
for (var prop in cookie) {
if (!cookie.hasOwnProperty(prop)) {
continue;
}
res.cookie(prop, '', {expires: new Date(0)});
}
res.redirect('/');
});

I was going through the same problem a few days ago. After discussing it with a friend, I think this is the best solution.
res.setHeader('set-cookie', 'mycookie=; max-age=0');
Advantages:
only use node
simple to understand
credits: #andy

To delete any http cookie if we just try to clear it from response [using res.clearCookie("key")], it is definitely not going to work. In reality, to delete http cookie, domain and path are very important.
Domain and path define the scope of the cookie. In face, they essentially tell the browser what website the cookie belongs to.
Sending the same cookie value with ; expires appended is also a bad idea since you want the content to be destroyed, but that is not going to happen.
The best idea would be invalidating the cookie by setting the value to empty and include an expires field as well like below:
res.cookie("key","empty the key content", {expires:old date, domain:'.example.com', path:'/'});
res.cookie("token", "", { expires: new Date(0),domain:'.test.com', path: '/' });
Hope this helps!!!

I am using cookie-parser as well, and upper answers lead me to the solution. In my case I needed to add overwrite: true as well, otherwise new cookie key was added.
So my final solution looks like:
res.cookie('cookieName', '', {
domain: 'https://my.domain.com',
maxAge: 0,
overwrite: true,
});

When using in production with SSL, you need to specify the domain. This domain must correspond to the one, which is used to store the cookie!
For example:
res.clearCookie('sid', {domain: ".somedomain"})

create cookie with expires time
res.cookie("keyname", data, {
expires: new Date(Date.now() + 1000 * 60 * 15),
})
Remove cookie
res.clearCookie("key name here");

I have tried all the solutions, and none worked until I found this one.
I set up my cookie like this:
res.writeHead(200, {
"Set-Cookie": `token=${accessToken}; HttpOnly; path=/`,
"Access-Control-Allow-Credentials": "true",
});
res.end();
Then destroyed it like this:
res.writeHead(200, {
"Set-Cookie": `token=; HttpOnly; path=/; max-age=0`,
});
res.end();

Another way to destroying cookies from the server. Just set negative integer as a maxAge. One more thing that keep in mind, don't forget to set a path when will set or destroy cookie.

The Best way to doing this
before you set the like token you should remove that first
like that
res.clearCookie('token');
res.cookie('token',token, { maxAge: 900000, httpOnly: true });

Related

Postman receive cookies with expires: never

I use express to create cookie like this
res.cookie(user[0].email, token, {expire: new Date(Date.now()) + 1200, httpOnly: true})
It works fine when receive cookie from server as well as send cookie in the request. The only problem is that when I open cookies tab in post man it shows the expires is never.
A few things are wrong here.
You're not setting the expiry correctly: the property is named expires.
Using the + operator on Date doesn't add time, it converts to a string and concatenates a number onto the end, which is not what you want.
Check your math. JavaScript date units are typically milliseconds. Do you really want this cookie to expire 1200 milliseconds (1.2 seconds) after it's set?
This will fix the first two points:
res.cookie('abc#d.com', 'foo', { expires: new Date(Date.now() + 1200), httpOnly: true })

Express Session / Cookie maxAge property refreshes on request

Code in app.js
var cookieParser = require("cookie-parser")
var session = require("express-session")
app.use(cookieParser())
app.set('trust proxy', 1)
app.use(session(
{
"name": '***',
"secret": '***',
"cookie": {
"maxAge": null,
"expires": null,
"httpOnly": true,
"secure": true
},
"rolling": false,
"saveUninitialized": false,
"resave": false,
}))
When logging in this end point gets hit
req.session.username = email // defaults to putting something in cookie
req.session.cookie.maxAge = 1000 * 5
req.session.touch()
Test: finding the time left for cookie/session
router.get('/refresh-session', function(req, res){
if (req.session){
console.log(req.session.username)
console.log(req.session.cookie.maxAge)
}
})
My goal is to display a popup to the user in react notifying them that their session is about to expire. I will be refreshing the maxAge every time they navigate to a new page... However, before that I need to find out what the actual current maxAge is. Doing so seems to refresh the maxAge of the cookie. But this maxAge refresh isn't actually effecting the expiration time.
For example:
If maxAge is set to 5 seconds (testing purposes) then calling the method to check the maxAge will consistently be between 4800-5000 millis. However, after the 5 seconds - no matter how many times I refresh - the cookie does expire at 5 seconds (which is intended).
The thing is why id maxAge reseting?
I've looked around and found some unhelpful git pages. Here:
https://github.com/expressjs/session/issues/189#issuecomment-182631933 - doesn't work
https://github.com/expressjs/session/issues/2 - very unhelpful
Anyone run into this issue or can suggest alternatives?
The req.session.cookie.maxAge tells how much time is left in the session. It is reset at end of request to original value. This is documented in the README.md.
Your frontend can not ask the backend for how much of session is still left, because the session is touched at the request. You can set the cookie.maxAge already at the session parameters, no need to postpone until login. Your frontend should keep own timer and reset it at every request to backend.

How can I unstate(delete) and state(create) a cookie in single request in hapijs?

I just want to do two operations in a single request.
1) Delete an older cookie for the entire domain and not just for a given path
2) Create a new cookie for the entire domain, subdomain and ports.
For deleting a cookie,I tried "unstate" but the cookie does not get removed from the browser.
"cookieOptions": {
"ttl": 315569260000,
"isSecure": true,
"isHttpOnly": true,
"isSameSite":false,
"path":"/",
"encoding": "base64json",
"clearInvalid": false, // remove invalid cookies
"strictHeader": true // don't allow violations of RFC 6265
}
sample of cookies options from my config
handler: function (request, reply) {
reply('ok').unstate(“olderCookies”).state(“newCookies”,Config.get('cookieOptions'));
}

Expiring cookies in native NodeJS

I'm trying to expire a cookie with native NodeJS, specifically for the chrome browser. However, the expiration date that I place doesn't cause the cookie to go away.
As of right now, here's my code:
var cookie = 'Expires=' + new Date();
response.setHeader('Set-Cookie', cookie);
I ended up getting cookies with the expiration date like so even after subsequent requests:
cookie: Expires=Wed Mar 22 2017 02:14:52 GMT-0400 (EDT)
You can set cookie expires and httpOnly using the below code.
res.cookie(myCookie, myValue, { expires: new Date(Date.now()+10000), httpOnly: true };
https://expressjs.com/en/api.html#res.cookie
Try This, It may work for you.
'Set-Cookie':'sesh=wakadoo; expires='+new Date(new Date().getTime()+86409000).toUTCString();
Replace sesh=wakadoo with your variable.

Reload a page after res.redirect('back') in route

I'm working on an application which allows you to upload images, and create albums. Everything works fine accept that after an album is created the new album isn't shown in the client until the page is reloaded, and I can't figure out how to solve this.
Below is the route for creating an album. Is it somehow possible to use something else than res.redirect('back') in this case so that the page is reloaded after the route has finished?
Of course I could copy/paste the code from the route for loading the page in the first place, but that would be to much DRY. Maybe I can call the other route from within this route?
route:
app.post('/album', function(req, res){
var newAlbum = new albumModel.Album();
newAlbum.imageName = req.body.albumPicsName;
newAlbum.imageId = req.body.albumPicsId;
newAlbum.title = req.body.albumTitle;
newAlbum.save(function (err) {
if (err) {
console.log(err);
// do something
console.trace();
}
res.redirect('back');
});
});
'back' is an alias for req.get('Referrer') so if '/albums' is your referrer you might still experience issues with the browser returning a 304 (http not modified) http status or a browser cached page (common). If you experience that issue you can do a couple of things:
Send some cache clearing headers:
res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
res.redirect('back');
Or modify the url:
var url = require('url');
var u = url.parse(req.get('Referrer'), true, false);
u.query['v'] = +new Date(); // add versioning to bust cache
delete u.search;
res.redirect(url.format(u));
Of course if you know the url such as '/albums' you don't have to go though all that rigamarole to add some versioning - just append current timestamp to the url string.
The first way is cleaner and works better imo. I've seen cases when a page doesn't have a referrer even though I clearly came from another page due to caching.
You should be able to do res.redirect('/album') instead of back to force a full reload but get the same type of feedback.

Resources