Rate Limiting in Node with Express
Rate Limiting is Most Common Practice to Limit The Incoming Request of API's
Rate Limit in Node.js - Education Funda |
Let's see how we can achieve it easily in Node with Express framework:
- You need to install rate limit package via ~$ npm i express-rate-limit.
import * as RateLimit from 'express-rate-limit';
const env = process.env.NODE_ENV || 'dev';
const rateLimitRequest = Number(process.env.RATE_LIMIT_TIME) || 15;
const rateLimitTime = Number(process.env.RATE_LIMIT_REQUEST) || 100;
export default () => {
if (env === 'production') {
return new RateLimit({
windowMs: rateLimitTime * 60 * 1000, // 15 minutes
max: rateLimitRequest, // limit each IP to 30 requests per windowMs
delayMs: 0,
handler: 'Rate limt exceeded, please try again later some time.',
});
}
return new RateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 3000, // limit each IP to 3000 requests per windowMs
delayMs: 0,
handler: 'Rate limit exceeded, please try again later some time.',
});
};
Now in our Routes or Validation index file we can simply add it to all routes or if we want then we can add it in single route as well:
import rateLimiter from './middleware/rateLimit';
app.use(rateLimiter()); // apply to all requests
That's it!
<> Happy Coding </>
Comments
Post a Comment