-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrateLimitedMiddleware.tsx
39 lines (30 loc) · 1.22 KB
/
rateLimitedMiddleware.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { get, set } from 'lodash';
import { NextApiRequest, NextApiResponse } from 'next';
const rateLimit = 15; // Number of allowed requests per minute
export const checker = (ip: any, rateLimiter: {}) => {
const now = Date.now();
const windowStart = now - 60 * 1000; // 1 minute ago
//The _.get() method in Lodash retrieves the object’s value at a specific path.
//_.get(object, path, defaultValue)
const requestTimestamps: number[] = get(rateLimiter, ip, []).filter(
timestamp => timestamp > windowStart
);
requestTimestamps.push(now);
//The _.set() method in Lodash is used to set the value at a specific path of the object.
//_.set(object, path, value)
set(rateLimiter, ip, requestTimestamps);
//returning boolean value
return requestTimestamps.length <= rateLimit;
};
const rateLimiterMiddleware = (req: NextApiRequest, res: NextApiResponse, rateLimiter: {}) => {
const ip = req.headers['x-real-ip'] || req.connection.remoteAddress;
const rateLimitOk = checker(ip, rateLimiter);
if (!rateLimitOk) {
res
.status(429)
.json({ message: 'Blocked. Too Many Requests. Make another request after 1 minute.' });
return false;
}
return true;
};
export default rateLimiterMiddleware;