How to implement a remember me feature
persistent cookies, maxAge, remember me checkbox, long-lived session, security tradeoffs, absolute vs sliding expiry, re-authentication for sensitive actions
Persistent vs Session Cookies
A "remember me" checkbox is a request for a persistent cookie. Without it, the session cookie has no expiry and disappears when the browser closes. With it, you set a maxAge so the cookie survives restarts.
app.post('/auth/login', async (req, res) => {
const { email, password, rememberMe } = req.body;
// ... verify credentials ...
req.session.regenerate((err) => {
if (err) return res.status(500).end();
req.session.userId = user.id;
if (rememberMe) {
// 30 days
req.session.cookie.maxAge = 30 * 24 * 60 * 60 * 1000;
} else {
// Session cookie — no maxAge
req.session.cookie.expires = false;
}
res.json({ message: 'Logged in' });
});
});
Security Tradeoffs
Longer sessions mean more time for a stolen cookie to be exploited. Consider absolute expiry (session dies after 30 days regardless of activity) versus sliding expiry (session extends on each use). Absolute expiry is simpler and safer.
For sensitive actions — password change, adding a payment method — always require the user to re-enter their password even if they have an active session. This limits damage from an unattended device.
