Distributed Session Management Solutions - Redis Enterprise (2024)

How to use us for session management

Consider a text chat application using MySQL as the relational database, Node.js as the backend server technology, and Redis Enterprise for session management. The frontend is comprised of two pages: a home page, where users log in, and a chat page, in which users type in and send messages.

For the sake of simplicity, we will show only the server code here. It will explain how to implement the session state lifecycle in Node.js. We are also omitting the HTML view pages and the rest of the application.

First, the application loads dependencies, including session, Redis objects, and MySQL client:

var express = require("express");var session = require('express-session');var mysql = required("mysql");var redis = require("redis");var redisStore = require('connect-redis')(session);Var redisClient = redis.createClient();//more dependencies are loaded here....

The declarations above create objects for managing web routing, session, database, caching and session Node.js libraries. Then set up Redis as the session store:

app.use(session({ secret: 'mysecret', // create new redis store. store: new redisStore({ host: 'localhost', port: 6379, client: redisClient }), saveUninitialized: false, resave: false}));

Next, configure the Node.js express routes for the home and chat page, along with support for AJAX requests coming from the client, including login, logout and send comments.

When a user requests the home page, the server redirects them to the chat.html page or displays the login page.html, depending on whether the user is logged in or not. The snippet below shows the handler code for the /get web route:

app.get('/', function (req, res) { // create new session object. if (req.session.key) { // user is already logged in res.redirect('/chat'); } else { // no session found, go to login page res.render("login.html"); }});

When the user submits the login form data (with email and password), the client JavaScript AJAX sends form data to the server. In this example, it calls theexecuteLoginDbCommandfunction (not shown here), which executes a SQL query against the MySQL database and returns an object containing the user’s previously saved session data.

If the login succeeds, the user data coming from MySQL is saved to the web session backed by the Redis session store, and the client JavaScript code redirects the user to the chat page:

app.post('/login', function (req, res) { // SQL Query will compare login and password // from HTTP request body to user table data executeLoginDbCommand(req.body.Email, req.body.Password, function (dbResult) { // if (!dbResult) { res.json({ "success": false, "message": "Login failed ! Please register" }); } else { req.session.key = dbResult; res.json({ "success": true, "message": "Login success." }); } });});

The application chat page lets users read and post messages to other people logged in to the application. Since users see only their own message interactions with others, the data returned by the server for the chat page requests change from user to user. Most importantly, access to this page is restricted to logged-in users. Checking the session key reveals whether the user is logged in or not:

app.get('/chat', function (req, res) { if (req.session.key) { //user is already logged in, //so let's render the chat page with the user email res.render("chat.html", { email: req.session.key["UserEmail"], name: req.session.key["UserName"] }); } else { // no session found, go to login page res.redirect("/"); }});

When the user submits a new comment from the chat page, the client JavaScript AJAX sends form data to the server. If the user is logged in, the comments are inserted in the MySQL UserComments table. We do this by invoking theexecuteSendCommmentDbCommandfunction (not shown here).

app.post("/sendComment", function (req, res) { // This SQL command will insert a new comment in // users table if (req.session.key) { executeSendCommmentDbCommand(req.body.Email, req.body.Recipient, req.body.Comment, function (dbResult) { if (!dbResult) { res.json({ "success": true, "message": "Comment has been sent successfully." }); } else { res.json({ "success": false, "message": "SendComment failed!" }); } }); } else { res.json({ "success": false, "message": "Please login first." }); }});

When the user logs out, the session object is destroyed and the user is redirected to the login page. But first, theexecutePersistSessionDbCommand(not shown here) saves the in-memory user session to the MySQL database:

app.get('/logout', function (req, res) { // user is logged in, so let's destroy the session // and redirect to login page. if (req.session.key) { executePersistSessionDbCommand(req.session, function (dbResult) { if (!dbResult) { req.session.destroy(function () { res.redirect('/'); } else { res.json({ "success": false, "message": "Session persistence failed!" }); } }); }); } else { res.redirect('/'); }});

These snippets only scratch the surface of a real application using Redis as a session store. But they illustrate how Redis can manage in-memory session state lifecycle in combination with permanent database storage like MySQL.

Next steps

Contact us

Try for free

Distributed Session Management Solutions - Redis Enterprise (2024)

References

Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 6100

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.