Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically set the session cookie's expires/maxAge in Express/Node.js?

I'm trying to implement a "remember me" function for my login form. How do most sites do this? I'm assuming most sites dynamically change the session cookie's expires or max-age field when the checkbox is checked.

So, how do I change how long the cookie should last dynamically depending on whether the Remember Me checkbox is selected?

So far I have:

if (req.body.remember)
{
    var thirtyDays = 30*24*60*60*1000;
    req.session.cookie.expires = new Date(Date.now() + thirtyDays);
    req.session.cookie.maxAge = thirtyDays;
}
else
{
    req.session.cookie.expires = false;
    req.session.cookie.maxAge = false;
}

console.log(req.session.cookie.expires, req.session.cookie.maxAge)

This works. But I cannot choose not to remember me; for some reason the cookie last forever. Even after I delete the cookie (in chrome) and login without the remember me field checked, it still last when I close my browser's session, even though it says in the cookies panel in web inspector that it's Session and the console.log is giving me 'false, false'.

I'm obviously doing something wrong. How do I do it right?

Thanks in advance! :)

Edit

Looks like the above code is working, actually. The reason why it appeared as though it wasn't working was because I had the option to re-open the browser tabs when restarting Chrome. This cause Chrome to never delete browser-session cookies, and made me think that setting the cookie's expiry to false didn't make them browser-session cookies.

like image 893
Sam Avatar asked Jul 17 '13 01:07

Sam


People also ask

How do cookies expire in Express?

cookie(name, 'value', {expire: 360000 + Date. now()}); Another way to set expiration time is using 'maxAge' property. Using this property, we can provide relative time instead of absolute time.

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

So, to set expire time to cookies, an object with expire property can be sent which holds the expire time in milliseconds. An alternate approach to set cookie expiration age is to use optional magAge property. res. cookie(name, 'value', {maxAge : 9999});

How do you set an express session cookie?

var cookieSession = require('cookie-session') var express = require('express') var app = express() app. use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })) // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.


1 Answers

According to HTTP cookie's Expires and Max-Age directives, the cookie's expires date can be set to the epoch time (or a date earlier than now) and maxAge to 0:

req.session.cookie.expires = new Date(0);
req.session.cookie.maxAge = 0;
like image 61
yuxhuang Avatar answered Oct 27 '22 21:10

yuxhuang