API Rate Limiting with Express
๐ก️ API Rate Limiting with Express
✅ What is API Rate Limiting?
Rate limiting is a technique used to control the number of requests a client can make to your API over a certain period of time. It helps:
Prevent abuse (e.g. DDoS attacks, brute-force login attempts)
Protect your server from being overwhelmed
Ensure fair usage across users
๐ Setting Up Rate Limiting in Express
๐ฆ Step 1: Install the express-rate-limit Package
This is a popular middleware for rate limiting in Express.
bash
Copy
Edit
npm install express-rate-limit
๐ ️ Step 2: Basic Usage in Express App
javascript
Copy
Edit
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Create a rate limiter
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.',
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
// Apply rate limiter to all requests
app.use(limiter);
app.get('/', (req, res) => {
res.send('Hello, this is a rate-limited API!');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
๐ง Customizing the Rate Limiter
You can customize the limiter based on your needs:
javascript
Copy
Edit
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Max 5 login attempts
message: 'Too many login attempts. Please try again in 5 minutes.',
});
Apply it only to a specific route:
javascript
Copy
Edit
app.post('/login', loginLimiter, (req, res) => {
// Handle login
});
๐ง Best Practices
Apply stricter limits on sensitive routes (e.g., /login, /signup).
Use Redis or a database for distributed rate limiting in production (e.g., across multiple servers).
Combine with IP whitelisting or authentication tokens for smarter control.
Provide useful feedback (e.g., Retry-After headers).
๐ Advanced: Using Redis Store
To share rate limiting data across multiple servers (stateless scaling), use Redis:
bash
Copy
Edit
npm install rate-limit-redis ioredis
Then configure it like:
javascript
Copy
Edit
const RedisStore = require('rate-limit-redis');
const Redis = require('ioredis');
const limiter = rateLimit({
store: new RedisStore({
sendCommand: (...args) => redisClient.call(...args),
}),
windowMs: 1 * 60 * 1000, // 1 minute
max: 60,
});
๐งพ Summary
Feature Description
windowMs Time window in milliseconds
max Max requests per IP in that window
message Message returned when limit is exceeded
headers Send standard or legacy headers
store Optional backing store (like Redis)
Learn MERN Stack Course in Hyderabad
Read More
Logging with Morgan and Winston
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment