# express-rate-limit

## Overview

express-rate-limit is a TypeScript middleware library that provides IP-based rate limiting for Express.js applications. It protects applications from abuse by limiting the number of requests that can be made by a single client within a specified time window. 

Key features include:
- Flexible configuration options for rate limits and time windows
- Built-in memory storage for single-server deployments
- Support for external storage backends (Redis, Memcached, etc.)
- IPv6 subnet-aware rate limiting
- Multiple standardized header formats (legacy, draft-6, draft-7, draft-8)
- Request filtering based on success/failure status
- Comprehensive TypeScript support with full type definitions

## Package Information

**Name:** express-rate-limit  
**Type:** Express.js middleware library  
**Language:** TypeScript  

**Installation:**
```bash
npm install express-rate-limit
```

## Core Imports

```typescript { .api }
// ESM (recommended)
import rateLimit from "express-rate-limit";
// or named import
import { rateLimit } from "express-rate-limit";

// Additional utilities
import { MemoryStore, ipKeyGenerator } from "express-rate-limit";

// CommonJS
const rateLimit = require("express-rate-limit");
const { MemoryStore, ipKeyGenerator } = require("express-rate-limit");
```

## Basic Usage

```typescript { .api }
import express from "express";
import rateLimit from "express-rate-limit";

const app = express();

// Basic rate limiting - 100 requests per 15 minutes per IP
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  limit: 100, // Limit each IP to 100 requests per windowMs
  message: "Too many requests from this IP, please try again later.",
  standardHeaders: "draft-7", // Return rate limit info in headers
  legacyHeaders: false, // Disable the X-RateLimit-* headers
});

// Apply to all requests
app.use(limiter);

// Apply to specific routes
app.get("/api/sensitive", limiter, (req, res) => {
  res.send("Protected endpoint");
});
```

## Core Types

```typescript { .api }
interface Options {
  // Time window in milliseconds (default: 60000)
  windowMs: number;
  
  // Maximum number of requests per window (default: 5)
  limit: number | ValueDeterminingMiddleware<number>;
  
  // Response message when limit is exceeded (default: "Too many requests, please try again later.")
  message: any | ValueDeterminingMiddleware<any>;
  
  // HTTP status code for rate-limited responses (default: 429)
  statusCode: number;
  
  // Enable legacy X-RateLimit-* headers (default: true)
  legacyHeaders: boolean;
  
  // Enable standardized RateLimit headers (default: false)
  standardHeaders: boolean | DraftHeadersVersion;
  
  // Policy identifier for draft-8 headers (default: dynamic based on limit and window)
  identifier: string | ValueDeterminingMiddleware<string>;
  
  // Custom key generator function (default: IP-based with IPv6 subnet)
  keyGenerator: ValueDeterminingMiddleware<string>;
  
  // IPv6 subnet mask for grouping IPv6 addresses (default: 56)
  ipv6Subnet: number | ValueDeterminingMiddleware<number> | false;
  
  // Storage backend for rate limit data (default: MemoryStore)
  store: Store | LegacyStore;
  
  // Skip failed requests (4xx/5xx status codes) (default: false)
  skipFailedRequests: boolean;
  
  // Skip successful requests (2xx/3xx status codes) (default: false)
  skipSuccessfulRequests: boolean;
  
  // Custom handler for rate limit exceeded events
  handler: RateLimitExceededEventHandler;
  
  // Skip requests based on custom logic (default: never skip)
  skip: ValueDeterminingMiddleware<boolean>;
  
  // Custom logic to determine request success (default: status < 400)
  requestWasSuccessful: ValueDeterminingMiddleware<boolean>;
  
  // Allow requests if store encounters errors (default: false)
  passOnStoreError: boolean;
  
  // Property name for rate limit info on request object (default: "rateLimit")
  requestPropertyName: string;
  
  // Validation configuration (default: true)
  validate: boolean | EnabledValidations;
  
  // DEPRECATED: Use legacyHeaders instead
  headers?: boolean;
  
  // DEPRECATED: Use limit instead  
  max?: number | ValueDeterminingMiddleware<number>;
}

type ValueDeterminingMiddleware<T> = (
  request: Request,
  response: Response,
) => T | Promise<T>;

type DraftHeadersVersion = "draft-6" | "draft-7" | "draft-8";

interface RateLimitInfo {
  limit: number;
  used: number;
  remaining: number;
  resetTime: Date | undefined;
  key: string;
}
```

## Main API

```typescript { .api }
// Primary middleware factory function
function rateLimit(options?: Partial<Options>): RateLimitRequestHandler;

// Enhanced request handler with additional methods
interface RateLimitRequestHandler extends RequestHandler {
  // Reset hit counter for specific client
  resetKey(key: string): void;
  
  // Get hit count and reset time for specific client
  getKey(key: string): Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
}

interface ClientRateLimitInfo {
  totalHits: number;
  resetTime: Date | undefined;
}
```

## Capabilities

### [Configuration Options](./configuration.md)
Comprehensive configuration options for customizing rate limiting behavior including time windows, limits, headers, request filtering, and validation settings.

Key options:
- **windowMs**: Time window duration
- **limit**: Request limit (static or dynamic)
- **message**: Custom response messages
- **headers**: Multiple header standard support
- **keyGenerator**: Custom client identification
- **ipv6Subnet**: IPv6 subnet grouping

### [Storage Backends](./stores.md)
Built-in memory storage and extensible store interface for external backends like Redis and Memcached.

Key components:
- **MemoryStore**: Built-in in-memory storage
- **Store interface**: For custom storage implementations
- **Legacy store support**: Backward compatibility
- **Store methods**: increment, decrement, reset operations

### [Advanced Middleware Patterns](./middleware.md)
Advanced usage patterns including custom handlers, request filtering, key generation, and integration strategies.

Key patterns:
- **Custom handlers**: Rate limit exceeded responses
- **Request filtering**: Skip based on success/failure
- **Key generation**: Custom client identification
- **IPv6 handling**: Subnet-aware rate limiting
- **Validation system**: Configuration validation and warnings

## Utility Functions

```typescript { .api }
// IP-based key generation with IPv6 subnet support
function ipKeyGenerator(ip: string, ipv6Subnet: number | false = 56): string;
```

The `ipKeyGenerator` function processes IP addresses for rate limiting keys:
- IPv4 addresses are returned as-is
- IPv6 addresses are converted to subnet notation (e.g., `2001:db8::/56`)
- Supports configurable subnet mask (default: 56-bit)
- Used internally by default keyGenerator, available for custom implementations