Reputation:
I have an app in express and I have a login form. I need sessions to last for 1 month do I set maxAge to a month in milliseconds.
I left two computers on and logged in for 24 hours and when I came back both were logged out.
How do I fix this/achieve what I'm trying to do? Thanks.
Upvotes: 22
Views: 61068
Reputation: 26189
You can use the expires
attribute instead of maxAge
, which takes a Date object as value. Also, check session cookie expires
on the client after they set. It's always possible that the session was ended by the server (i.e. memcached restarted).
This works for me:
app.use(express.session({
secret: "secret",
store: new MemoryStore(),
expires: new Date(Date.now() + (30 * 24 * 3600 * 1000))
}));
but this also works:
app.use(express.session({
secret: "secret",
store: new MemoryStore(),
maxAge: Date.now() + (30 * 24 * 3600 * 1000)
}));
Upvotes: 13
Reputation: 434
maxAge
means how long the session lasts, in ms;
expires
means when the session gonna expire, ie: a date object
var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)
or
var hour = 3600000
req.session.cookie.maxAge = hour
Upvotes: 16
Reputation: 311
The accepted answer by @Vadim Baryshev is flawed in at least the most recent express-session implementations. When your app starts up you create the session implementation and set the max age. As for the answer using expires, that is not recommended, stick with maxAge.
This means that the maxAge example as written would expire every single session a month after the server starts, and every session created in the future would be expired immediately. Until the server was restarted, there would not be any valid sessions.
Instead of passing a date object, just pass the number of milliseconds to the maxAge property like so:
app.use(
session({
...,
cookie: {
maxAge: 30 * 24 * 60 * 60 * 1000
}
})
);
Upvotes: 31
Reputation: 103
The documentation does not recommend setting cookie.expires directly. Instead, set cookie.maxAge directly.
Express session - cookie.expires
Upvotes: 6
Reputation: 187
app.use(express.session({
secret : 'sdfsdSDFD5sf4rt4egrt4drgsdFSD4e5',
store : new storage({ client : conn, cleanup: false }),
cookie : { maxAge : new Date(Date.now() + (60 * 1000 * 30)) }
}));
Upvotes: -3