Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set cookie 'expires' or 'maxAge' in Node.js using Express 3.0

I've been trying to set my cookie's expiry date in Node.js using Express 3.0, but nothing is working.

My first attempt:

res.cookie('user', user, { maxAge: 9000, httpOnly: true });

Just ends in a cookie that has an invalid expiry time according to Chrome. Then I tried to set 'expires' instead, like so:

res.cookie('user', user, { expires: new Date(new Date().getTime()+5*60*1000), httpOnly: true });

And now my cookie is just a session cookie.

Does anyone know how to fix this?

like image 810
skerit Avatar asked Jan 05 '13 21:01

skerit


People also ask

How do cookies expire in Express?

Cookie expire time can be set easily by : res. cookie(name , 'value', {expire : new Date() + 9999}); Addition options for cookies can be set be passing an object as argument which carries additional settings for cookies.

Which property is used to set expiration time of cookies in Express JS?

res. cookie(name, 'value', {expire: 360000 + Date. now()}); Another way to set expiration time is using 'maxAge' property.

How can express set a cookie on the client?

In order to correctly set cookies accessible on the client just use a snippet like the following: res. cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false});

What is maxAge in cookie?

Set the cookie "Max-Age" attribute. A positive value indicates when the cookie should expire relative to the current time. A value of 0 means the cookie should expire immediately. A negative value results in no "Max-Age" attribute in which case the cookie is removed when the browser is closed.


2 Answers

Do note that maxAge is in milliseconds-

res.cookie('jwtToken', token, { maxAge: 2 * 60 * 60 * 1000, httpOnly: true }); // maxAge: 2 hours
like image 110
Varun Kumar Avatar answered Sep 21 '22 18:09

Varun Kumar


You have to use req.session.cookie:

req.session.cookie.expires = false;

req.session.cookie.maxAge = 5 * 60 * 1000;

See also connect docs.

like image 25
asgoth Avatar answered Sep 19 '22 18:09

asgoth