Session Management Basics with Redis
Tags: redis, backend, webdev
Published: 2023-10-21 22:58:32

#Introduction

Hello guys, recently I have started learning **session management** and **Redis**, which are great option to manage your web application better.

In this article, I'd like to share my insights and the knowledge I've gained so far about session management and Redis, not only to help myself organize what I've learned but also to provide valuable information to others who may be interested in this topic.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s50bjpgrn6o8p6haapma.png)



#Session Management and Redis: What Are They?

**Session management** is crucial for web applications, helping maintain user states for personalized experiences. Using **Redis** for session management offers speed and reliability.

**Redis** is a fast **key-value database** that stores data in memory, providing quick access and scalability.

##Tip: What Is a Session?
A session is a mechanism to maintain user states across a series of requests. It stores information like user login details and shopping cart contents.

##Tip: Key-value Database
A key-value database is a simple and efficient type of database used for storing and retrieving data. In this database, each data element is identified by a <u>unique key</u> and associated value. Keys and values are typically composed of text or binary data, and the key is used to quickly search and retrieve the corresponding value within the database.

Key-value databases are well-suited for applications that require fast read and write access. <u>Common uses include caching, session management, configuration management, and temporary data storage</u>. Key-value databases excel in performance because data resides in memory, allowing for lightning-fast access and enhancing the overall performance of applications.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z78m3m20q2ff507hevet.png)


#Using Redis for Session Management
Redis is used in a variety of scenarios in web development. In this article, below are some examples of combined use of **Express.js** and Redis.

##Session Management
When using Express.js to implement session management, Redis can be used as a session store. In this code example, Redis is introduced at the entry point, allowing the storage of session data in Redis. This enables the sharing of session data among different Express.js applications.

```js
const express = require('express');
const session = require('express-session');
const redis = require('redis');
const connectRedis = require('connect-redis');

const app = express();

const RedisStore = connectRedis(session);
const client = redis.createClient();

app.use(session({
    store: new RedisStore({ client: client }),
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: true,
}));

app.get('/', (req, res) => {
    if (req.session.views) {
        req.session.views++;
    } else {
        req.session.views = 1;
    }
    res.send(`Views: ${req.session.views}`);
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
```

###Tip: Session ID
In Redis, a **session ID** is used to identify sessions. Users can store this ID as a cookie or in URL parameters.

The session ID is stored as a cookie in the client's browser. By default, the session ID is saved in a cookie with the name `connect.sid`. This cookie is used to identify and differentiate sessions between the server and the client.

Here's the code snippet responsible for saving the session ID as a cookie in the client's browser:

```js
app.use(session({
    store: new RedisStore({ client: client }),
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: true,
}));
```

In this part of the code, the express-session middleware sets the session ID as a cookie and sends it to the client's browser. Whenever the client sends a request to the server, the session ID contained in this cookie is used to identify and retrieve the corresponding session data on the server.

While the default cookie name for the session ID is `connect.sid`, you have the flexibility to customize it as needed. If you want to change the cookie name, you can specify it within the options of the session middleware.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqxw8kwyubfvx5cx8ok1.png)


##Bonus: Caching
Redis can be used for purposes other than session management. You can also utilize Redis to **cache data** within your Express.js application. Here is an example of fetching data from a specific endpoint and caching it in Redis.

```js
const express = require('express');
const redis = require('redis');

const app = express();
const client = redis.createClient();

app.get('/data', (req, res) => {
    // Get data from Redis
    client.get('cachedData', (err, cachedData) => {
        if (cachedData) {
            // In case there is data
            res.send(`Cached Data: ${cachedData}`);
        } else {
            // In case that there is no cache, make data
            const newData = 'This is the new data';
            // Cache data to Redis
            client.set('cachedData', newData);
            res.send(`New Data: ${newData}`);
        }
    });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

```

#Conclusion
In this article, I've provided a brief overview of session management and Redis. I had some ideas to write about this topic more - including setting up Redis, etc, but due to time constraints, I'll wrap it up here for today.

I might consider writing a follow-up in the future, but anyways I hope this article has been helpful to you!

Thank you for reading :)