MongoDB session store for Connect and Express
- Support Express up to
5.0
- Support all Connect versions
- Support Mongoose
>= 4.1.2+
- Support native MongoDB driver
>= 2.0.36
- Support Node.js 4, 6 and 8
- Support MongoDB
>= 3.0
For extended compatibility, see previous versions.
Express 4.x
, 5.0
and Connect 3.x
:
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
app.use(session({
secret: 'foo',
store: new MongoStore(options)
}));
Express 2.x
, 3.x
and Connect 1.x
, 2.x
:
const MongoStore = require('connect-mongo')(express);
app.use(express.session({
secret: 'foo',
store: new MongoStore(options)
}));
For Connect 1.x
and 2.x
, just replace express
by connect
.
In many circumstances, connect-mongo
will not be the only part of your application which need a connection to a MongoDB database. It could be interesting to re-use an existing connection.
Alternatively, you can configure connect-mongo
to establish a new connection.
const mongoose = require('mongoose');
// Basic usage
mongoose.connect(connectionOptions);
app.use(session({
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
// Advanced usage
const connection = mongoose.createConnection(connectionOptions);
app.use(session({
store: new MongoStore({ mongooseConnection: connection })
}));
In this case, you just have to give your Db
instance to connect-mongo
.
If the connection is not opened, connect-mongo
will do it for you.
/*
** There are many ways to create dbInstance.
** You should refer to the driver documentation.
*/
app.use(session({
store: new MongoStore({ db: dbInstance })
}));
Or just give a promise...
app.use(session({
store: new MongoStore({ dbPromise: dbInstancePromise })
}));
MongoDB connection strings are the best way to configure a new connection. For advanced usage, more options can be configured with mongoOptions
property.
// Basic usage
app.use(session({
store: new MongoStore({ url: 'mongodb:https://localhost/test-app' })
}));
// Advanced usage
app.use(session({
store: new MongoStore({
url: 'mongodb:https://user12345:foobar@localhost/test-app?authSource=admins&w=1',
mongoOptions: advancedOptions // See below for details
})
}));
A MongoStore
instance will emit the following events:
Event name | Description | Payload |
---|---|---|
create |
A session has been created | sessionId |
touch |
A session has been touched (but not modified) | sessionId |
update |
A session has been updated | sessionId |
set |
A session has been created OR updated (for compatibility purpose) | sessionId |
destroy |
A session has been destroyed | sessionId |
When the session cookie has an expiration date, connect-mongo
will use it.
Otherwise, it will create a new one, using ttl
option.
app.use(session({
store: new MongoStore({
url: 'mongodb:https://localhost/test-app',
ttl: 14 * 24 * 60 * 60 // = 14 days. Default
})
}));
Note: Each time an user interacts with the server, its session expiration date is refreshed.
By default, connect-mongo
uses MongoDB's TTL collection feature (2.2+) to have mongod automatically remove expired sessions. But you can change this behavior.
connect-mongo
will create a TTL index for you at startup. You MUST have MongoDB 2.2+ and administration permissions.
app.use(session({
store: new MongoStore({
url: 'mongodb:https://localhost/test-app',
autoRemove: 'native' // Default
})
}));
Note: If you use connect-mongo
in a very concurrent environment, you should avoid this mode and prefer setting the index yourself, once!
You have an older MongoDB version (compatible with connect-mongo) or you can't or don't want to create a TTL index.
connect-mongo
will take care of removing expired sessions, using defined interval.
app.use(session({
store: new MongoStore({
url: 'mongodb:https://localhost/test-app',
autoRemove: 'interval',
autoRemoveInterval: 10 // In minutes. Default
})
}));
You are in production environnement and/or you manage the TTL index elsewhere.
app.use(session({
store: new MongoStore({
url: 'mongodb:https://localhost/test-app',
autoRemove: 'disabled'
})
}));
If you are using express-session >= 1.10.0 and don't want to resave all the session on database every single time that the user refresh the page, you can lazy update the session, by limiting a period of time.
app.use(express.session({
secret: 'keyboard cat',
saveUninitialized: false, // don't create session until something stored
resave: false, //don't save session if unmodified
store: new MongoStore({
url: 'mongodb:https://localhost/test-app',
touchAfter: 24 * 3600 // time period in seconds
})
}));
by doing this, setting touchAfter: 24 * 3600
you are saying to the session be updated only one time in a period of 24 hours, does not matter how many request's are made (with the exception of those that change something on the session data)
collection
Collection (default:sessions
)fallbackMemory
Fallback toMemoryStore
. Useful if you want to use MemoryStore in some case, like in development environment.stringify
If true, connect-mongo will serialize sessions usingJSON.stringify
before setting them, and deserialize them withJSON.parse
when getting them. (optional, default: true). This is useful if you are using types that MongoDB doesn't support.serialize
Custom hook for serializing sessions to MongoDB. This is helpful if you need to modify the session before writing it out.unserialize
Custom hook for unserializing sessions from MongoDB. This can be used in scenarios where you need to support different types of serializations (e.g., objects and JSON strings) or need to modify the session before using it in your app.transformId
(optional) Transform original sessionId in whatever you want to use as storage key.
npm test
The tests use a database called connect-mongo-test
.
Open source projects and production apps using connect-mongo
. Feel free to add yours in a pull request.
- Builder Book: Open source web app to write and host documentation or sell books. Built with React, Material-UI, Next, Express, Mongoose, MongoDB.
The MIT License