connect-mongo vs connect-pg-simple vs connect-redis vs connect-session-knex vs express-session
Session Store Libraries for Node.js
connect-mongoconnect-pg-simpleconnect-redisconnect-session-knexexpress-sessionSimilar Packages:

Session Store Libraries for Node.js

Session store libraries are used in Node.js applications to manage user sessions. They provide a way to store session data in various backends, allowing developers to choose the most suitable storage solution based on their application's needs. These libraries integrate with Express.js to facilitate session management, ensuring that user data persists across requests. Each library offers unique features and optimizations tailored to different storage systems, such as MongoDB, PostgreSQL, Redis, and more, helping developers maintain efficient session handling in their applications.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
connect-mongo01,974144 kB83 months agoMIT
connect-pg-simple024824.3 kB22a year agoMIT
connect-redis02,83130.5 kB08 months agoMIT
connect-session-knex09550.2 kB112 years agoISC
express-session06,36177.2 kB107a month agoMIT

Feature Comparison: connect-mongo vs connect-pg-simple vs connect-redis vs connect-session-knex vs express-session

Storage Backend

  • connect-mongo:

    connect-mongo uses MongoDB as its storage backend, allowing session data to be stored in a NoSQL database. This is beneficial for applications already utilizing MongoDB, as it provides a unified data storage approach.

  • connect-pg-simple:

    connect-pg-simple stores session data in PostgreSQL, leveraging its relational database features. This is ideal for applications that require structured data storage and complex querying capabilities.

  • connect-redis:

    connect-redis utilizes Redis, an in-memory data structure store, which provides extremely fast access to session data. This makes it suitable for high-performance applications that demand quick session retrieval.

  • connect-session-knex:

    connect-session-knex integrates with Knex.js to store session data in various SQL databases. It provides flexibility in choosing the underlying database while maintaining a consistent API for session management.

  • express-session:

    express-session is a generic session middleware that can be configured with various storage backends. It provides a simple API for session management, allowing developers to choose their preferred storage solution.

Performance

  • connect-mongo:

    connect-mongo is optimized for MongoDB, but performance may vary based on the database's configuration and indexing. It is suitable for applications with moderate session data requirements.

  • connect-pg-simple:

    connect-pg-simple benefits from PostgreSQL's performance optimizations, especially for applications that require complex transactions and queries. It is efficient for applications with structured session data.

  • connect-redis:

    connect-redis is highly performant due to Redis's in-memory nature, making it ideal for applications with high traffic and low latency requirements. It can handle a large number of sessions with minimal overhead.

  • connect-session-knex:

    connect-session-knex's performance depends on the underlying SQL database used. It can be optimized for performance with proper indexing and query optimization strategies.

  • express-session:

    express-session provides a basic session management solution, but its performance is heavily influenced by the session store used. It can be optimized by selecting a high-performance store.

Scalability

  • connect-mongo:

    connect-mongo scales well with MongoDB, allowing for horizontal scaling through sharding. This is beneficial for applications that anticipate growth in user sessions.

  • connect-pg-simple:

    connect-pg-simple can scale with PostgreSQL, but may require more careful planning for scaling out, as relational databases typically have more constraints than NoSQL options.

  • connect-redis:

    connect-redis is highly scalable, as Redis can handle large volumes of data and connections. It is suitable for distributed applications that require fast access to session data across multiple instances.

  • connect-session-knex:

    connect-session-knex scales with the underlying SQL database. Proper database management and optimization are essential for maintaining performance as the application grows.

  • express-session:

    express-session's scalability depends on the chosen session store. Selecting a store that supports clustering and distributed environments is crucial for scaling.

Ease of Use

  • connect-mongo:

    connect-mongo is straightforward to set up for developers familiar with MongoDB. Its API is intuitive, making it easy to integrate into existing applications.

  • connect-pg-simple:

    connect-pg-simple is easy to use for developers who are already familiar with PostgreSQL. It provides a simple API for session management without complex configurations.

  • connect-redis:

    connect-redis is easy to set up and use, especially for developers familiar with Redis. Its performance and simplicity make it a popular choice for session management.

  • connect-session-knex:

    connect-session-knex is user-friendly for those already using Knex.js. It allows seamless integration with existing SQL databases, making it easy to manage sessions alongside other data.

  • express-session:

    express-session is very easy to use and configure, making it a great starting point for session management in Express applications. It provides a simple API and can be extended with various stores.

Community and Support

  • connect-mongo:

    connect-mongo has a strong community and is widely used in applications that utilize MongoDB, ensuring good support and frequent updates.

  • connect-pg-simple:

    connect-pg-simple benefits from the robust PostgreSQL community, providing ample resources and support for developers.

  • connect-redis:

    connect-redis has a large user base and is well-supported, with extensive documentation and community resources available for troubleshooting.

  • connect-session-knex:

    connect-session-knex is supported by the Knex.js community, which is active and provides resources for developers using SQL databases.

  • express-session:

    express-session has a large community and is widely adopted in the Express ecosystem, ensuring good support and a wealth of resources for developers.

