Managing Node.js - Express Sessions with Redis
If you have ever created a local Node.js / Express application that uses session variables for data persistence (i.e.
req.session), then you have probably used the
express-session library that comes along with most boilerplate Express server configurations.
You may have also noticed that the
express-session docs explicitly state the following:
Warning The default server-side session storage,
MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
If you have never been exposed to production application architecture, then this information might confuse you a bit. It is assuming that we probably have multiple instances of our application running (and perhaps on multiple boxes) under a load balancer like NGINX that is taking some kind of round-robin approach to fulfilling client requests.
With a setup like this, a typical user journey may comprise of the following:
- User A goes to your site and logs in (their request is processed by box One), establishing their user session data.
- They click on the “My Profile” section of your site to go look at their private profile (this request is round-robined and sent to box Two). Access to this feature requires a user to be logged in, and requires the user’s session data for processing.
Whoops! How does box Two know about the session data established on box One so that it can proceed with the request? This is where Redis comes to the rescue.
What Is Redis
Here it is, straight from the horse’s mouth:
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.
In simple terms, it is an open source database technology that uses key-value pairs which are stored in memory. It has the ability to store…