Memcached Store for express-rate-limit

raw JSON →
1.0.1 verified Thu Apr 23 auth: no javascript

rate-limit-memcached is a specialized storage adapter designed for the `express-rate-limit` middleware, enabling distributed rate limiting using a Memcached server. It is currently at version 1.0.1, indicating a stable and mature state after its initial 1.0.0 release. The package is actively maintained within the `express-rate-limit` ecosystem, though a specific release cadence is not formally stated. Its key differentiator is providing an efficient, externalized state management solution for rate limiting, making it suitable for applications deployed across multiple instances where local memory stores are insufficient. It integrates seamlessly with the core `express-rate-limit` package, providing configuration options for Memcached server locations and custom client instances, ensuring flexibility for various deployment scenarios.

error TypeError: MemcachedStore is not a constructor
cause Attempting to import `MemcachedStore` using CommonJS `require()` syntax or incorrect destructuring in an ESM context.
fix
Use import { MemcachedStore } from 'rate-limit-memcached'; for ES Modules. Ensure your project is configured for ESM if using type: module in package.json.
error Memcached connection error: Connection refused
cause The Memcached server is not running or is not accessible at the specified `locations`.
fix
Start your Memcached server (e.g., memcached -p 11211). Verify the locations array in MemcachedStore options. Check firewall settings or network connectivity for remote servers.
error npm ERR! ERESOLVE unable to resolve dependency tree
cause The `express-rate-limit` peer dependency version requirement is not met by other installed packages or is missing.
fix
Install express-rate-limit explicitly: npm install express-rate-limit@^6. If conflicts persist, try npm install --force (use with caution) or npm install --legacy-peer-deps.
error ReferenceError: require is not defined
cause Attempting to use `require()` in an ES Module context without proper setup or bundler transformation.
fix
Convert your project to use ES Modules by adding "type": "module" to your package.json and using import statements, or configure your bundler (Webpack, Rollup, etc.) to handle CommonJS modules.
breaking This package requires Node.js version 16 or above. Older Node.js versions are not supported and may lead to runtime errors.
fix Upgrade your Node.js environment to version 16 or higher.
gotcha This store requires a running Memcached server instance. If no server is accessible at the configured `locations`, the rate limiter will fail to store and retrieve counts, potentially leading to uncaught errors or unexpected behavior.
fix Ensure Memcached is installed and running at the specified `locations` (default `localhost:11211`). Verify network connectivity and firewall rules if Memcached is remote.
breaking The `express-rate-limit` peer dependency must be version 6 or greater. Earlier versions are not compatible and will result in installation warnings or runtime errors.
fix Install or upgrade `express-rate-limit` to a version `>= 6.0.0`.
gotcha If you don't provide a custom `client` option to `MemcachedStore`, the package internally instantiates the `memcached` npm package. Ensure `memcached` is accessible if you rely on this default behavior.
fix If you encounter issues with the default client, consider installing `memcached` directly, passing your own `Memcached` client instance, or debugging the default client's connection via the `locations` and `config` options.
npm install rate-limit-memcached
yarn add rate-limit-memcached
pnpm add rate-limit-memcached

Demonstrates initializing `express-rate-limit` with `rate-limit-memcached` for distributed rate limiting across an Express application, using environment variables for Memcached host.

import express from 'express';
import { rateLimit } from 'express-rate-limit';
import { MemcachedStore } from 'rate-limit-memcached';

const app = express();

// Ensure a Memcached server is running at localhost:11211 or specified locations
const limiter = rateLimit({
	windowMs: 15 * 60 * 1000, // 15 minutes
	max: 100, // Limit each IP to 100 requests per window
	standardHeaders: 'draft-7',
	legacyHeaders: false,
	store: new MemcachedStore({
		// Optional: The prefix attached to all keys stored in Memcached
		prefix: 'rl:', 
		// The server location(s), passed directly to Memcached client constructor
		locations: [process.env.MEMCACHED_HOST || 'localhost:11211'], 
		// Optional: Pass a custom Memcached client instance instead of default
		// client: myCustomMemcachedClient
	}),
});

// Apply the rate limiting middleware to all requests
app.use(limiter);

app.get('/', (req, res) => {
  res.send('Hello, you are rate limited!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Ensure Memcached is running, e.g., `memcached -p 11211`');
});