Skip to content

Instantly share code, notes, and snippets.

@Prosen-Ghosh
Created January 22, 2023 14:41
Show Gist options
  • Save Prosen-Ghosh/dc11ce700b3002a40191020210a63678 to your computer and use it in GitHub Desktop.
Save Prosen-Ghosh/dc11ce700b3002a40191020210a63678 to your computer and use it in GitHub Desktop.
const Redis = require("ioredis");
const redis = new Redis();
app.use(async (req, res, next) => {
const userIp = req.ip;
const currentTime = Date.now();
const rateLimit = 100; // Number of requests per hour
const rateLimitPeriod = 3600; // 1 hour
const rateLimitKey = `rate_limit:${userIp}`;
const requests = await redis.lrange(rateLimitKey, 0, -1);
const filteredRequests = requests.filter(r => currentTime - r < rateLimitPeriod);
await redis.ltrim(rateLimitKey, filteredRequests.length, -1);
await redis.rpush(rateLimitKey, currentTime);
if (filteredRequests.length >= rateLimit) {
return res.status(429).send("Too Many Requests");
}
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment