How to Implement Rate Limiting in Express.js Using express-rate-limit
🔒 Rate Limiting in Express.js Rate limiting is a critical part of modern web applications that helps prevent abuse by restricting the number of requests a user or IP can make within...

🔒 Rate Limiting in Express.js
Rate limiting is a critical part of modern web applications that helps prevent abuse by restricting the number of requests a user or IP can make within a certain timeframe. It's especially useful to defend against brute-force attacks, spamming, or denial-of-service (DoS) attempts.
🚀 What is Rate Limiting?
Rate limiting is a strategy used to control the amount of incoming traffic to a server. For example, you might allow 100 requests per 15 minutes for each IP address. If the limit is exceeded, the server returns a 429 (Too Many Requests) response.
🛠️ Installing express-rate-limit
Express provides a middleware called express-rate-limit which makes implementation simple. First, install it using npm or your preferred package manager:
npm install express-rate-limit
⚙️ Basic Usage
Here's a simple implementation:
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Define the rate limit rule
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
});
// Apply the limiter to all requests
app.use(limiter);
// A simple route
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
🎯 Applying Rate Limiting to Specific Routes
You can also apply rate limiting only to specific routes instead of the entire app:
// Only apply rate limit to /api routes
app.use('/api', limiter);
📌 Customizing Response
You can fully customize the response returned when the limit is hit:
const customLimiter = rateLimit({
windowMs: 10 * 60 * 1000,
max: 20,
handler: (req, res) => {
res.status(429).json({
status: 'error',
message: 'You have exceeded the 20 requests in 10 mins limit!',
});
},
});
✅ Best Practices
- Use different limits for public APIs and user-authenticated routes.
- Combine with authentication and IP logging for enhanced protection.
- Use a distributed store like Redis if you're running multiple server instances.
📦 Bonus: Using Redis Store
To make rate limiting work across multiple servers, you can use a Redis store:
npm install rate-limit-redis
const RedisStore = require('rate-limit-redis');
const Redis = require('ioredis');
const redisClient = new Redis();
const limiterWithRedis = rateLimit({
store: new RedisStore({
sendCommand: (...args) => redisClient.call(...args),
}),
windowMs: 15 * 60 * 1000,
max: 100,
});
📘 Conclusion
Rate limiting is an essential tool to secure your Express.js apps. With the express-rate-limit package, implementation is quick and customizable. Always consider adding it to your production apps to ensure safety and performance.

Tech Ahmed
Related Articles

Caddy vs Nginx vs Apache: Which Web Server Should You Use?
Caddy vs Nginx vs Apache — Which Web Server Should You Use? TL;DR: Legacy & shared hosting → Apache • High-traffic & reverse proxy → Nginx • Fast setup & automatic HTTPS → Caddy Table of...

How to Upload Files in Express.js Using Multer and Upload to AWS S3
How to Upload Files in Express.js to AWS S3 Using AWS SDK v3 and Multer Uploading files to AWS S3 is a common task in many backend applications. In this tutorial, you'll learn how to build a clean Ex...

SQL vs NoSQL – PostgreSQL vs MongoDB with Real Use Case, Performance & Code Comparison
SQL vs NoSQL: Comparing PostgreSQL and MongoDB with Real-World Examples Choosing the right database is a key decision that directly impacts the scalability, performance, and maintainability of your a...