I know this is an old question but I'm adding an answer since all answers here seem to be either outdated, have security flaws or are just plain wrong.
As of now, express uses the MemoryStore
by default, you don't need to explicitly handle that.
Also, as of now, the express-session's official readme page has a stark warning at the beginning to not use MemoryStore
as the session store for production, quoting:
Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
For a list of stores, see compatible session stores.
Here's a simple solution with connect-mongodb-session
if you want to use MongoDBStore for session storage:
import express from 'express';
import session from 'express-session';
import ConnectMongoDbSession from 'connect-mongodb-session';
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
secret: < COOKIE_SECRET >,
name: 'sessionId', // Don't use the default name, see http://expressjs.com/en/advanced/best-practice-security.html
cookie: {
httpOnly: true,
secure: true, // Remove this if you're not using HTTPS, but it will be a massive security flaw
sameSite: 'strict',
},
store: getStore(),
// Boilerplate options, see:
// * https://www.npmjs.com/package/express-session#resave
// * https://www.npmjs.com/package/express-session#saveuninitialized
resave: true,
saveUninitialized: true,
}));
function getStore() {
const MongoDBStore = ConnectMongoDbSession(session);
const store = new MongoDBStore({
uri: < DATABASE_URI >,
collection: < SESSION_COLLECTION_NAME >,
connectionOptions: {
useNewUrlParser: true,
useUnifiedTopology: true,
},
});
store.on('error', (error: any) => {
console.error(error);
});
return store;
}