rate-limit-mongo is a specialized MongoDB store designed for the popular `express-rate-limit` middleware, currently at version 2.3.2. This package provides a persistent, database-backed storage mechanism for rate limiting records, moving beyond in-memory or Redis solutions. It leverages MongoDB's TTL (Time-To-Live) indexes to automatically expire rate limiting entries, ensuring efficient cleanup and preventing stale data. While not on a strict release cadence, updates typically align with bug fixes or `express-rate-limit`/MongoDB driver compatibility improvements. Its primary differentiation lies in offering a robust, low-configuration MongoDB-specific solution for managing API rate limits, particularly beneficial for applications already using MongoDB and requiring shared, persistent rate limit counters across multiple instances.
npm install rate-limit-mongoVerified import paths — ran on the pinned version, not inferred.
This code demonstrates the basic setup of `rate-limit-mongo` as a store for `express-rate-limit`, configuring connection details and matching `expireTimeMs` with `windowMs`.
Ensure `expireTimeMs` in `MongoStore` options and `windowMs` in `RateLimit` options are numerically equivalent (e.g., both 15 * 60 * 1000 for 15 minutes).
Account for this delay in application logic if strict immediate deletion is required, or consider shorter `expireTimeMs` for more aggressive cleanup (though this increases database write load).
If index creation fails or is not desired from the application, set `createTtlIndex: false` in the `MongoStore` options and ensure the TTL index is manually created on the collection (`db.collection.createIndex({ expirationDate: 1 }, { expireAfterSeconds: 0 })`).Monitor `mongodb` driver release notes for changes to connection options. Explicitly define all desired connection options via the `connectionOptions` property to maintain control over connection behavior.
Ensure the MongoDB server is running and accessible from the application host. Verify the `uri` provided in the `MongoStore` configuration is correct and points to an active MongoDB instance.
Verify that the `user` and `password` fields in the `MongoStore` configuration match valid MongoDB credentials with access to the specified database or `authSource`.
Drop the existing index (`db.collection.dropIndex('expirationDate_1')`) or ensure the `createTtlIndex` option is set to `false` if you manage the index manually with the correct `expireAfterSeconds: 0` setting.