I use express-session together with connect-mongo for storing the sessions in MongoDB. My code looks like this:
var express = require('express');
var session = require('express-session');
var mongoStore = require('connect-mongo')({
session: session
});
var cookieExpiration = 30 * (24 * 60 * 60 * 1000); // 1 month
app.use(session({
// When there is nothing on the session, do not save it
saveUninitialized: false,
// Update session if it changes
resave: true,
// Set cookie
cookie: {
// Unsecure
secure: false,
// Http & https
httpOnly: false,
// Domain of the cookie
domain: 'http://localhost:3001',
// Maximum age of the cookie
maxAge: cookieExpiration
},
// Name of your cookie
name: 'testCookie',
// Secret of your cookie
secret: 'someHugeSecret',
// Store the cookie in mongo
store: new mongoStore({
// Store the cookie in mongo
url: 'mongodb://localhost/databaseName',
// Name of the collection
collection: 'sessions'
})
}));
For all the options of express-sessions, see the docs.
Now you can store all your session data on req.session. Everything you put on your session, will also be saved in the MongoDB. Make also sure you are sending your cookie from your front-end, otherwise your session will always be empty.
MongoDBorRedisstore. There are File stores.