Redis Logo

Using Redis with Express in Node

You are probably here to understand how to handle sessions in Node using Redis. I would recommend you to read this article to understand the need to use Redis or Memcache cache to persist session information.

If you are using Windows, then you may also be interested in my article on how to install Redis for Windows. This article assumes you are familiar with the basics of Node.js.

Using Redis with Express in Node

You need to install and import these node modules into the app.js file of your node application.

express-session is the base module which helps  in session management in a node-express app.

Here we are getting an instance of redis, redis store and redis client.

Next we set the config to be used.

By default, the Redis server runs on port 6379. ‘ttl’ is how many seconds you want the session info to be cached in the server.

You then tell your app to use this session and its config.

Setting the session is as simple as this:

req.session.some_key_here = some_value_here;
For example,
req.session.session_info = req.body.email;
Once set this way, the key value pair is stored in the Redis server.
Open your Redis Cli and type KEYS * to see the key Redis used for the above setting.
You can get the value for a specific key using GET “key-name”
Note:
Before starting your node app, you need to run the Redis server as mentioned in my article.