HTTP and HTTPS are internet protocols that allow data to be sent over the internet by sending a request via a web browser. Because they are stateless, each request sent to the browser is treated independently. This means that the browser cannot remember the source of a request, even if the same user makes it. HTTP sessions solve this problem.
This article will look at session management and how tools like Passport, Redis, and MySQL can help us manage Node.js sessions. Let’s dive in.
How do HTTP sessions work?
HTTP sessions allow web servers to maintain user identity and store user-specific data across multiple request/response interactions between a client app and a web app. When a client logs into the application, the server generates a SessionID. The session is saved in memory using a single-server, non-replicated persistent storage mechanism. Examples of such mechanisms include JDBC persistence, file system persistence, cookie-based session persistence, and in-memory replication. When the user sends a subsequent request, the sessionID is passed in the request header, and the browser checks if the ID matches any on in the memory storage and grants the user access until the session expires.
HTTP sessions store the following data in memory:
- Specifics about the session (session identifier, creation time, time last accessed, etc.)
- Contextual information about the user (for example, client login status)
What is Redis?
Redis (Remote Dictionary Server) is a fast, open-source, in-memory key-value data store used as a database, cache, message broker, and queue.
Redis has sub-millisecond response times, allowing millions of requests per second for real-time applications in industries such as gaming, ad-tech, finance, healthcare, and IoT. As a result, Redis is now one of the most popular open-source engines, having been named the "Most Loved" database by Stack Overflow five years in a row. Due to its fast performance, Redis is a popular choice for caching, session management, gaming, leaderboards, real-time analytics, geospatial, ride-hailing, chat/messaging, media streaming, and pub/sub-apps.
What are we building?
To demonstrate session management in Node.js, we will create simple signup and sign-in application. Users will sign up for and sign in to this application by providing their email address and password. A session is created and saved in the Redis store for future requests when a user signs in. When a user logs out, we will delete their session. Enough talking; let's get started!
This tutorial is a hands-on demonstration. Ensure you have the following installed before getting started:
The code for this tutorial is available on my Github repository. Feel to clone and follow along.
Let’s start by creating a project folder for the application with the command below:
Then, initialize a Node.js application to create a package.json file with the command below:
-y flag in the above command tells npm to use the default configuration. Now create the following folder structure in your project root directory.
┃ ┣ 📂controllers
┃ ┃ ┗ 📜index.js
┃ ┣ 📂models
┃ ┃ ┗ 📜index.js
┃ ┣ 📂routes
┃ ┃ ┗ 📜index.js
┃ ┣ 📂utils
┃ ┃ ┗ 📜passport.js
┃ ┗ 📜server.js
┃ ┣ 📂auth
┃ ┃ ┣ 📜login.ejs
┃ ┃ ┗ 📜register.ejs
┃ ┗ 📜home.ejs
With our package.json created, let’s install the required package for this project in the next section.
We’ll install the following dependencies for our application:
- Bcryptjs - This module will be used to hash the user’s password.
- Connect-redis - This module will provide Redis session storage for Express.
- Express-session - This module will be used to create sessions.
- Ejs - This module is our template engine
- Passport - This module will be used for user’s authentication
- Passport-local - This module will be used for local username and password authentication
- Sequelize - This module is our MySQL ORM to connect our application to MySQL database.
- Dotenv - This module will be used to load our environment variables.
Use the command below to install all the required dependencies.
Wait for the installation to finish. Once the installation is complete, proceed with setting up the MySQL database in the next section.
Setting up MySQL Database
We’ll create a MySQL database for our application. But before that, run the command below to create a MySQL user account.
Now create a database session_db, and grant the newuser access to the database with the command below:
Now reload all the privileges with the command below:
With our MySQL database setup, let's create our
users database model in the next section.
Create Express Server
With our MySQL database setup, let's create an express server for our application. Open the src/server.js file and add the code snippet below:
In the above code snippet, we create an express server, which will listen to requests on Port 4300. Then, we parse the incoming requests with JSON payloads using the
express.json() middleware and parse incoming requests with
Create the database model
At this point, our Express server is set. Now we'll create a
Users model to represent the user data we'll see the database using
Sequelize. Open the
src/models/index.js file and add the code snippet below.
In the above code snippet, we import
sequelize to connect to our MySQL database and assign a data type to our model properties. Then, we connect to MySQL by creating a
sequelize instance from the
Sequelize class and passing in our database credentials. For example, with the
sequelize instance, we defined our model and its properties. We only want this tutorial's id, email, and password fields. But sequelize creates two additional fields, the
Setup Passport and Redis
To handle and store our user's credentials, we'll use and configure
Redis. To do that, open the
src/index.js file and import the following dependencies below:
Then, locate the area commented
//Redis configurations and add the code snippet below:
In the above code snippet, we established a connection to our database, which will manage our user's username data.
Next, locate the area commented
//Commented session middleware and add the code snippet below:
In the above code snippet, we created a
SESSION_SECRET variable in a
.env file to hold our session secret, then created a session middleware and used Redis as our store. For the session to work we add two more middlewares the
Create application controllers
With our Redis and express session setup, we'll create a route to handle users' information. To do that, open the
src/controllers/index.js file and add the code snippet below:
In the above code snippet, we import
bcrypt and our
User model, we destructure the user's
password from the
req.body object. Then we hashed the password using bcrypt and create a new user using the
sequelize create method.
Next, create a
login page with the code snippet below:
HomePage, we’ll render some of the authenticated user’s details alongside the
Finally, create the
logout route, to delete the user's username data with the code snippet below:
Create the Passport strategy
At this point, users can register, log in, and log out of our application. Now, let's create the passport strategy to authenticate the users and create a session. To do that, open the
src/utils/passport.js file, and add the code snippet below:
In the above code snippet we import
bcrypt, and our User model, and we create a passport middleware to use the
local-strategy. Then we rename the default file name to the field names (
password) we are using to authenticate the users. Now, we check if the user details exist in the database before a session can be created for them.
passport.deserialize commands are used to persist the users id as a cookie in the user's browser and to retrieve the id from the cookie when necessary, which is then used to retrieve user information in a callback.
done() function is an internal
passport.js function that takes the user id as the second parameter.
Create the application routes
With our passport strategy created, let’s proceed with creating routes for our controllers. To do that, open the
src/routes/index.js file and add the following code snippet below:
In the above code snippet, we import our controller functions and created a route for them. For the
signin route, we used the
passport.authenticate method to authenticate the users using the
local strategy in setup in the previous section.
Now back to our
server.js file, we’ll create a middleware for our routes. Before that, we need to import our
router and the
Then, we’ll call the
passportConfig function right below the code in the areas commented
//Configure session middleware.
Then, we’ll create our route middleware right after the area commented
Create our application views
With our routes created, we’ll create views rendered in our
RegisterPage controllers. Before that, we'll set up our ejs view engine in the server.js file with a code snippet below right below the area commented
Then, we’ll start with the home page, open the
views/home.ejs file and add the following markup.
Here in our home page, we used bootstrap to add some styling to our markups. Then we check if the user is authenticated to show the logout button. Also we display the user’s
ExpirationTime from the backend.
Next, open the
src/views/auth/resgister and add the following markup below for the register page.
In the register page, we created an html form to accept the users details. In the form, we also add the active attribute and specify the signup endpoint. This means that when a user clicks on the submit button, a request will be sent to the
Finally, open the
src/views/auth/signin.js file, and add the following markup snippet below:
In the above markup, we added an html form that willl be used login a user by sending a request to the
View users' data with Arctype
We have now successfully created a Node.js session management application. Let's look at the users' data with Arctype. To begin, launch Arctype, click the MySQL tab, and enter the following MySQL credentials, as shown in the screenshot below:
Then, click on the
users table to show the registered users as shown in the screenshot below:
By building a demo login application, we've learned how to implement session management in Node.js using Passport and Redis. We started with the introduction of HTTP sessions and how they work, then we looked at what Redis is, and created a project to put all this into practice. Now that you have the knowledge you seek, how would you authenticate users' projects?