connect-mongo

repository·master·Indexed 24 days ago

https://github.com/jdesboeufs/connect-mongo

A MongoDB session store for Express and Connect written in TypeScript. Version 6.0.0 provides features including automatic session expiration via MongoDB TTL indexes, lazy session updates via the touchAfter option, and transparent encryption/decryption of session data using cryptoAdapter (supporting Web Crypto API and Kruptein). It supports multiple connection methods via mongoUrl, clientPromise, or an existing MongoClient instance.

Tokens
6K
Snippets
16
Records
29
Agent score
79%

What's inside connect-mongo

  1. Configure expired session removal (autoRemove)

    master

    You can control how expired sessions are cleaned up using the autoRemove option:

    1. native (Default): Uses MongoDB's TTL collection feature. Requires MongoDB 2.2+ and admin permissions. connect-mongo creates the TTL index for you. Avoid this in highly concurrent environments; instead, manage the index manually.
    2. interval: connect-mongo handles removal at a defined interval. Useful for environments like Azure Cosmos DB that don't support TTL indexes. Use autoRemoveInterval (in minutes, default 10) to set the frequency.
    3. disabled: Disables automatic cleaning. Use this if you manage the TTL index elsewhere or in production environments where you want manual control.
    // Native mode (Default)
    app.use(session({
      store: MongoStore.create({
        mongoUrl: 'mongodb://localhost/test-app',
        autoRemove: 'native'
      })
    }));
    
    // Interval mode
    app.use(session({
      store: MongoStore.create({
        mongoUrl: 'mongodb://localhost/test-app',
        autoRemove: 'interval',
        autoRemoveInterval: 10 // In minutes. Default
      })
    }));
    
    // Disabled mode
    app.use(session({
      store: MongoStore.create({
        mongoUrl: 'mongodb://localhost/test-app',
        autoRemove: 'disabled'
      })
    }));
  2. Implement session encryption with cryptoAdapter

    master

    For new integrations, use the cryptoAdapter option instead of the legacy crypto options. The cryptoAdapter accepts an object with async encrypt and decrypt functions.

    Helpers are provided to simplify this:

    • createWebCryptoAdapter: Uses AES-GCM via the Web Crypto API.
    • createKrupteinAdapter: Uses the Kruptein library.

    Legacy crypto options (wrapped internally via a kruptein adapter) include:

    • secret: Enables transparent encryption.
    • algorithm: Symmetric encryption cipher (default: 'aes-256-gcm').
    • hashing: Hashing algorithm (default: 'sha512').
    • encodeas: Cipher text encoding (default: 'hex').
    • key_size: Key size (default: 32).
    • iv_size: IV size (default: 16).
    • at_size: Authentication tag size (default: 16).
  3. Implement lazy session updates

    master

    To prevent unnecessary database writes on every page refresh, use the touchAfter option in conjunction with express-session settings (resave: false). touchAfter defines a period in seconds; the session will only be updated in the database once per period, unless the session data itself is modified.

    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
      })
    }));
  4. Connect to MongoDB using a connection string

    master

    You can configure connect-mongo to establish its own connection using a MongoDB connection string via the mongoUrl option. For advanced driver configurations, use the 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
      })
    }));
  5. Install connect-mongo

    master

    Install connect-mongo via npm. Note that mongodb is a required peer dependency, so you must install it alongside connect-mongo to ensure the driver version matches your MongoDB cluster.

    If upgrading from v3.x to v4, refer to the migration guide in the repository.

    npm install connect-mongo
  6. Integrate connect-mongo with Express or Connect

    master

    To use connect-mongo as a session store, pass an instance created by MongoStore.create(options) to the store property of your session middleware (e.g., express-session).

    // CJS
    const session = require('express-session');
    const { MongoStore } = require('connect-mongo');
    
    app.use(session({
      secret: 'foo',
      store: MongoStore.create(options)
    }));
    // ESM or TS
    import session from 'express-session'
    import MongoStore from 'connect-mongo'
    
    app.use(session({
      secret: 'foo',
      store: MongoStore.create(options)
    }));
  7. Encrypt session data with cryptoAdapter

    master

    For sensitive data, use the cryptoAdapter option to implement encryption.

    • Web Crypto API (Recommended): Use createWebCryptoAdapter with a secret. This uses AES-GCM.
    • Legacy Kruptein: Use createKrupteinAdapter if you require the old behavior.

    Note: The legacy crypto option is still supported for backwards compatibility and is automatically wrapped in a kruptein-based adapter. However, providing both crypto and cryptoAdapter will throw an error.

    import MongoStore, { createWebCryptoAdapter } from 'connect-mongo'
    
    const store = MongoStore.create({
      mongoUrl: 'mongodb://localhost/test-app',
      cryptoAdapter: createWebCryptoAdapter({
        secret: process.env.SESSION_SECRET!,
      }),
    })
    import { createKrupteinAdapter } from 'connect-mongo'
    
    const store = MongoStore.create({
      mongoUrl: 'mongodb://localhost/test-app',
      cryptoAdapter: createKrupteinAdapter({ secret: 'squirrel' }),
    })
  8. Run the example application

    master

    To run the provided example application from the repository root:

    1. Copy the environment template: cp example/.env.example example/.env
    2. Link the package: npm link
    3. Navigate to the example directory: cd example
    4. (Optional) Link the local version of connect-mongo: npm link "connect-mongo"
    5. Install dependencies: npm install
    6. Start the app: npm run start:js (or start:mongoose / start: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
  9. Connect to MongoDB by re-using an existing MongoClient

    master

    To avoid creating multiple connections, you can pass an existing native MongoDB driver MongoClient instance (as a promise) to connect-mongo using the clientPromise option. You can also explicitly specify the dbName.

    // 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'
      })
    }));
  10. Customize session serialization and transformation

    master

    You can intercept the session data during the read/write process using these hooks:

    • serialize: A custom hook for serializing sessions before they are written to MongoDB.
    • unserialize: A custom hook for deserializing sessions when they are retrieved from MongoDB.
    • transformId: A function to transform the original sessionId into a different storage key.
    • writeOperationOptions: An object passed to every MongoDB write operation (e.g., update, remove). This is useful for adjusting write concerns.
  11. Configure session storage and TTL

    master

    Use the following options to control how sessions are stored and how long they last:

    • collectionName: The name of the collection used for sessions (default: 'sessions').
    • ttl: The maximum lifetime of a session in seconds (default: 1209600, which is 14 days). This sets session.cookie.expires if not already set.
    • timestamps: If true, stores createdAt and updatedAt fields on each session document for auditing.
    • stringify: If true (default), sessions are serialized using JSON.stringify and deserialized with JSON.parse. This is useful for types not natively supported by MongoDB.
  12. Configure session expiration (TTL)

    master

    When the session cookie does not have an expiration date, connect-mongo uses the ttl option (in seconds) to set the session lifetime. The default is 14 days. Each user interaction refreshes the expiration date.

    app.use(session({
      store: MongoStore.create({
        mongoUrl: 'mongodb://localhost/test-app',
        ttl: 14 * 24 * 60 * 60 // = 14 days. Default
      })
    }));