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 forexpress-session.store: The MongoDB store instance passed to session options.secret: A string to sign the session ID cookie.resaveandsaveUninitialized: 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-sessionorexpress-sessionproperly. - Forgetting to handle store errors, which can cause silent failures.
- Using
saveUninitialized: truecan create empty sessions unnecessarily. - Not setting a proper
secretstring 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-sessionmiddleware. - Set
secret,resave, andsaveUninitializedproperly. - 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.