DEV Community


Saving Session Data with Connect-Mongo

Full time project engineer, part time student of web development, computer science and the world!
・2 min read

I recently completed a full-stack application using Express-Session to store user sessions, PassportJS authentication with a local strategy, and deployed it to Heroku. However, after a successful deployment I saw the following error:

Warning: connect.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process.

Luckily, I was able to find a helpful github link instructing me how to fix the issue. Instead of using the default MemoryStore to store session data, I needed to find a way to store the data. There are many available session stores listed, and you can choose whatever you like. Since I was already using a Mongo database, I wanted to take advantage and use that to store session data too.

I decided to use the more popular connect-mongo package to connect to my database. After installing the package, I used the existing connection to my database.

My code changes

I was able to connect via mongoose using only a few new lines of code! This is assuming the app is already configured with express-session.

  1. const MongoStore = require('connect-mongo')(session) to add the package in to my app
  2. Add this line to modify my existing app.use to add a store option as follows:
  secret: process.env.SECRET,
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
  1. That's it! There are additional parameters you can pass in, but that's all you need to get it working.

Now, when I login to Mongo Atlas and view my project's database, I can see the session data is stored here too!
My sessions!

For a simple app, this is great for me. In a larger production environment you might want to have a separate database connection for the session data, you can learn to do that in the docs.

Discussion (0)