Reputation: 9279
I am trying to implement some anti-spamming mechanism into my app. I came across the limiter package.
I am confused after reading their example:
var RateLimiter = require('limiter').RateLimiter;
var limiter = new RateLimiter(150, 'hour', true); // fire CB immediately
// Immediately send 429 header to client when rate limiting is in effect
limiter.removeTokens(1, function(err, remainingRequests) {
if (remainingRequests < 1) {
response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
response.end('429 Too Many Requests - your IP is being rate limited');
} else {
callMyMessageSendingFunction(...);
}
});
Where is 'response' defined? Don't we need to hook the limiter to a path with app.use()? How does the limiter know the incoming IP otherwise?
Upvotes: 4
Views: 1936
Reputation: 852
I've tried this package some days ago. This package is used to record the request count in a period of time. It doesn't matter where the request comes from. So this package doesn't care what the incoming IP address is.
It's true that we need to add code to the application middle-ware to limit the whole application or a route middle-ware for a specified route. Then you can get the response object. The following is a simple usage.
var express = require('express')
var app = express()
app.use(function (req, response, next) {
limiter.removeTokens(1, function(err, remainingRequests) {
if (remainingRequests < 1) {
response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
response.end('429 Too Many Requests - your IP is being rate limited');
} else {
next();
}
});
})
If you want to track the specified IP addresses. I'd recommend express-rate-limit and express-limiter.
Upvotes: 3