Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Session Management In Your Express.js Web Application

TwitterFacebookRedditLinkedInHacker News

I’ve still been doing a lot of fiddling with Express web framework for Node.js. I recently ran into an issue with saving data to sessions because much of the documentation online is outdated and no longer functional. However, I did get it working, and am going to discuss it in this guide.

If you’re not familiar with Express, you may want to take a moment and read my other article regarding installation.

As of right now we are currently on Express version 4.11.0. To manage our sessions we’re going to be using the express-session middleware.

The first thing you want to do is create a fresh Express project, preferably on your Desktop:

express MySessionProject
cd MySessionProject
npm install

We now have a baseline project, but with no session management. To install the express-session middleware, run the following from your Terminal or command prompt:

npm install express-session --save

Notice that I used the --save attribute because I want it to automatically add the package to our dependency list for any future re-deployment.

With the package installed, we need to open our app.js file and include a few things so that way we can use it in our project:

var express = require('express');
var path = require('path');
var fs = require("fs");
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require("express-session");

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({resave: true, saveUninitialized: true, secret: 'SOMERANDOMSECRETHERE', cookie: { maxAge: 60000 }}));
app.use(express.static(path.join(__dirname, 'public')));

The above code is not my complete app.js file, but only the top part instead. We included the package in our project and then constructed it. By adding a secret we get get a little more security in the things that we store.

So how do we go about using sessions now that they are included in our project? That is easy!

Inside one of your routes, your sessions can be set and obtained from the req.session variable:

app.get("/", function(req, res) {
    req.session.fullname = "Nic Raboy";
    res.render("index", { title: "Express" });
});

Just like that your session has been set, and it can be obtained the same way.

However, this is where I started banging my head because it wasn’t working as expected. I was using Mongoose in my project to get data from my MongoDB database. The goal was to sign in and get the user id to store in a session. The problem was, that my sessions were not being set partially because of the callback function included with Mongoose.

app.get("/login", function(req, res) {
    UserModel.findOne({username: "nraboy"}, function(error, user) {
        if(error) {
            console.error(error);
            return;
        }
        req.session.userId = user.id;
        res.render("user/login", { title: "Login" });
    });
});

Ignore the simplicity of the login route above. It is also alright if you don’t understand Mongoose. What is important is that the res.render is included inside the callback method. Previously, I was setting the session inside the callback, but rendering outside. Because this is asynchronous, the render was happening first, invalidating the session save.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.