Node js Express sessions using Redis

Express session is used as express middleware session for data persistence

Redis is an in-memory data-storage which uses key-value pair

Lets talk about simple example how the whole thing works

Lets think our application is using a load balancer like Nginx

so, when user logged in , our express middleware will create a cookie and session id and stores it in redis storage and cookie is saved in users browser. the cookie saved in browser will be used to identify the redis session

after login, the user will be using the access pages. so here when accessing pages, our express middleware will get the browser cookie and send it to redis to find matching session id. the express session variables can be accessed using req.session objects.

Lets dive to example.

Install redis https://redis.io/download

After installing redis, run redis server and redis client

These files will be in the path of download

Lets run our redis server with the refis.conf file path specified

redis-server.exe redis.windows.conf

Now the redis server is running. it says port 6379. it will be the default port of redis client

Now, run redis client by using redis-cli

Test the client able to communicate with server by entering ping and server will respond with pong

Now enter monitor to see sessions for client request

Here we run a simple app

Now, create a simple nodejs app and install required dependencies

Now, our app server has the express session with port 6379 and running a simple web app on port 3000

When run our app in browser, you can see our monitor redis client app will show the session id and cookie information with access and refresh tokens

If you open the browser you can see the cookie results with cookie name and value which will match session id in redis

Code in my Github: https://github.com/pbndru/phani.redissession

Leave a comment