0
0
ExpressHow-ToBeginner · 4 min read

How to Store Session in MongoDB with Express

To store sessions in MongoDB with Express, use the express-session middleware combined with connect-mongodb-session as the session store. This setup saves session data in MongoDB, allowing sessions to persist across server restarts and scale well.
📐

Syntax

Use express-session to handle sessions and connect-mongodb-session to save sessions in MongoDB. You create a MongoDB store instance and pass it to the session middleware.

  • express-session: Middleware to manage sessions in Express.
  • connect-mongodb-session: MongoDB session store for express-session.
  • store: The MongoDB store instance passed to session options.
  • secret: A string to sign the session ID cookie.
  • resave and saveUninitialized: Session behavior flags.
javascript
import express from 'express';
import session from 'express-session';
import connectMongoDBSession from 'connect-mongodb-session';

const app = express();
const MongoDBStore = connectMongoDBSession(session);

const store = new MongoDBStore({
  uri: 'mongodb://localhost:27017/mydatabase',
  collection: 'sessions'
});

app.use(session({
  secret: 'your secret here',
  resave: false,
  saveUninitialized: false,
  store: store
}));
💻

Example

This example shows a simple Express app that stores sessions in MongoDB. It saves a visit count in the session and displays it on the homepage.

javascript
import express from 'express';
import session from 'express-session';
import connectMongoDBSession from 'connect-mongodb-session';

const app = express();
const MongoDBStore = connectMongoDBSession(session);

const store = new MongoDBStore({
  uri: 'mongodb://localhost:27017/mydatabase',
  collection: 'sessions'
});

store.on('error', function(error) {
  console.error('Session store error:', error);
});

app.use(session({
  secret: 'my secret',
  resave: false,
  saveUninitialized: false,
  store: store,
  cookie: { maxAge: 1000 * 60 * 60 } // 1 hour
}));

app.get('/', (req, res) => {
  if (!req.session.views) {
    req.session.views = 1;
  } else {
    req.session.views++;
  }
  res.send(`You visited this page ${req.session.views} times.`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 When visiting http://localhost:3000 multiple times, the page shows: "You visited this page 1 times." "You visited this page 2 times." ... and so on.
⚠️

Common Pitfalls

  • Not installing connect-mongodb-session or express-session properly.
  • Forgetting to handle store errors, which can cause silent failures.
  • Using saveUninitialized: true can create empty sessions unnecessarily.
  • Not setting a proper secret string for session security.
  • Incorrect MongoDB URI or collection name causing connection failures.
javascript
/* Wrong: Missing store causes sessions to be stored in memory (not persistent) */
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: false
}));

/* Right: Use MongoDB store for persistence */
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: false,
  store: store
}));
📊

Quick Reference

  • Install packages: npm install express express-session connect-mongodb-session
  • Import and create MongoDB store with your MongoDB URI and collection.
  • Pass the store to express-session middleware.
  • Set secret, resave, and saveUninitialized properly.
  • Handle store errors to debug connection issues.

Key Takeaways

Use express-session with connect-mongodb-session to store sessions in MongoDB.
Always provide a secure secret and handle store errors.
Set resave and saveUninitialized to false for better session management.
Ensure your MongoDB URI and collection are correct for the session store.
Storing sessions in MongoDB allows persistence and scalability across server restarts.