DEV Community

Jayvee Ramos
Jayvee Ramos

Posted on

4

Dynamic rate-limiting middleware in Express

To create a dynamic rate-limiting middleware in Express that can be used at different levels (controller, app, router), you can use the express-rate-limit package. This middleware can be configured dynamically based on the parameters you pass.

Here's an example of a custom rate-limiting middleware that can be used at different levels in Express:

First, install the express-rate-limit package:

npm install express-rate-limit
Enter fullscreen mode Exit fullscreen mode

Then, create a module that exports a function to generate the rate-limiting middleware dynamically:

// rateLimitMiddleware.js

const rateLimit = require("express-rate-limit");

function createRateLimitMiddleware(options) {
  // You can configure the rate limit dynamically using the options parameter
  const limiter = rateLimit({
    windowMs: options.windowMs || 60 * 1000, // 1 minute by default
    max: options.max || 100, // 100 requests per windowMs by default
    message: options.message || "Too many requests, please try again later."
  });

  return limiter;
}

module.exports = createRateLimitMiddleware;

Enter fullscreen mode Exit fullscreen mode

Next, in your Express application, you can use this dynamically created rate-limiting middleware in different levels:

At the App Level:

const express = require("express");
const app = express();
const createRateLimitMiddleware = require("./rateLimitMiddleware");

// Apply rate limiting for the entire app
const appLevelRateLimiter = createRateLimitMiddleware({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 1000, // 1000 requests per hour
});

app.use(appLevelRateLimiter);
// Other app configurations and routes

Enter fullscreen mode Exit fullscreen mode

At the Router/Route Level:

const express = require("express");
const router = express.Router();
const createRateLimitMiddleware = require("./rateLimitMiddleware");

// Apply rate limiting for a specific router
const routerLevelRateLimiter = createRateLimitMiddleware({
  windowMs: 60 * 1000, // 1 minute
  max: 30, // 30 requests per minute
});

router.use(routerLevelRateLimiter);
// Define router paths and their respective handlers

Enter fullscreen mode Exit fullscreen mode

At the Controller Level (per route):

const express = require("express");
const router = express.Router();
const createRateLimitMiddleware = require("./rateLimitMiddleware");

// Apply rate limiting for specific routes/controllers
const specificRouteRateLimiter = createRateLimitMiddleware({
  windowMs: 60 * 1000, // 1 minute
  max: 10, // 10 requests per minute
});

router.get("/specific-route", specificRouteRateLimiter, (req, res) => {
  // Controller logic for the specific route
});
Enter fullscreen mode Exit fullscreen mode

This setup allows you to dynamically configure rate-limiting based on your specific needs at different levels within your Express application. Adjust the parameters in the options object passed to createRateLimitMiddleware to fit your requirements.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay