-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Backend] Introduce rate limit to some routes
- Loading branch information
1 parent
1b62cdd
commit ad61685
Showing
4 changed files
with
62 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { createClient } from "redis"; | ||
|
||
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}`; | ||
const requests = await redis.incr(redisId); | ||
if (requests === 1) { | ||
await redis.expire(redisId, 60); | ||
} | ||
if (requests > limit) { | ||
res.locals.message = "Rate limit exceeded"; | ||
return res.status(429).json({ | ||
success: false, | ||
message: "Requests over limit, please wait for some time.", | ||
data: null, | ||
}); | ||
} | ||
next(); | ||
}; | ||
|
||
export { rateLimit }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters