How to setup rate limit for /api/

hi there, how to setup properly rate limit for /api/ i.e /api/posts/
I want to limit that POST method limited by IP 1 every 10 Second
Prevent Double Post/Spam

I think you can use strapi policies.
Each model has policies.
Policies are middleware - for example, you can check if a user is authorized.

P.S. If you deploy to VPS and use nginx as a reverse proxy - you can find this functionality in nginx

P.P.S you can see this beatufil strapi course :

hi there thank you for recommended this, I have bought and learning strapi more, because I am launch strapi for my startup and this is my first project using strapi to my mobile apps (android/ios)
seems strapi good for production if I know more about strapi, thank you for recommended this course

To do so, take a look at the rateLimit policy that is provided by users-permissions plugin.

You can add it to your routes like this (config/routes.json):

{
  "routes": [
    {
      "method": "GET",
      "path": "/test-route",
      "handler": "test.index",
      "config": {
        "policies": ["plugins::users-permissions.ratelimit"]
      }
    }
  ]
}

By default, it allows you to limit an IP to max 5 requests per minute. To change these limits you should create your custom policy, copy the content from the rateLimit.js file and modify the values from interval and max variables, then attach that policy to your route.

Note: It uses koa2-ratelimit under the hood, so you can take a look at their documentation for extra configs(like whitelisting your IP). Also, it stores the ips in memory, so if you restart your node app then the limits will be refreshed, to solve this you could store IPs in a persistent memory like Redis/Mongo.

1 Like

Custom policy might be better if you plan on scaling too as you can have the policy dump the rate-limit information into Koa.

Our rate-limit policy is very very basic and stores that info in the node memory so if the server restarts that rate-limit log is lost.

hi there, how to integrate strapi with redis?
I am using mongodb as main database now

yes I am using custom policy now since default rate limit in strapi is 5 request perminutes