Express Rate Limiting

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 app.js file:

const express = require('express');
const app = express();
const rateLimit = require('express-rate-limit');
const slowDown = require('express-slow-down');

// Load middleware
...
const apiLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 100
});

const speedLimiter = slowDown({
windowMs: 1 * 60 * 1000, // 1 minute
delayAfter: 10,
delayMs: 500
});

app.use('/api/', apiLimiter);
app.use('/api/', speedLimiter);

// Load & use routes
...

// Start app
...

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.