Skip to content

Commit

Permalink
[Backend] Rate limit based on user id with fallback to ip address
Browse files Browse the repository at this point in the history
  • Loading branch information
MananGandhi1810 committed Nov 14, 2024
1 parent 54ffc78 commit 5b9b3be
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions backend/middlewares/rate-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ const redis = createClient({ url: process.env.REDIS_URL });
redis.connect();

const rateLimit = async (req, res, next, limit = 5, use = "") => {
const ip =
req.headers["x-forwarded-for"] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
const redisId = `rate-limit:${use}/${ip}`;
var key;
if (req.user) {
key = req.user.id;
} else {
key =
req.headers["x-forwarded-for"] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
}
console.log(key);
const redisId = `rate-limit:${use}/${key}`;
const requests = await redis.incr(redisId);
if (requests === 1) {
await redis.expire(redisId, 60);
Expand Down

0 comments on commit 5b9b3be

Please sign in to comment.