node.jsmongodbexpresssessionconnect-mongo

How to refer same mongo store from one node app to other app using connect-mongodb-session package


I have two node app projects, where one is for the login authentication server (server_app.js) and another one is dashboard node project (app_dashboard.js). I'm storing sessions in mongodb store collection named sessions.

server_app.js

const mongoDbStore = require('connect-mongodb-session')(session);
const uuidv4 = require('uuid').v4;
const store = new mongoDbStore({
    uri: MONGODB_URI,
    collection: 'sessions'
});
app.use(session({
    secret: uuidv4(),
    cookie: {
        path: '/',
        domain: 'localhost',
    },
    store: store,
    name: 'sid',

}))

Now I'm forwarding session_id to another app after successful login in cookies and I want to refer the same MongoDB store in my session of app_dashboard.js, How do I make it work to refer same mongo store used in server_app.js to validate my sessions?

app_dashboard.js

app.use(session({
    secret: uuidv4(),
    resave: false,
    saveUninitialized: false,
    // name: 'sessionid',
    // store: store
}))

Solution

  • Use the same options for the store and session on both. You'll need to have the same secret for both, so generate a cryptographically secure random string for that and pass it into both via environment variables (process.env).