Book Image

Mastering Web Application Development with Express

By : Alexandru Vladutu
Book Image

Mastering Web Application Development with Express

By: Alexandru Vladutu

Overview of this book

Table of Contents (18 chapters)
Mastering Web Application Development with Express
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

API rate limiting


Sometimes, we may want to rate limit our API to prevent abuse or because the system can handle a limited amount of requests per second. There are several ways to rate limit our API, such as by limiting the number of requests by IP address or username. If we choose to implement rate limiting based on the username, we can create a middleware that can be reused for all the routes that require authentication.

There is an excellent module by TJ Holowaychuk (the creator of Express) called node-ratelimiter (https://github.com/visionmedia/node-ratelimiter) that will basically do all the heavy lifting for us.

We create a configurable middleware that takes three arguments: the database connection to Redis (the in-memory database needed by the rate limiter), the maximum number of requests allowed in the time frame specified, and the duration of the limit. Here's how our middleware will look:

var Limiter = require('ratelimiter');
var ms = require('ms');

module.exports = function(db,...