Use Redis because sessions kept in the Node process memory break as soon as you run more than one instance of the app:
- A request that lands on another instance does not find the session.
- Every restart or deploy logs everyone out.
Redis gives all instances one shared, fast store, and the sessions survive app restarts.
How to structure them:
- Store each session under a key like
sess:<id>, as a JSON string or a hash. - Give the key a TTL (time to live) equal to the idle timeout.
- Refresh the TTL on each activity. This is sliding expiration: the session ends only after the user is idle for the whole timeout.
- Session IDs must be long random values, so nobody can guess them.
- To log a user out, delete the key.
- To log a user out everywhere, keep a set of their session IDs and delete them all.
In Express or NestJS, you usually do this with express-session and connect-redis.
If sessions must survive a Redis restart, turn on Redis persistence (saving data to disk). Otherwise, accept that users must log in again.
- Sessions in process memory fail with multiple instances and are lost on restarts.
- Store one key per session, with a TTL.
- Refresh (slide) the TTL on each activity.
- Delete the key to end a session. Keep a set per user to log them out everywhere.
- Redis persistence decides whether sessions survive a Redis restart.
Read more