1

I am trying to add a middleware in strapi custom route which can control how many requests can come from a specific IP> For this I am using express-rate-limit but its not working

I tried this:

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

module.exports = () => {
  return async (ctx, next) => {
    await next();
    rateLimit({
      windowMs: 60 * 1000, // 1 minutes
      max: 3, // Limit each IP to 3 requests per windowMs
      message: "too many requests",
    });
  };
};

Custom route:

    {
      method: "GET",
      path: "/v1/customer/social/accounts",
      handler: "customer.getSocialAccounts",
      config: {
        auth: false,
        middlewares: ["global::jwtVerify", "global::rate-limit"],
      },
    },

But its not giving me the desired output like if I hit more then 3 requests then it should give too many requests error(429).

1 Answers1

0

I see a few potential issues:

  1. express-rate-limit is designed to work with express, whereas strapi appears to use koa. They do similar things, but they're different enough that middleware written for one is unlikely to just work with the other.

  2. Your sample code calls next() right away, which means that the limiter won't have a chance to actually limit the request.

  3. Your sample code appears to be creating a new rateLimit middleware instance on each request, which with the default store, means that the hit count is reset to 0 on each request.

  4. Your sample code isn't doing anything with the rateLimit middleware instance it creates, so the hit count is never increased beyond 0, and it will never invoke the limit.

Here's a potential solution using koa-connect, which converts express-style middleware to work with Koa. I haven't tested it, but hopefully it will work or at least point you in the right direction.

const rateLimit = require("express-rate-limit");
const c2k = require('koa-connect');

module.exports = () => {
  return c2k(rateLimit({
      windowMs: 60 * 1000, // 1 minutes
      max: 3, // Limit each IP to 3 requests per windowMs
      message: "too many requests",
    }));
};
Nathan Friedly
  • 7,837
  • 3
  • 42
  • 59