Store user sessions in Redis, implement remember-me tokens, share sessions across multiple app instances.
By default, Express stores sessions in memory. That works for one server. The moment you have two servers behind a load balancer, sessions don't work — requests hit different servers and only one has the session. Redis fixes this.
npm install express-session connect-redis redis
import session from 'express-session';
import RedisStore from 'connect-redis';
import { createClient } from 'redis';
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// Login: store user in session
app.post('/login', async (req, res) => {
const user = await authenticateUser(req.body);
req.session.userId = user.id;
req.session.role = user.role;
res.json({ success: true });
});// For JWTs with revocation support
// Blacklist: store invalidated tokens until they expire
async function logout(token) {
const decoded = jwt.decode(token);
const ttl = decoded.exp - Math.floor(Date.now() / 1000);
if (ttl > 0) {
await redis.setEx(`blacklist:${token}`, ttl, '1');
}
}
async function isTokenBlacklisted(token) {
return await redis.exists(`blacklist:${token}`) === 1;
}connect-redis is the Express session store. One line to switch from memory to Redis.httpOnly: true and secure: true (in prod) on session cookies always.