NodeJS + Express + Mongo Session storage NodeJS + Express + Mongo Session storage mongodb mongodb

NodeJS + Express + Mongo Session storage


It ended being a problem of the various modules: connect-session-mongo / express-session-mongo / connect-mongo, using connect 2.0.1 and Express using connect 1.8.5.

Apparently the dependency clash here prevented the session store modules to access the 'req.secret' property.

To make it work I ended using the module connect-mongodb that is still using connect 1.8.5, just like Express.

The reason I couldn't make connect-mongodb work before though was user error, I tried too hard to use copy/paste from online examples instead of my head.

Here is the configuration code that ended up working for me with connect-mongodb:

var Session = require('connect-mongodb');app.configure('production', function(){  var oneWeek = 657450000;  app.use(express.static(__dirname + '/../public', { maxAge: oneWeek }));  var session = express.session({        store: new Session({              url: 'mongodb://localhost:27017/test',               maxAge: 300000        }),        secret: 'superTopSecret'   });  app.use(session);  app.use(mongooseAuth.middleware());  app.use(require('./mySite').middleware());  app.use(express.methodOverride());  app.use(express.errorHandler());  });

Hope this helps anyone else who runs into this issue. If you have any suggestion/improvement on this solution, I'd be glad to hear it. :)


const express = require('express')const app = express()const cookieParser = require('cookie-parser');const session = require('express-session')const mongoose = require('mongoose');const MongoStore = require('connect-mongo')(session);mongoose.connect('mongodb://localhost/my-database', {    useMongoClient: true});mongoose.Promise = global.Promise;const db = mongoose.connectionapp.use(cookieParser());app.use(session({    secret: 'my-secret',    resave: false,    saveUninitialized: true,    store: new MongoStore({ mongooseConnection: db })}));