Package detail

connect-mongo

jdesboeufs538.3kMIT5.1.0

MongoDB session store for Express and Connect

connect, mongo, mongodb, session

readme

connect-mongo

MongoDB session store for Connect and Express written in Typescript.

npm version downloads Sanity check Coverage Status

Breaking change in V4 and rewritten the whole project using Typescript. Please checkout the migration guide and changelog for details.

Install

npm install connect-mongo
yarn add connect-mongo
  • You may also need to run install mongodb if you do not have it installed already because mongodb is not a peerDependencies instead.
  • If you are upgrading from v3.x to v4, please checkout the migration guide for details.
  • If you are upgrading v4.x to latest version, you may check the example and options for details.

Compatibility

For extended compatibility, see previous versions v3.x. But please note that we are not maintaining v3.x anymore.

Usage

Express or Connect integration

Express 4.x, 5.0 and Connect 3.x:

const session = require('express-session');
const MongoStore = require('connect-mongo');

app.use(session({
  secret: 'foo',
  store: MongoStore.create(options)
}));
import session from 'express-session'
import MongoStore from 'connect-mongo'

app.use(session({
  secret: 'foo',
  store: MongoStore.create(options)
}));

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.

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: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
}));

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

Re-use an existing native MongoDB driver client 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.
*/

// Database name present in the connection string will be used
app.use(session({
  store: MongoStore.create({ clientPromise })
}));

// Explicitly specifying database name
app.use(session({
  store: MongoStore.create({
    clientPromise,
    dbName: 'test-app'
  })
}));

Known issues

Known issues in GitHub Issues page.

Native autoRemove causing error on close

  • Calling close() immediately after creating the session store may cause error when the async index creation is in process when autoRemove: 'native'. You may want to manually manage the autoRemove index. #413

MongoError exports circular dependency

The following error can be safely ignored from official reply.

(node:16580) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)

Existing encrypted v3.2.0 sessions are not decrypted correctly by v4

v4 cannot decrypt the session encrypted from v3.2 due to a bug. Please take a look on this issue for possible workaround. #420

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 manually 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: MongoStore.create({
    mongoUrl: 'mongodb://localhost/test-app',
    ttl: 14 * 24 * 60 * 60 // = 14 days. Default
  })
}));

