DEV Community

Cover image for Session Management Basics with Redis
koshirok096
koshirok096

Posted on

Session Management Basics with Redis

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

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 unique key 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. Common uses include caching, session management, configuration management, and temporary data storage. 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

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.



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');
});


Enter fullscreen mode Exit fullscreen mode

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:



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


Enter fullscreen mode Exit fullscreen mode

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

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.



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: </span><span class="p">${</span><span class="nx">cachedData</span><span class="p">}</span><span class="s2">);
} 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: </span><span class="p">${</span><span class="nx">newData</span><span class="p">}</span><span class="s2">);
}
});
});

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

Enter fullscreen mode Exit fullscreen mode




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 :)

Top comments (1)

Collapse
 
benedettodev profile image
Benedetto Proietti

I am curious whether a SQL way to access Redis data would be beneficial in this case.
Specifically I am referring to Memurai SQL, an open-source Redis module that allows to create and query secondary indexes with SQL.