express-rate-shield
v1.0.0
Published
Custom Express rate limiter middleware in TypeScript to protect your APIs from excessive requests.
Maintainers
Readme
Express Rate Shield - Express Rate Limiting Middleware
A lightweight, high-performance rate limiting middleware for Express.js and Node.js applications. Protect your APIs from abuse with configurable request throttling per IP address.
Overview
express-rate-shield is a simple yet powerful TypeScript-based rate limiting solution designed to prevent API abuse, DDoS attacks, and excessive requests. It tracks incoming requests by IP address and enforces rate limits with minimal overhead.
Key Features
- ⚡ Lightweight & Fast - Minimal memory footprint with efficient IP tracking
- 🔒 Secure - Prevents abuse and protects API endpoints from excessive requests
- 🎯 Easy Integration - Simple Express.js middleware setup
- 📊 Rate Limit Headers - Standard HTTP headers (X-RateLimit-*) for client transparency
- 🌍 Proxy Support - Respects X-Forwarded-For headers for proxy environments
- 💾 Auto Cleanup - Automatic memory management with timestamp cleanup
- 🧪 TypeScript Ready - Full TypeScript support with type definitions
Installation
npm install express-rate-shieldOr with yarn:
yarn add express-rate-shieldQuick Start
import express from "express";
import { rateLimiter } from "rate-limit";
const app = express();
// Create rate limiter: max 100 requests per 15 minutes
const limiter = new rateLimiter({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // max 100 requests per window
message: { error: "Too many requests, please try again later." },
});
// Apply to all routes
app.use(limiter.handler());
// Or apply to specific routes
app.get("/api/data", limiter.handler(), (req, res) => {
res.json({ data: "your data" });
});
app.listen(3000);Configuration Options
RateLimiterOptions
interface rateLimiterOptions {
windowMs: number; // Time window in milliseconds
max: number; // Max requests per window
message?: message; // Custom error message
headers?: boolean; // Enable/disable rate limit headers (default: true)
}Parameters
| Parameter | Type | Default | Description |
| ---------- | ------- | ------------------------------------------------ | ----------------------------------------------------------------- |
| windowMs | number | required | Time window in milliseconds (e.g., 15 _ 60 _ 1000 for 15 minutes) |
| max | number | required | Maximum number of requests allowed per time window |
| message | object | { error: 'too many request please try again' } | Custom error response message |
| headers | boolean | true | Include rate limit information in response headers |
Examples
Basic API Protection
import express from "express";
import { rateLimiter } from "express-rate-shield";
const app = express();
const apiLimiter = new rateLimiter({
windowMs: 60 * 1000, // 1 minute window
max: 30, // 30 requests per minute
});
app.use("/api/", apiLimiter.handler());Strict Login Protection
const loginLimiter = new rateLimiter({
windowMs: 15 * 60 * 1000, // 15 minute window
max: 5, // Only 5 attempts per 15 minutes
message: { error: "Too many login attempts, please try again later." },
});
app.post("/login", loginLimiter.handler(), (req, res) => {
// Handle login
});Custom Error Messages
const customLimiter = new rateLimiter({
windowMs: 10 * 60 * 1000,
max: 100,
message: {
error:
"API rate limit exceeded. Please upgrade your plan for higher limits.",
},
});Disable Response Headers
const limiter = new rateLimiter({
windowMs: 60 * 1000,
max: 50,
headers: false, // Disable X-RateLimit-* headers
});Response Headers
When headers are enabled (default), the middleware adds the following headers:
X-RateLimit-Limit- Maximum requests per windowX-RateLimit-Remaining- Remaining requests in current windowRetry-After- Seconds to wait before retrying (when rate limit exceeded)
Error Responses
When rate limit is exceeded, the middleware returns:
{
"status": 429,
"message": "Too many requests, please try again later."
}HTTP Status Code: 429 Too Many Requests
How It Works
- IP Detection - Identifies user IP from request (respects X-Forwarded-For for proxies)
- Request Tracking - Records request timestamps per IP address
- Window Validation - Checks if requests exceed limit in current time window
- Cleanup - Automatically removes old timestamps outside the window
- Response - Allows request to proceed or returns 429 status
Performance
- Memory Efficient - Only stores IP addresses and timestamps
- Automatic Cleanup - Expired timestamps are automatically removed
- Fast Lookups - Uses JavaScript Map for O(1) lookups
- Minimal Overhead - Minimal impact on request latency
Use Cases
- ✅ Prevent API abuse and DDoS attacks
- ✅ Protect login endpoints from brute-force attacks
- ✅ Control resource consumption
- ✅ Enforce API pricing tiers
- ✅ Protect public endpoints from scraping
- ✅ Implement fair usage policies
Proxy & Load Balancer Support
The middleware respects the X-Forwarded-For header, making it suitable for applications behind proxies and load balancers:
// Correctly identifies client IP through proxies
app.use(limiter.handler());Best Practices
- Choose Appropriate Limits - Set limits based on expected traffic patterns
- Use Descriptive Messages - Help users understand rate limiting
- Monitor Usage - Track rate limit violations to detect attacks
- Combine Strategies - Use different limits for different endpoints
- Test Before Production - Verify limits don't block legitimate users
TypeScript Support
Full TypeScript support with exported types:
import { rateLimiter, rateLimiterOptions } from "rate-limit";
const options: rateLimiterOptions = {
windowMs: 60 * 1000,
max: 100,
};
const limiter = new rateLimiter(options);License
See LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
Support
For issues, questions, or suggestions, please open an issue on the project repository.
rate-limit - Simple. Secure. Scalable rate limiting for Node.js and Express.js
