Skip to content

HarshP34/rate-limiter-flex

Repository files navigation

rate-limiter-flex

Multi-algorithm rate limiting middleware for Express and Fastify, using a Redis-backed store.

Install

npm i rate-limiter-flex ioredis

Quick start (Express + Redis)

import express from 'express';
import Redis from 'ioredis';
import { createExpressRateLimiter, RedisStore, byIp } from 'rate-limiter-flex';

const app = express();

const redis = new Redis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379');
const store = new RedisStore(redis, { keyPrefix: 'myapp' });

app.use(
  createExpressRateLimiter({
    algorithm: 'fixed-window',
    store,          // required
    limit: 100,
    windowMs: 60_000,
    keyGenerator: byIp(),
  }),
);

app.get('/health', (_req, res) => res.json({ ok: true }));
app.listen(3000);

Fastify

import Fastify from 'fastify';
import Redis from 'ioredis';
import { createFastifyRateLimiter, RedisStore, byIp } from 'rate-limiter-flex';

const app = Fastify();

const redis = new Redis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379');
const store = new RedisStore(redis, { keyPrefix: 'myapp' });

app.addHook(
  'preHandler',
  createFastifyRateLimiter({
    algorithm: 'sliding-window-log',
    store, // required
    limit: 20,
    windowMs: 10_000,
    keyGenerator: byIp(),
  }),
);

app.get('/health', async () => ({ ok: true }));
await app.listen({ port: 3000 });

Algorithms

  • fixed-window
  • sliding-window-log
  • sliding-window-counter
  • token-bucket (uses limit as bucket capacity; optional refillRate tokens/sec)

Key generators

  • byIp()
  • byUserId(field = 'user.id')
  • byApiKey(header = 'x-api-key')
  • byRoute()
  • combined(...generators)

Headers

On every request:

  • X-RateLimit-Limit
  • X-RateLimit-Remaining
  • X-RateLimit-Reset

On 429 responses:

  • Retry-After

Store (Redis)

You must provide store in RateLimiterOptions.

This package exports RedisStore, which needs a client that matches the RedisClientLike interface (the ioredis client works out of the box).

Note: A MemoryStore exists in the repository for internal unit tests, but it is not exported and is not part of the published package API.

Example

See example/server.ts.

About

Multi-algorithm rate limiting middleware for Express and Fastify with a Redis-backed store — supports fixed window, sliding window, and token bucket.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors