4

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?

Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100

1 Answers1

3

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.

Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100
Kevin Law
  • 814
  • 4
  • 15
  • Thanks. How do you know that it doesn't care about the incoming IP? I have taken a look at express-rate-limit and express-limiter but they don't seem to limit the transfer rate. They only limit the number of messages. – Chong Lip Phang May 22 '18 at 08:25
  • 1
    You could found the [source code](limiter) of **limiter** from github, it's pretty short, you could read it if you got time. What do you mean by **transfer rate**? – Kevin Law May 22 '18 at 08:49
  • I am referring to a functionality similar to TokenBucket in limiter. – Chong Lip Phang May 22 '18 at 08:51