Today I learned how to limit requests to an API in an Express app, and it turned out to be pretty simple with two npm packages:
express-rate-limit stops the API from responding to requests after a certain number of requests is reached.
express-slow-down incrementally slows down responses from the API after a certain number of requests is reached. For example if you set the limit to 10 requests and the delay time to 500 milliseconds, the 11th request will be held for 500ms, the 12th for 1 second, the 13th for 1.5 seconds, and so on.
These middlewares can be implemented into an app by creating new modules out of them, or adding them directly into the API’s
const express = require('express');
To test it, you can make the limits really low and then make requests to the API either in Postman or from the app that consumes the API. When testing in the browser, errors will display in the console, so you can see which ones may need to be handled differently.
This is a really simple implementation thanks to these packages, but you can also do this from scratch. There are also different types of rate limiting which I read about in this article, which may be of interest for further reading.