mirror of
https://github.com/goldbergyoni/nodebestpractices.git
synced 2025-10-28 19:43:38 +08:00
Update limitrequests.md
Add common example, which is suitable for any framework or pure NodeJS
This commit is contained in:
@ -2,7 +2,44 @@
|
|||||||
|
|
||||||
### One Paragraph Explainer
|
### One Paragraph Explainer
|
||||||
|
|
||||||
Rate limiting should be implemented in your application to protect a Node.js application from being overwhelmed by too many requests at the same time. Rate limiting is a task best performed with a service designed for this task, such as nginx, however it is also possible with application middleware such as [express-rate-limiter](https://www.npmjs.com/package/express-rate-limit).
|
Rate limiting should be implemented in your application to protect a Node.js application from being overwhelmed by too many requests at the same time. Rate limiting is a task best performed with a service designed for this task, such as nginx, however it is also possible with [rate-limiter-flexible](https://www.npmjs.com/package/rate-limiter-flexible) package or middleware such as [express-rate-limiter](https://www.npmjs.com/package/express-rate-limit) for Express.js applications.
|
||||||
|
|
||||||
|
### Code example: pure NodeJS app with [rate-limiter-flexible](https://www.npmjs.com/package/rate-limiter-flexible)
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const http = require('http');
|
||||||
|
const redis = require('redis');
|
||||||
|
|
||||||
|
const { RateLimiterRedis } = require('rate-limiter-flexible');
|
||||||
|
|
||||||
|
const redisClient = redis.createClient({
|
||||||
|
enable_offline_queue: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Maximum 50 requests per second
|
||||||
|
const rateLimiter = new RateLimiterRedis({
|
||||||
|
storeClient: redisClient,
|
||||||
|
points: 50,
|
||||||
|
duration: 1,
|
||||||
|
inmemoryBlockOnConsumed: 51, // If user consumes >=51 points per second
|
||||||
|
inmemoryBlockDuration: 60, // Block it for a minute in memory, so no requests go to Redis
|
||||||
|
});
|
||||||
|
|
||||||
|
http.createServer((req, res) => {
|
||||||
|
rateLimiter.consume(req.socket.remoteAddress)
|
||||||
|
.then((rateLimiterRes) => {
|
||||||
|
// Some app logic here
|
||||||
|
|
||||||
|
res.writeHead(200);
|
||||||
|
res.end()
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
res.writeHead(429);
|
||||||
|
res.end('Too Many Requests')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}).listen(3000);
|
||||||
|
```
|
||||||
|
|
||||||
### Code example: Express rate limiting middleware for certain routes
|
### Code example: Express rate limiting middleware for certain routes
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user