Limiting the number of request by user in any given hour [Nodejs]

550 views Asked by At

I'm building a server side application using Nodejs and Express and for some reason i was thinking about how to limit the number of request by user in a fixed amount of time to prevent hackers from spamming and trying to break down the server.

I am a little concerned with people abusing/spamming the available services with a large number of requests.

so is there any idea about how to build an express middleware that allows me to control the number of request send by specific user based on his access_token



the questions are:

1) how to build this middleware and what is the best way to do this?

2) is there any module that can do the job?

3) is there any other solution or a structure that allows me to secure my server against this kind of attack?

All suggestions are welcome.

2

There are 2 answers

0
colefner On

There's a bunch of existing modules out there, but this seems to be what you're looking for:

https://www.npmjs.com/package/tokenthrottle

In the Node community there is almost always a module to do all or part of what you're looking for. You almost never have to reinvent the wheel.

2
Jonas Wilms On

Just collect the request ips/whatever in a Map that keeps a counter running. When the counter hits a certain just show an error page:

const app = Express();

const ips = new Map; 
const limit = 20;

app.use((req, res, next) => {
  const count = ips.get(req.ip) || 0;
  if(count < 20){
    ips.set(req.ip, count + 1);
    next();
  } else {
   res.end("spam filter activated, sorry :(");
  }
});

// ... your endpoints

app.listen(80);

That will block certain ips until you restart the server. However you could also reset the Map at a certain interval:

setInterval(() => ips.clear(), 60 * 60 * 1000);