How to Choose: connect-mongo vs connect-pg-simple vs connect-redis vs connect-session-knex vs express-session

  • connect-mongo:

    Choose connect-mongo if you are using MongoDB as your database and need a session store that integrates seamlessly with it. This package is ideal for applications that already leverage MongoDB for data storage, providing a consistent data model and easy scalability.

  • connect-pg-simple:

    Opt for connect-pg-simple if your application uses PostgreSQL and you want a session store that takes advantage of its relational capabilities. This package is suitable for applications that require complex queries and transactions, benefiting from PostgreSQL's robust features.

  • connect-redis:

    Select connect-redis if you need a fast, in-memory session store. Redis is known for its speed and efficiency, making it a great choice for applications with high traffic and a need for quick session retrieval. This package is ideal for real-time applications where performance is critical.

  • connect-session-knex:

    Use connect-session-knex if you are already using Knex.js as your SQL query builder and want to store sessions in a SQL database. This package allows you to leverage the flexibility of Knex.js while managing sessions, making it suitable for applications that require a SQL-based solution.

  • express-session:

    Choose express-session if you need a simple and flexible session middleware for Express applications. It provides basic session management capabilities and can be easily extended with various session stores, making it a good starting point for most applications.

README for connect-mongo

connect-mongo

MongoDB session store for Connect and Express written in Typescript.

npm version downloads Sanity check coverage

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
  • Install mongodb alongside connect-mongo; it is a required peer dependency so you pick the driver version that matches your cluster.
  • 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

  • Support Express up to 5.0
  • Support native MongoDB driver >= 5.x (peer dependency range >=5.0.0, tested in CI with 5.x, 6.x, and 7.x)
  • Support Node.js 20 LTS, 22 LTS and 24 (Current LTS)
  • Support MongoDB server versions 4.4 - 8.0

We follow MongoDB's official Node.js driver compatibility tables and exercise every combination of the versions above (3 Node releases × 3 driver majors × 5 server tags) in CI so that mismatches surface quickly. Note that driver 5.x officially supports Node 20, while Node 22/24 coverage relies on driver 6.x/7.x, matching the upstream guidance.

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 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 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.
Use the new cryptoAdapter option to plug in your encryption strategy. The preferred helper uses the Web Crypto API (AES-GCM):

import MongoStore, { createWebCryptoAdapter } from 'connect-mongo'

const store = MongoStore.create({
  mongoUrl: 'mongodb://localhost/test-app',
  cryptoAdapter: createWebCryptoAdapter({
    secret: process.env.SESSION_SECRET!,
  }),
})

If you need the legacy kruptein behavior, wrap it explicitly:

import { createKrupteinAdapter } from 'connect-mongo'

const store = MongoStore.create({
  mongoUrl: 'mongodb://localhost/test-app',
  cryptoAdapter: createKrupteinAdapter({ secret: 'squirrel' }),
})

The legacy crypto option still works for backwards compatibility; it is automatically wrapped into a kruptein-based adapter. Supplying both crypto and cryptoAdapter throws an error so it is clear which path is used.

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.

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.
3clientAn 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

OptionDefaultDescription
mongoOptions{}Options object forwarded to MongoClient.connect, e.g. TLS/SRV settings. 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.
timestampsfalseWhen true, stores createdAt (on insert) and updatedAt (on every write/touch) fields on each session document for auditing. Disabled by default to preserve existing schemas.
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.
cryptoAdapterPreferred hook for encrypting/decrypting session payloads. Accepts any object with async encrypt/decrypt functions; helpers createWebCryptoAdapter (AES-GCM via Web Crypto API) and createKrupteinAdapter are provided.
cryptoCrypto related options. See below.

If you enable timestamps, each session document will include createdAt (first insert) and updatedAt (every subsequent set/touch) fields. These fields are informational only and do not change TTL behavior.

Crypto-related options (legacy)

Prefer cryptoAdapter for new integrations. The legacy crypto options are wrapped internally into a kruptein adapter to preserve backwards compatibility:

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

npm install
docker compose up -d
npm run watch:test

TLS & SRV fixtures

  • Generate local certificates once with npm run tls:setup (drops files in docker/tls).
  • Launch the optional TLS container with docker compose -f docker-compose.yaml -f docker-compose.tls.yaml --profile tls up -d.
  • Copy example/.env.example to example/.env and point MONGO_URL to the TLS port (mongodb://root:example@127.0.0.1:27443/example-db?authSource=admin). Add MONGO_TLS_CA_FILE=../docker/tls/ca.crt so the driver trusts the self-signed CA. Set MONGO_TLS_CERT_KEY_FILE=../docker/tls/client.pem if you need mutual TLS.
  • To exercise SRV/TLS against a managed cluster (Atlas, DocumentDB, CosmosDB), set MONGO_URL to your mongodb+srv:// string and either MONGO_TLS_CA_FILE or NODE_EXTRA_CA_CERTS to the provider CA bundle. The example scripts automatically reuse those settings in every variant (plain JS, Mongoose, and TS).

Example application

# from the repo root
cp example/.env.example example/.env
npm link
cd example
npm link "connect-mongo"   # optional if you want live code from this checkout
npm install
npm run start:js
# or npm run start:mongoose / npm run start:ts

After the first run you can edit example/.env to swap between the local docker fixture, the TLS profile, or any mongodb+srv:// cluster without changing the code.

Release

Until the GitHub release workflow lands, do the manual flow:

  1. Bump version, update CHANGELOG.md and README. Commit and push.
  2. Run npm test && npm run build (build uses tsdown to emit dual ESM/CJS bundles to dist/).
  3. Publish: npm publish
  4. Tag: git tag vX.Y.Z && git push --tags

License

The MIT License