perseidesperseides
rate-limit

Customization

Learn how to customize the @perseidesjs/medusa-plugin-rate-limit plugin in your Medusa app

Available Methods

The RateLimit class provides three main methods:

limit(identifier: string)

Checks and increments the rate limit for a given identifier.

const { success, remaining, limit } = await rateLimit.limit('user-123')

Returns:

  • success: Whether the request is within the rate limit
  • remaining: Number of requests remaining in the current window
  • limit: The configured limit for the window

getRemaining(identifier: string)

Gets the remaining requests for a specific identifier without incrementing the counter.

const remaining = await rateLimit.getRemaining('user-123')

reset(identifier: string)

Resets the request count for a specific identifier.

await rateLimit.reset('user-123')

Configuration Options

RateLimit class options

OptionTypeDefaultDescription
limitnumber100Maximum number of requests in the time window
windownumber900Time window in seconds (default: 15 minutes)
prefixstring"rl"Prefix for cache keys

ipRateLimit middleware options

Accepts all options from RateLimit plus:

OptionTypeDefaultDescription
trustProxyboolean | numberfalseWhether to trust X-Forwarded-For header. See Extracting the client IP.

Multiple rate limiters

You can create multiple rate limiters with different options:

const rateLimiters = {
  loggedInUser: new RateLimit({
    cacheService,
    options: { limit: 100, window: 3600 }
  }),
  anonymousUser: new RateLimit({
    cacheService,
    options: { limit: 10, window: 60 }
  })
}

async (req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction) => {
  const userId = req.auth_context.actor_id
  const ip = req.headers['x-forwarded-for'] as string
  const { success, remaining } = userId
  ? await rateLimiters.loggedInUserRateLimit.limit(`user:${userId}`)
  : await rateLimiters.anonymousUserRateLimit.limit(ip)

  if (!success) {
    res.status(429).send('Too many requests, please try again later.')
    return
  }

  // ...
}

On this page