Granular control over rate limiting

The choice of having options directly inside the middleware instead of globally inside the global options (as on version 1.x of the project) was made to provide greater flexibility. This approach allows users to be more or less restrictive on certain specific routes. By specifying options directly within the middleware, you can tailor the rate limiting mechanism to suit the needs of individual routes, rather than applying a one-size-fits-all configuration globally. This ensures that you can have fine-grained control over the rate limiting behavior, making it possible to adjust the limits based on the specific requirements of each route.

Additionally, you can use a exported function called configureDefaults to update the default global values, such as the limit, window and includeHeaders. This allows you to set your own default values that will be applied across many routes, while still having the flexibility to specify more granular settings for specific routes. By configuring the middleware options, you can establish a baseline rate limiting policy that suits the majority of your application, and then override these defaults as needed for particular routes.

Default configuration

OptionTypeDefaultDescription
limitNumber5The number of requests allowed in the given time window
windowNumber60The time window in seconds
includeHeadersBooleanfalseWhether to include the headers (X-RateLimit-Limit, X-RateLimit-Remaining) in the response

Overriding default options

import {
  defineMiddlewares
} from "@medusajs/framework/http"
import { defaultRateLimit, configureDefaults } from '@perseidesjs/medusa-plugin-rate-limit'

// This will override the global default options for all routes
// Here, we set the limit to 1 request per 30 seconds
configureDefaults({
  limit: 1,
  window: 30,
})

export default defineMiddlewares({
  routes: [
    {
      matcher: "/store/custom*",
      method: "POST",
      middlewares: [
        // Uses the global default options
        defaultRateLimit()
      ],
    },
        {
      matcher: "/store/custom*",
      method: "POST",
      middlewares: [
        // If the options are provided, they will ignore the global default options and use the provided ones
        defaultRateLimit({
          limit: 10,
          window: 60,
        })
      ],
    },
  ],
})