Express Production Setup - 2 | Rate Limiting | DDOS
Simple Rate Limiter In Memory
index.js
const express = require("express")
const initRateLimiter = require("./rate-limiter")
const app = express()
// add for all route
// app.use(initRateLimiter);
app.get("/", (req, res) => {
res.send("hello")
})
// added only for rate route
app.get("/rate", initRateLimiter, (req, res) => {
res.send("ok")
})
app.listen(3000, () => console.log("app runnning on port 3000"))
rate-limiter.js
const { RateLimiterMemory, RateLimiterRedis } = require('rate-limiter-flexible');
// Configure the rate limiter
const rateLimiter = new RateLimiterMemory({
points: 10, // Number of requests
duration: 10, // Per second
blockDuration: 10,
});
const initRateLimiter = (req, res, next) => {
rateLimiter.consume(req.ip)
.then(() => {
next();
})
.catch(() => {
res.status(429).send('Too Many Requests'); // 429 to many request response code
});
}
module.exports = initRateLimiter;
Using radis
const { RateLimiterRedis } = require('rate-limiter-flexible');
const Redis = require('ioredis');
// Create a Redis client
const redisClient = new Redis({
host: '127.0.0.1', // Redis server host
port: 6379, // Redis server port
password: 'your-redis-password', // If you have a password set for Redis
});
// Configure the rate limiter with Redis
const rateLimiter = new RateLimiterRedis({
storeClient: redisClient,
points: 10, // Number of requests
duration: 10, // Per 10 seconds
blockDuration: 10, // Block for 10 seconds if limit is exceeded
});
// Middleware to apply rate limiting
const initRateLimiter = (req, res, next) => {
rateLimiter.consume(req.ip)
.then(() => {
next(); // Proceed to the next middleware/route handler
})
.catch((rejRes) => {
if (rejRes.remainingPoints === 0) {
// User is blocked, reset their points after blockDuration
rateLimiter.penalty(req.ip, 1) // Add a penalty point to block immediately
.then(() => {
setTimeout(() => {
rateLimiter.delete(req.ip); // Reset the rate limiter for this user
}, rejRes.msBeforeNext); // Wait for the blocking duration to end
});
}
res.status(429).send('Too Many Requests'); // 429 Too Many Requests response code
});
}
module.exports = initRateLimiter;
Comments
Post a Comment