Storing sessions with connect-mongo in MongoDB.
By: Megh Agarwal
Tags: Expressjs, Nodejs, Sessions, Mongodb

Creating a Node.js application is not that easy when we talk about creating and managing sessions. We need to consider a lot while using sessions, and connect-mongo makes it easier for us to manage sessions. This article is for those who want to manage sessions in Node.js by storing session objects in MongoDB.

Before we go ahead with the coding, let’s discuss: what are sessions? A session is a total time devoted to the activity. In computer systems, a user session begins when a user logs in to or accesses a particular computer, network, or software service. It ends when the user logs out of the service or shuts down the computer. A session can temporarily store information related to the activities of the user while connected. For example, you can store a unique confidential ID through which your applications know that the user with that particular id performs an activity. Now you don’t want to show this personal ID as it can be misused. Instead of storing large and continuously changing information via cookies in the user’s browser, only a unique identifier is stored on the client-side called a session ID. This session id is passed to the web server every time the browser makes an HTTP request. The web application pairs this session id with its internal database and retrieves the stored variables for use by the requested page.

Now, let’s get on to coding.

First, let’s initialize a new project which will be using Node modules.

npm init -y

The above command will generate a package.json file with default values. If you want to add custom values, you can use npm init and add custom values like Author name, License, package name, keywords, Git repository, etc.

We will need express, express-session (for creating sessions.), nodemon (restarts the server automatically when you save a file).

npm i express connect-mongo express-session nodemon

The above command will install all the modules required.

Create a new file called index.js (default main file). We will write our main code for sessions in the index.js file. First, let’s import all of the modules using the require keyword.

const express = require(‘express’);

const session = require(‘express-session’);

const MongoStore = require(‘connect-mongo’)(session);

Now, before using anything, we will have to initialize our app to use express.

const app = express();

app.listen(4000, () => {

console.log(“App listening on port 4000”)

})

We have our basic app ready!

Now, we will have to initialize our session before initializing our session store.

This can be achieved using:

app.use(session(

secret: 'SECRET KEY',

resave: false,

saveUninitialized: true,

))

This will initialize our session with a secret session key and some default operations required when initializing a session in express. If you want to read more on sessions in express, here are the docs: http://expressjs.com/en/resources/middleware/session.html

We will have to initialize the session store by using a simple option ‘store’ in the option.

app.use(session(

secret: 'SECRET KEY',

resave: false,

saveUninitialized: true,

store: new MongoStore({

url: 'mongodb://localhost:27017/test-app', //YOUR MONGODB URL

ttl: 14 * 24 * 60 * 60,

autoRemove: 'native'

})

))

You are good to go! You can replace the URL with your MongoDB URL. The ‘ttl’ basically means Time To Live. This is the expiry time of the session. If the session expires, a new session is to be initialized by the user when logging in. The ‘AutoRemove’ basically means that when the session expires, the document in MongoDB will be removed automatically.

Your session store is ready! Now let’s test if our session store is working. Let’s create a GET request on path ‘/.’ When the user requests this path, a new session will be initialized (This should be done once the user has logged in. This is just a test website).

We can access the session through the ‘req’ variable.

app.get('/', (req,res,next) => {

req.session.user = {

uuid: '12234-2345-2323423'

} //THIS SETS AN OBJECT - 'USER'

req.session.save(err => {

if(err){

console.log(err);

} else {

res.send(req.session.user) // YOU WILL GET THE UUID IN A JSON FORMAT

}

}); //THIS SAVES THE SESSION.

})

If you see it in your MongoDB shell or MongoDB compass. You will see a new collection called ‘Sessions,’ which has a new object with a custom ID. If you want to end the session, we need to create a new GET request with the path ‘/end’ (can be anything you want).

app.get('/end', (req,res,next) => {

req.session.destroy(err => {

if(err){

console.log(err);

} else {

res.send('Session is destroyed')

}

}); //THIS DESTROYES THE SESSION.

})

Here is the whole code.

Link to the repository: Megh-Agarwal/session-store-mongodb