express-session is the core middleware for managing user sessions in Express.js applications, while connect-mongo, connect-pg-simple, connect-redis, and connect-session-knex are session store implementations that determine where session data is persisted. express-session handles the session lifecycle (creation, validation, destruction) but requires a separate store for production use. The store packages integrate with different databases: MongoDB (connect-mongo), PostgreSQL (connect-pg-simple), Redis (connect-redis), and any Knex-supported database (connect-session-knex). Choosing the right combination depends on your existing infrastructure, scalability needs, and operational preferences.
Managing user sessions is a fundamental requirement for most web applications. While express-session provides the core middleware for handling sessions in Express.js, you need a session store to persist session data beyond a single server restart. Let's compare the five most common options and understand their trade-offs.
express-session is the foundation — it manages session IDs, cookies, and the session lifecycle, but stores data in memory by default (not suitable for production).
// express-session: Core middleware setup
import session from 'express-session';
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: { secure: true, maxAge: 24 * 60 * 60 * 1000 }
}));
connect-mongo stores sessions in MongoDB collections with automatic TTL expiration.
// connect-mongo: MongoDB store
import MongoStore from 'connect-mongo';
app.use(session({
secret: 'your-secret-key',
store: MongoStore.create({
mongoUrl: 'mongodb://localhost:27017/myapp',
ttl: 14 * 24 * 60 * 60 // 14 days
})
}));
connect-pg-simple stores sessions in a PostgreSQL table with automatic cleanup.
// connect-pg-simple: PostgreSQL store
import pgSession from 'connect-pg-simple';
const PgStore = pgSession(session);
app.use(session({
secret: 'your-secret-key',
store: new PgStore({
conString: 'postgresql://localhost/myapp',
tableName: 'session'
})
}));
connect-redis stores sessions in Redis with native expiration support.
// connect-redis: Redis store
import RedisStore from 'connect-redis';
import { createClient } from 'redis';
const redisClient = createClient();
await redisClient.connect();
app.use(session({
secret: 'your-secret-key',
store: new RedisStore({ client: redisClient }),
cookie: { maxAge: 24 * 60 * 60 * 1000 }
}));
connect-session-knex stores sessions in any Knex-supported database.
// connect-session-knex: Knex-based store
import knex from 'knex';
import session from 'express-session';
import connectSessionKnex from 'connect-session-knex';
const KnexStore = connectSessionKnex(session);
const store = new KnexStore({ knex: knex({ client: 'mysql', connection: {} }) });
app.use(session({
secret: 'your-secret-key',
store: store
}));
Session store performance directly impacts request latency. Here's how they compare:
express-session (memory store) is fastest but loses data on restart.
// Memory store - fastest but not production-safe
app.use(session({
secret: 'your-secret-key',
// No store = memory (default)
}));
// ⚠️ Sessions lost on server restart
connect-redis offers sub-millisecond access with in-memory storage.
// Redis - ~1ms read/write times
const store = new RedisStore({ client: redisClient });
// Best for: High-traffic apps, horizontal scaling
connect-mongo typically runs 5-20ms per operation depending on indexing.
// MongoDB - moderate speed, good for existing Mongo setups
const store = MongoStore.create({ mongoUrl: process.env.MONGO_URI });
// Best for: Apps already using MongoDB
connect-pg-simple runs 10-50ms depending on database load and connection pooling.
// PostgreSQL - slower than Redis, queryable sessions
const store = new PgStore({ conString: process.env.DATABASE_URL });
// Best for: Teams wanting session data in SQL
connect-session-knex performance varies by underlying database (MySQL, SQLite, etc.).
// Knex - depends on configured database
const store = new KnexStore({ knex: db });
// Best for: Non-standard database requirements
Each store handles expired sessions differently:
express-session relies on the store for expiration — memory store has no cleanup.
// Memory store - no automatic cleanup
app.use(session({
cookie: { maxAge: 86400000 } // 1 day
// Expired sessions stay in memory until restart
}));
connect-mongo uses MongoDB TTL indexes for automatic removal.
// MongoDB - TTL index handles cleanup
MongoStore.create({
mongoUrl: 'mongodb://localhost/myapp',
ttl: 1209600, // 14 days in seconds
autoRemove: 'native' // Uses MongoDB TTL
});
connect-pg-simple runs a periodic cleanup query on idle connections.
// PostgreSQL - cleanup on idle
new PgStore({
conString: 'postgresql://localhost/myapp',
pruneSessionInterval: 60 // Cleanup every 60 seconds
});
connect-redis uses Redis native EXPIRE command.
// Redis - native expiration
new RedisStore({
client: redisClient,
ttl: 86400 // 1 day in seconds
});
// Redis automatically removes expired keys
connect-session-knex requires manual cleanup configuration.
// Knex - configurable cleanup
new KnexStore({
knex: db,
clearInterval: 3600000 // Cleanup every hour
});
Setup effort varies significantly between stores:
express-session requires minimal configuration.
npm install express-session
// Minimal setup
import session from 'express-session';
app.use(session({ secret: 'change-me', resave: false, saveUninitialized: false }));
connect-mongo needs MongoDB connection string and peer dependency.
npm install connect-mongo mongodb
// Requires MongoDB instance
import MongoStore from 'connect-mongo';
const store = MongoStore.create({ mongoUrl: 'mongodb://localhost:27017/sessions' });
connect-pg-simple needs PostgreSQL and creates table automatically.
npm install connect-pg-simple pg
// Auto-creates session table
import pgSession from 'connect-pg-simple';
const PgStore = pgSession(session);
const store = new PgStore({ conString: 'postgresql://localhost/sessions' });
connect-redis requires Redis server and redis client.
npm install connect-redis redis
// Needs running Redis server
import RedisStore from 'connect-redis';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const store = new RedisStore({ client });
connect-session-knex needs Knex and database driver.
npm install connect-session-knex knex mysql2
// Requires Knex configuration
import connectSessionKnex from 'connect-session-knex';
const KnexStore = connectSessionKnex(session);
const store = new KnexStore({ knex: knexConfig });
All stores inherit express-session security features but differ in data protection:
express-session provides cookie signing and HTTP-only flags.
// Core security settings
app.use(session({
secret: process.env.SESSION_SECRET, // Required for signing
cookie: {
httpOnly: true, // Prevents XSS access
secure: true, // HTTPS only
sameSite: 'strict' // CSRF protection
}
}));
connect-mongo stores session data encrypted at rest if MongoDB encryption is enabled.
// MongoDB encryption at rest (Enterprise feature)
MongoStore.create({
mongoUrl: 'mongodb://localhost/myapp',
// Session data encrypted if MongoDB configured
});
connect-pg-simple benefits from PostgreSQL row-level security if configured.
// PostgreSQL with connection encryption
new PgStore({
conString: 'postgresql://localhost/myapp?ssl=true',
// Data encrypted in transit with SSL
});
connect-redis requires Redis AUTH and TLS for production.
// Redis security configuration
const client = createClient({
password: process.env.REDIS_PASSWORD,
socket: { tls: true }
});
const store = new RedisStore({ client });
connect-session-knex depends on underlying database security.
// Database-level security
const store = new KnexStore({
knex: knex({
connection: { ssl: true, encrypt: true }
})
});
Session store choice affects how you scale across multiple servers:
express-session memory store does NOT support multiple servers.
// ❌ Memory store - breaks with multiple servers
app.use(session({ secret: 'key' }));
// Each server has different sessions - users get logged out randomly
connect-mongo supports horizontal scaling with shared MongoDB.
// ✅ MongoDB - shared across servers
const store = MongoStore.create({ mongoUrl: 'mongodb://cluster/myapp' });
// All servers access same session data
connect-pg-simple supports scaling with shared PostgreSQL.
// ✅ PostgreSQL - shared across servers
const store = new PgStore({ conString: 'postgresql://cluster/myapp' });
// Connection pooling handles concurrent access
connect-redis is built for horizontal scaling with Redis Cluster.
// ✅ Redis - designed for distributed systems
const client = createClient({ url: 'redis://cluster' });
const store = new RedisStore({ client });
// Native support for Redis Cluster and Sentinel
connect-session-knex supports scaling with shared database.
// ✅ Knex - depends on database scaling
const store = new KnexStore({ knex: db });
// Scales as well as your database supports
| Feature | express-session | connect-mongo | connect-pg-simple | connect-redis | connect-session-knex |
|---|---|---|---|---|---|
| Type | Core middleware | MongoDB store | PostgreSQL store | Redis store | Knex-based store |
| Production Ready | ❌ (memory default) | ✅ | ✅ | ✅ | ✅ |
| Auto Cleanup | ❌ | ✅ (TTL) | ✅ (prune) | ✅ (native) | ✅ (interval) |
| Horizontal Scale | ❌ | ✅ | ✅ | ✅ | ✅ |
| Setup Complexity | Low | Medium | Medium | Medium | High |
| Query Sessions | N/A | ✅ | ✅ | ❌ | ✅ |
| Best For | Development | Mongo apps | SQL teams | High traffic | Custom DB needs |
As of current verification:
express-session — Actively maintained, stable APIconnect-mongo — Actively maintained, regularly updatedconnect-pg-simple — Actively maintained, stableconnect-redis — Actively maintained, updated for Redis v4+connect-session-knex — Maintained but less active than others⚠️ Important: Always check npm and GitHub before starting a new project. Maintenance status can change.
Use express-session with memory store for development, then add a persistent store for production.
// Development
if (process.env.NODE_ENV === 'development') {
app.use(session({ secret: 'dev-secret', cookie: { secure: false } }));
} else {
// Production store here
}
Choose connect-mongo to avoid adding new dependencies.
// Leverage existing MongoDB
const store = MongoStore.create({
mongoUrl: process.env.MONGO_URI,
dbName: 'sessions'
});
Choose connect-redis for performance and scalability.
// Redis for speed
const store = new RedisStore({
client: redisClient,
prefix: 'sess:'
});
Choose connect-pg-simple to keep sessions queryable.
// PostgreSQL for relational session data
const store = new PgStore({
conString: process.env.DATABASE_URL,
tableName: 'user_sessions'
});
Choose connect-session-knex for MySQL, SQLite, or other databases.
// MySQL via Knex
const store = new KnexStore({
knex: knex({ client: 'mysql', connection: config })
});
express-session is mandatory — it's the core middleware all stores build on. Never skip it.
connect-redis wins for performance-critical applications. Redis provides the fastest session access and best horizontal scaling support.
connect-mongo and connect-pg-simple are excellent choices when you already use those databases. They reduce operational overhead by avoiding additional infrastructure.
connect-session-knex fills the gap when you need MySQL, SQLite, or other Knex-supported databases.
Final Thought: Your session store choice should align with your existing infrastructure. Adding Redis solely for sessions may not be worth the operational cost for small applications. But for high-traffic sites, Redis pays for itself in performance gains. Choose based on your team's database expertise and scaling requirements.
Choose connect-mongo if your application already uses MongoDB as its primary database. It reduces operational complexity by avoiding additional infrastructure. Best for small to medium applications where MongoDB performance is acceptable for session lookups. Avoid if you need sub-millisecond session access or have extremely high concurrent user counts.
Choose connect-pg-simple if PostgreSQL is your main database and you want sessions stored relationally. It creates a dedicated session table automatically. Ideal for teams already managing PostgreSQL who want session data queryable alongside other business data. Not recommended if you need horizontal scaling or very high write throughput.
Choose connect-redis for high-performance applications requiring fast session access. Redis provides sub-millisecond read/write times and built-in expiration. Best for high-traffic sites, microservices architectures, or when you need session data accessible across multiple application instances. Requires running and maintaining a Redis server.
Choose connect-session-knex if you need database flexibility beyond PostgreSQL or MongoDB. It works with any database supported by Knex.js (MySQL, SQLite, Oracle, etc.). Good for legacy applications or teams with specific database requirements. Adds a dependency on Knex, which may be overkill if you only need session storage.
Choose express-session as your foundation for any Express.js session management. It is required regardless of which store you pick. Use it when you need server-side sessions instead of JWT tokens, particularly for applications requiring immediate session invalidation, rolling session expiration, or sensitive user data that should not be stored client-side.
MongoDB session store for Connect and Express written in Typescript.
Breaking change in V4 and rewritten the whole project using Typescript. Please checkout the migration guide and changelog for details.
npm install connect-mongo
mongodb alongside connect-mongo; it is a required peer dependency so you pick the driver version that matches your cluster.5.0>= 5.x (peer dependency range >=5.0.0, tested in CI with 5.x, 6.x, and 7.x)4.4 - 8.0We 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.
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)
}));
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.
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
})
}));
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 in GitHub Issues page.
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. #413The 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)
v4 cannot decrypt the session encrypted from v3.2 due to a bug. Please take a look on this issue for possible workaround. #420
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 |
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.
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.
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!
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
})
}));
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'
})
}));
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)
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.
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. |
| Option | Default | Description |
|---|---|---|
mongoOptions | {} | Options object forwarded to MongoClient.connect, e.g. TLS/SRV settings. 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. |
timestamps | false | When 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. |
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. | |
cryptoAdapter | Preferred 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. | |
crypto | Crypto 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.
Prefer cryptoAdapter for new integrations. The legacy crypto options are wrapped internally into a kruptein adapter to preserve backwards compatibility:
| 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. |
npm install
docker compose up -d
npm run watch:test
npm run tls:setup (drops files in docker/tls).docker compose -f docker-compose.yaml -f docker-compose.tls.yaml --profile tls up -d.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.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).# 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.
Until the GitHub release workflow lands, do the manual flow:
CHANGELOG.md and README. Commit and push.npm test && npm run build (build uses tsdown to emit dual ESM/CJS bundles to dist/).npm publishgit tag vX.Y.Z && git push --tagsThe MIT License