Socket
Socket
Sign inDemoInstall

connect-mongo

Package Overview
Dependencies
25
Maintainers
2
Versions
67
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    connect-mongo

MongoDB session store for Express and Connect


Version published
Maintainers
2
Install size
3.36 MB
Created

Changelog

Source

[4.2.2] - 2021-03-02

Fixed

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

Readme

Source

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

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').default;

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

Events

A MongoStore instance will emit the following events:

Event nameDescriptionPayload
createA session has been createdsessionId
touchA session has been touched (but not modified)sessionId
updateA session has been updatedsessionId
setA session has been created OR updated (for compatibility purpose)sessionId
destroyA session has been destroyed manuallysessionId

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 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: MongoStore.craete({
    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.craete({
    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.craete({
    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 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: 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

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.

PriorityOptionDescription
1mongoUrlA 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.
2clientPromiseA 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.

More options

OptionDefaultDescription
mongoOptions{ useUnifiedTopology: true }Options object for MongoClient.connect() method. Can be used with mongoUrl option.
dbNameA 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.
ttl1209600The 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'.
autoRemoveInterval10Interval (in minutes) used when autoRemove option is set to interval.
touchAfter0Interval (in seconds) between session updates.
stringifytrueIf 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.
serializeCustom hook for serializing sessions to MongoDB. This is helpful if you need to modify the session before writing it out.
unserializeCustom 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.
writeOperationOptionsOptions 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.
transformIdTransform original sessionId in whatever you want to use as storage key.
cryptoCrypto related options. See below.
OptionDefaultDescription
secretfalseEnables 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_size32When using varying algorithms the key size may be used. Default value 32 is based on the AES blocksize.
iv_size16This can be used to adjust the default IV size if a different algorithm requires a different size.
at_size16When 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

Keywords

FAQs

Last updated on 02 Mar 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc