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

12,506

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;
Share:
12,506
Sam
Author by

Sam

Updated on June 22, 2022

Comments

  • Sam
    Sam almost 2 years

    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.