Developerbreeze Development Tutorials, Guides & Insights
Unlock 1+ expert-curated developerbreeze tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your developerbreeze skills on DeveloperBreeze.
Adblocker Detected
It looks like you're using an adblocker. Our website relies on ads to keep running. Please consider disabling your adblocker to support us and access the content.
Build a Custom Rate Limiter in Node.js with Redis
Tutorial April 04, 2025
// redisClient.js
const redis = require("redis");
const client = redis.createClient({ url: process.env.REDIS_URL });
client.on("error", (err) => console.error("Redis error:", err));
client.connect();
module.exports = client;// rateLimiter.js
const client = require("./redisClient");
const rateLimiter = (limit = 100, windowSec = 3600) => {
return async (req, res, next) => {
const ip = req.ip;
const key = `rate_limit:${ip}`;
const current = await client.get(key);
if (current !== null && parseInt(current) >= limit) {
return res.status(429).json({ error: "Too many requests. Try later." });
}
const multi = client.multi();
multi.incr(key);
if (!current) {
multi.expire(key, windowSec);
}
await multi.exec();
next();
};
};
module.exports = rateLimiter;