Skip to main content

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

OptionTypeDefaultDescription
limitNumber100Maximum number of requests in the time window
windowNumber900Time window in seconds (default: 15 minutes)
prefixString"rl"Prefix for cache keys

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
  }

  // ...
}