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! :)
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.
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.
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});
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.
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;
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