DEV Community

Monica
Monica

Posted on

2 2

Saving Session Data with Connect-Mongo

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:
app.use(session({
  secret: process.env.SECRET,
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
}))
Enter fullscreen mode Exit fullscreen mode
  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.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (1)

Collapse
 
aishtiaq7 profile image
Awshaf Ishtiaque

Did you need to create a cluster for storing the sessions in your mongoddb?
Also I use Mongodb Compass, is that the same thing as Atlas?

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay