Speed โ€‹โ€‹limit to prevent malicious behavior in ExpressJS

Someone told me about some shortcomings in the application I'm working on (mainly in my JavaScript on the interface), which leaves it possible, say, to immediately press a ton of buttons and send tons of transactional emails. This is clearly not good.

I think one way to handle this in ExpressJS is to use app.all() to count the number of requests that occur over a period of time. I would save this in session metadata with timestamps, and if more than X requests occur Y times, I will cut them off for a while before the expiration date.

Has anyone done this before or had tips / tricks to help me? Something that is easy to enter and exit my application is preferable. Thanks!

+8
javascript rate-limiting express
source share
1 answer

You can use the Collate object on your web page.

 function Collate(timeout) { this.timeout = timeout || 1000; } Collate.prototype = { time: 0, idle: function() { var t = new Date().getTime(); return (t - this.time > this.timeout && (this.time = t)); }, prefer: function(func) { this.func = func; clearTimeout(this.timer); this.timer = setTimeout(func, this.timeout); } }; 

If you want the function to run once and not run again within the next 1 second. For example, if you want the user to not submit the form many times, you do this:

 var timer = new Collate(3000); //3 seconds button1.onclick = function() { if(timer.idle()) { button1.form.submit(); } else alert("Don't click too quickly!"); } //or on the form tag <script>var submitTimer = new Collate(3000);</script> <form action="post" onsubmit="return submitTimer.idle();"> 

If you expect the event to fire several times and only want to respond the last time it fires. For example, if you want to search after the user has finished typing, you will do the following:

 var timer = new Collate(700); //0.7 seconds textfield1.onkeyup = function() { timer.prefer(function() { autocomplete.search(textfield1.value); }); }; 
+2
source share

All Articles