Add rate limit for sending email

System Information

I was testing sending emails with strapi and i noticed there isn’t a rate limit for that. I want to add limit for email sending so that user can’t spam it.

Just figured out how.

Create a file called strapi-server.js inside src/extentions/user-permissions/ and paste the code below:



/**
 There is default rate limiting for forgot password but not for send email confirmation
 so we will add rate limit middleware for both routes.
 */

// define the routes that you want to add rate limit middleware
const routesToAddRateLimitMiddleware = [
  "/auth/forgot-password",
  "/auth/send-email-confirmation",
];



export default (plugin) => {
  plugin.routes["content-api"].routes.forEach((route) => {
    // check if the route is in the list of routes to add rate limit middleware
    if (routesToAddRateLimitMiddleware.includes(route.path)) {
      // this will replace the existing middlewares with the new one
      // if you want to keep the existing middlewares use push method instead of assignment
      route.config.middlewares = [
        {
          name: "plugin::users-permissions.rateLimit",
          config: {
            max: 5, // max number of requests
            interval: {
              min: 5, // interval in minutes (i am not sure about if this value minutes or not but you can try it and see the result)
            },
          },
        },
      ];
    }
  });
  // don't forget to return the plugin otherwise it will not work
  return plugin;
};