Fix API Rate Limit Exhaustion in Express
API Rate Limit Exhaustion is a critical vulnerability that allows attackers to perform Denial of Service (DoS), brute-force authentication, or scrape sensitive data by overwhelming the server with requests. In Express, the default behavior is to process every incoming request until the event loop or downstream resources (like your DB) crash. To mitigate this, we must implement a middleware layer that tracks request counts per IP address and enforces a quota.
The Vulnerable Pattern
const express = require('express'); const app = express();// VULNERABLE: No rate limiting implemented. // An attacker can send 10,000 requests/sec to exhaust CPU/Memory/DB connections. app.post(‘/api/v1/login’, (req, res) => { const { username, password } = req.body; // Logic for auth… res.status(200).json({ message: ‘Success’ }); });
app.listen(3000);
The Secure Implementation
The secure implementation uses 'express-rate-limit' to track client IPs within a sliding window. When a client exceeds 100 requests in 15 minutes, the middleware intercepts the request and returns a 429 'Too Many Requests' status, preventing the application logic from even executing. For distributed systems, I recommend using 'rate-limit-redis' as a store; otherwise, the limit is only enforced per individual server instance, which attackers can bypass by hitting different nodes in a load-balanced cluster.
const express = require('express'); const rateLimit = require('express-rate-limit'); const app = express();// SECURE: Enforce strict limits on sensitive endpoints const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Limit each IP to 100 requests per window standardHeaders: ‘draft-7’, // Use standard RateLimit headers legacyHeaders: false, message: { status: 429, error: ‘Too many requests, please try again later.’ } });
// Apply the limiter to all API routes app.use(‘/api/’, apiLimiter);
app.post(‘/api/v1/login’, (req, res) => { res.status(200).json({ message: ‘Success’ }); });
app.listen(3000);
Your Express API
might be exposed to API Rate Limit Exhaustion
74% of Express apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.