Skip to content

Express Middleware

Roman edited this page Jan 4, 2019 · 15 revisions

Express Middleware

Create middleware/rateLimiterRedis.js

const redis = require('redis');
const {RateLimiterRedis} = require('rate-limiter-flexible');

const redisClient = redis.createClient({
  host: 'redis',
  port: 6379,
  enable_offline_queue: false,
});

const rateLimiter = new RateLimiterRedis({
  redis: redisClient,
  keyPrefix: 'middleware',
  points: 10, // 10 requests
  duration: 1, // per 1 second by IP
});

const rateLimiterMiddleware = (req, res, next) => {
  rateLimiter.consume(req.connection.remoteAddress)
    .then(() => {
      next();
    })
    .catch(() => {
      res.status(429).send('Too Many Requests');
    });
};

module.exports = rateLimiterMiddleware;

See all options here

Import created middleware and use it

const express = require('express');
const rateLimiterRedisMiddleware = require('./middleware/rateLimiterRedis');

const app = express();
app.use(rateLimiterRedisMiddleware);

Middleware with different logic and limiters can be applied to exact route or application part as well.

Mongo, Memcache, MySQL or any other limiter from this package can be used with the same approach.