Note: Each time a 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 mongodb 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: MongoStore.create({
    mongoUrl: '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

In some cases you can't or don't want to create a TTL index, e.g. Azure Cosmos DB.

connect-mongo will take care of removing expired sessions, using defined interval.

app.use(session({
  store: MongoStore.create({
    mongoUrl: '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: MongoStore.create({
    mongoUrl: '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 refreshes 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: MongoStore.create({
    mongoUrl: '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 = MongoStore.create({
  mongoUrl: 'mongodb://localhost/test-app',
  crypto: {
    secret: 'squirrel'
  }
})

Options

Connection-related options (required)

One of the following options should be provided. If more than one option are provided, each option will take precedence over others according to priority.

Priority Option Description
1 mongoUrl A connection string for creating a new MongoClient connection. If database name is not present in the connection string, database name should be provided using dbName option.
2 clientPromise A Promise that is resolved with MongoClient connection. If the connection was established without database name being present in the connection string, database name should be provided using dbName option.
3 client An existing MongoClient connection. If the connection was established without database name being present in the connection string, database name should be provided using dbName option.

More options

Option Default Description
mongoOptions { useUnifiedTopology: true } Options object for MongoClient.connect() method. Can be used with mongoUrl option.
dbName A name of database used for storing sessions. Can be used with mongoUrl, or clientPromise options. Takes precedence over database name present in the connection string.
collectionName 'sessions' A name of collection used for storing sessions.
ttl 1209600 The maximum lifetime (in seconds) of the session which will be used to set session.cookie.expires if it is not yet set. Default is 14 days.
autoRemove 'native' Behavior for removing expired sessions. Possible values: 'native', 'interval' and 'disabled'.
autoRemoveInterval 10 Interval (in minutes) used when autoRemove option is set to interval.
touchAfter 0 Interval (in seconds) between session updates.
stringify true If true, connect-mongo will serialize sessions using JSON.stringify before setting them, and deserialize them with JSON.parse when getting them. 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 Transform original sessionId in whatever you want to use as storage key.
crypto Crypto related options. See below.

Crypto-related options

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

Development

yarn install
docker-compose up -d
# Run these 2 lines in 2 shell
yarn watch:build
yarn watch:test

Example application

yarn link
cd example
yarn link "connect-mongo"
yarn install
yarn start

Release

Since I cannot access the setting page. I can only do it manually.

  1. Bump version, update CHANGELOG.md and README. Commit and push.
  2. Run yarn build && yarn test && npm publish
  3. git tag vX.Y.Z && git push --tags

License

The MIT License

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased]

[5.1.0] - 2023-10-14

Changed

  • Extend mongodb peer dependency allowed versions to 6.x
  • Upgrade dependency

[5.0.0] - 2023-03-14

BREAKING CHANGES

  • Upgraded peer dependency mongodb to 5.0.0
  • Change engines to require Node 12.9 or newer, matching the upgrade to mongodb that occurred in v4.5.0

Fixed

  • Declare express-session as a peer dependency.

[4.6.0] - 2021-09-17

Changed

  • Moved mongodb to a peer dependency (and also as a dev dependency for connect-mongo developers). connect-mongo is no longer pinned to a specific version of mongodb. This allows end users to avoid errors due to Typescript definition changes when moving to new versions of mongodb. Users can use any version of mongodb that provides a compatible (non-breaking) interface to mongodb ^4.1.0. Tested on mongodb 4.1.0 and 4.1.1. Should fix: #433 #434 #436

Fixed

  • Fixed "Callback was already called" when some code throws immediately after calling the set function

[4.5.0] - 2021-08-17

BREAKING CHANGES

  • Drop Node 10 support

Changed

  • Upgrade mongodb to V4 [#422] [#426]

Fixed

  • Move writeConcern away from top-level option to fix deprecation warning #422

[4.4.1] - 2021-03-23

Fixed

  • store.all() method not working with encrypted store #410 #411
  • Update and unpin mongodb dependency due to upstream fix has been deployed #409

[4.4.0] - 2021-03-11

BREAKING CHANGES

  • Use export = for better cjs require without .default

Added

  • Add typescript example

[4.3.1] - 2021-03-09

Fixed

  • Fix incorrect assertion checking after adding client options

[4.3.0] - 2021-03-08

Added

  • Add client option for non-promise client

[4.2.2] - 2021-03-02

Fixed

  • Fix crypto parsing error by upgrading kruptein to v3.0.0 and change encodeas to base64

[4.2.0] - 2021-02-24

Added

  • Added mongoose example
  • Revert createAutoRemoveIdx and add back autoRemove and autoRemoveInterval

Fixed

  • Use matchedCount instead of modifiedCount to avoid throwing exceptions when nothing to modify #390
  • Fixed Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency by downgrade to mongodb@3.6.3
  • Revert update session when touch #351
  • Fix cannot read property lastModified of null
  • Fix TS typing error

[4.1.0] - 2021-02-22

BREAKING CHANGES

  • Support Node.Js 10.x, 12.x and 14.x and drop older support.
  • Review method to connect to MongoDB and keep only mongoUrl and clientPromise options.
  • Remove the "Remove expired sessions compatibility mode". Now library user can choose to create auto remove index on startup or not.
  • Remove fallbackMemory options.
  • Rewrite the library and test case using typescript.

Checkout the complete migration guide for more details.

[3.2.0] - 2019-11-29

Added

  • Add dbName option (#343)

Fixed

  • Add missing secret option to TS definition (#342)

[3.1.2] - 2019-11-01

Fixed

  • Add @types/ dev dependencies for tsc. fixes #340 (#341)

[3.1.1] - 2019-10-30

Added

  • Add TS type definition

[3.1.0] - 2019-10-23

Added

  • Added useUnifiedTopology=true to mongo options

Changed

  • Refactor merge config logic
  • chore: update depns (#326)

[3.0.0] - 2019-06-17

BREAKING CHANGES

  • Drop Node.js 4 & 6 support
  • Upgrade mongoose to v5 and mongodb to v3 and drop old version support
  • Replace deprecated mongo operation
  • MongoStore need to supply client/clientPromise instead of db/dbPromise due to depns upgrade

Added

  • Add Node.js 10 & 12 support
  • Implement store.all function (#291)
  • Add option writeOperationOptions (#295)
  • Add Transparent crypto support (#314)

Changed

  • Change test framework from Mocha to Jest
  • Change linter from xo to eslint

[2.0.3] - 2018-12-03

Fixed

  • Fixed interval autoremove mode to use current date with every interval (#304, #305) (jlampise)

[2.0.2] - 2018-11-20

Fixed

  • Fxi #300 DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead
  • Fxi #297 DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead

[2.0.1] - 2018-01-04

Fixed

  • Fixed #271 TypeError: cb is not a function (brainthinks)

[2.0.0] - 2017-10-09

BREAKING CHANGES

  • Drop Node.js 0.12 and io.js support
  • Drop MongoDB 2.x support
  • Drop mongodb driver < 2.0.36 support
  • Drop mongoose < 4.1.2 support

Changed

  • Fix ensureIndex deprecation warning (#268, #269, #270)
  • Improve get() (#246)
  • Pass session in touch event
  • Remove bluebird from dependencies

1.3.2 / 2016-07-27

  • Fix #228 Broken with mongodb@1.x

1.3.1 / 2016-07-23

  • Restrict bluebird accepted versions to 3.x

1.3.0 / 2016-07-23

  • Add create and update events (#215)
  • Extend mongodb compatibility to 2.x

1.2.1 / 2016-06-20

  • Fix bluebird warning (Awk34)

1.2.0 / 2016-05-13

  • Accept dbPromise as connection param
  • Add close() method to close current connection

1.1.0 / 2015-12-24

  • Support mongodb 2.1.x

1.0.2 / 2015-12-18

  • Enforce entry-points

1.0.1 / 2015-12-17

  • Fix entry-point

1.0.0 (deprecated) / 2015-12-17

Breaking changes:

  • For older Node.js version (< 4.0), the module must be loaded using require('connect-mongo/es5')
  • Drop hash option (advanced)

Others changes:

  • Add transformId option to allow custom transformation on session id (advanced)
  • Rewrite in ES6 (w/ fallback)
  • Update dependencies
  • Improve compatibility

0.8.2 / 2015-07-14

  • Bug fixes and improvements (whitef0x0, TimothyGu, behcet-li)

0.8.1 / 2015-04-21

  • Fix initialization when a connecting mongodb 2.0.x instance is given (1999)

0.8.0 / 2015-03-24

  • Add touchAfter option to enable lazy update behavior on touch() method (rafaelcardoso)
  • Add fallbackMemory option to switch to MemoryStore in some case.

0.7.0 / 2015-01-24

  • Add touch() method to be fully compliant with express-session >= 1.10 (rafaelcardoso)

0.6.0 / 2015-01-12

  • Add ttl option
  • Add autoRemove option
  • Deprecate defaultExpirationTime option. Use ttl instead (in seconds)

0.5.3 / 2014-12-30

  • Make callbacks optional

0.5.2 / 2014-12-29

  • Extend compatibility to mongodb 2.0.x

0.5.1 / 2014-12-28

  • [bugfix] #143 Missing Sessions from DB should still make callback (brekkehj)

0.5.0 (deprecated) / 2014-12-25

  • Accept full-featured MongoDB connection strings as url + advanced options
  • Re-use existing or upcoming mongoose connection
  • [DEPRECATED] mongoose_connection is renamed mongooseConnection
  • [DEPRECATED] auto_reconnect is renamed autoReconnect
  • [BREAKING] autoReconnect option is now true by default
  • [BREAKING] Insert collection option in url in not possible any more
  • [BREAKING] Replace for-testing-purpose callback by connected event
  • Add debug (use with DEBUG=connect-mongo)
  • Improve error management
  • Compatibility with mongodb >= 1.2.0 and < 2.0.0
  • Fix many bugs

0.4.2 / 2014-12-18

  • Bumped mongodb version from 1.3.x to 1.4.x (B0k0)
  • Add sid hash capability (ZheFeng)
  • Add serialize and unserialize options (ksheedlo)

0.3.3 / 2013-07-04

  • Merged a change which reduces data duplication

0.3.0 / 2013-01-20

  • Merged several changes by Ken Pratt, including Write Concern support
  • Updated to mongodb version 1.2

0.2.0 / 2012-09-09

  • Integrated pull request for mongoose_connection option
  • Move to mongodb 1.0.x

0.1.5 / 2010-07-07

  • Made collection setup more robust to avoid race condition

0.1.4 / 2010-06-28

  • Added session expiry

0.1.3 / 2010-06-27

  • Added url support

0.1.2 / 2010-05-18

  • Added auto_reconnect option

0.1.1 / 2010-03-18

  • Fixed authentication

0.1.0 / 2010-03-08

  • Initial release