connect-mongo
MongoDB session store for Express and Connect
Last updated 6 years ago by mingchuno .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ npm install connect-mongo 
SYNC missed versions from official npm registry.

connect-mongo

MongoDB session store for Connect and Express

npm version downloads Build Status Coverage Status Dependency Status Greenkeeper badge XO code style

Compatibility

For extended compatibility, see previous versions. This branch is under development. Documentation for latest release please refer to v2.0.3

Usage

Express or Connect integration

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.

Connection to MongoDB

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.

Re-use a Mongoose 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 })
}));

Re-use a native MongoDB driver client (or a promise)

In this case, you just have to give your MongoClient instance to connect-mongo.

/*
** There are many ways to create MongoClient.
** You should refer to the driver documentation.
*/
app.use(session({
    store: new MongoStore({ client: clientInstance })
}));

Or just give a promise...

app.use(session({
    store: new MongoStore({ clientPromise: clientInstancePromise })
}));

Create a new connection from a MongoDB connection string

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://localhost/test-app' })
}));

// Advanced usage
app.use(session({
    store: new MongoStore({
        url: 'mongodb://user12345:foobar@localhost/test-app?authSource=admins&w=1',
        mongoOptions: advancedOptions // See below for details
    })
}));

Events

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

Session expiration

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://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.

Remove expired sessions

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.

Set MongoDB to clean expired sessions (default mode)

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://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!

Set the compatibility mode

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://localhost/test-app',
      autoRemove: 'interval',
      autoRemoveInterval: 10 // In minutes. Default
    })
}));

Disable expired sessions cleaning

You are in production environnement and/or you manage the TTL index elsewhere.

app.use(session({
    store: new MongoStore({
      url: 'mongodb://localhost/test-app',
      autoRemove: 'disabled'
    })
}));

Lazy session update

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://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)

Transparent encryption/decryption of session data

When working with sensitive session data it is recommended to use encryption

const store = new MongoStore({
  url: 'mongodb://localhost/test-app',
  secret: 'squirrel'
})

More options

  • collection Collection (default: sessions)
  • fallbackMemory Fallback to MemoryStore. Useful if you want to use MemoryStore in some case, like in development environment.
  • stringify If true, connect-mongo will serialize sessions using JSON.stringify before setting them, and deserialize them with JSON.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.
  • writeOperationOptions Options object to pass to every MongoDB write operation call that supports it (e.g. update, remove). Useful for adjusting the write concern. Only exception: If autoRemove is set to 'interval', the write concern from the writeOperationOptions object will get overwritten.
  • transformId (optional) Transform original sessionId in whatever you want to use as storage key.

Crypto options

  • secret (optional) Enables transparent crypto in accordance with OWASP session management recommendations.
  • algorithm (optional) Allows for changes to the default symmetric encryption cipher; default is GCM. See crypto.getCiphers() for supported algorithms.
  • hashing (optional) May be used to change the default hashing algorithm; default is sha512. See crypto.getHashes() for supported hashing algorithms.
  • encodeas (optional) Specify to change the session data cipher text encoding. Default is hex.
  • key_size (optional) When using varying algorithms the key size may be used. Default is 32 based on the AES blocksize.
  • iv_size (optional) This can be used to adjust the default IV size if a different algorithm requires a different size. Default is 16.
  • at_size (optional) When using newer AES modes such as the default GCM or CCM an authentication tag size can be defined; default is 16.

Tests

npm test

The tests use a database called connect-mongo-test.

Showcase

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.

License

The MIT License

Current Tags

  • 3.0.0-rc.2                                ...           beta (6 years ago)
  • 5.1.0                                ...           latest (a year ago)
  • 4.4.0-rc1                                ...           next (4 years ago)

67 Versions

  • 5.1.0                                ...           a year ago
  • 5.0.0                                ...           2 years ago
  • 4.6.0                                ...           3 years ago
  • 4.5.0                                ...           3 years ago
  • 4.4.1                                ...           4 years ago
  • 4.4.0                                ...           4 years ago
  • 4.4.0-rc1                                ...           4 years ago
  • 4.3.1                                ...           4 years ago
  • 4.3.0                                ...           4 years ago
  • 4.2.2                                ...           4 years ago
  • 4.2.1 [deprecated]           ...           4 years ago
  • 4.2.0                                ...           4 years ago
  • 4.2.0-rc2                                ...           4 years ago
  • 4.2.0-rc1                                ...           4 years ago
  • 4.1.0                                ...           4 years ago
  • 4.1.0-rc1                                ...           4 years ago
  • 4.0.0-rc2                                ...           4 years ago
  • 4.0.0-rc1                                ...           4 years ago
  • 4.0.0 [deprecated]           ...           4 years ago
  • 3.2.0                                ...           5 years ago
  • 3.1.2                                ...           5 years ago
  • 3.1.1                                ...           5 years ago
  • 3.1.0                                ...           5 years ago
  • 3.0.0                                ...           6 years ago
  • 3.0.0-rc.2                                ...           6 years ago
  • 3.0.0-rc.1                                ...           6 years ago
  • 2.0.3                                ...           6 years ago
  • 2.0.2                                ...           6 years ago
  • 2.0.1                                ...           7 years ago
  • 2.0.0                                ...           7 years ago
  • 1.3.2                                ...           8 years ago
  • 1.3.1                                ...           8 years ago
  • 1.3.0                                ...           8 years ago
  • 1.2.1                                ...           9 years ago
  • 1.2.0                                ...           9 years ago
  • 1.1.0                                ...           9 years ago
  • 1.0.2                                ...           9 years ago
  • 1.0.1                                ...           9 years ago
  • 1.0.0                                ...           9 years ago
  • 1.0.0-beta.1                                ...           9 years ago
  • 0.8.2                                ...           9 years ago
  • 0.8.1                                ...           10 years ago
  • 0.8.0                                ...           10 years ago
  • 0.7.0                                ...           10 years ago
  • 0.6.0                                ...           10 years ago
  • 0.5.3                                ...           10 years ago
  • 0.5.2                                ...           10 years ago
  • 0.5.1                                ...           10 years ago
  • 0.5.0 [deprecated]           ...           10 years ago
  • 0.4.2                                ...           10 years ago
  • 0.4.1                                ...           11 years ago
  • 0.4.0                                ...           11 years ago
  • 0.3.3                                ...           11 years ago
  • 0.3.2                                ...           12 years ago
  • 0.3.1                                ...           12 years ago
  • 0.3.0                                ...           12 years ago
  • 0.2.0                                ...           12 years ago
  • 0.1.9                                ...           13 years ago
  • 0.1.8                                ...           13 years ago
  • 0.1.7                                ...           13 years ago
  • 0.1.6                                ...           13 years ago
  • 0.1.5                                ...           13 years ago
  • 0.1.4                                ...           13 years ago
  • 0.1.3                                ...           13 years ago
  • 0.1.2                                ...           14 years ago
  • 0.1.1                                ...           14 years ago
  • 0.1.0                                ...           14 years ago
Maintainers (2)
Downloads
Total 1
Today 1
This Week 1
This Month 1
Last Day 0
Last Week 0
Last Month 0
Dependencies (1)
Dependents (2)

© 2010 - cnpmjs.org x YWFE | Home | YWFE