@perseidesjs/medusa-plugin-rate-limit
v1.0.8
Published
A simple rate-limit service for Medusa
Downloads
161
Maintainers
Readme
npm install @perseidesjs/medusa-plugin-rate-limit
const plugins = [
`medusa-fulfillment-manual`,
`medusa-payment-manual`,
`@perseidesjs/medusa-plugin-rate-limit`,
]
const plugins = [
`medusa-fulfillment-manual`,
`medusa-payment-manual`,
{
resolve: `@perseidesjs/medusa-plugin-rate-limit`,
/** @type {import('@perseidesjs/medusa-plugin-rate-limit').PluginOptions} */
options: {
limit: 5,
window: 60,
},
},
]
// src/middlewares/rate-limit.ts
import { type MedusaRequest, type MedusaResponse } from '@medusajs/medusa'
import type { NextFunction } from 'express'
import type { RateLimitService } from '@perseidesjs/medusa-plugin-rate-limit'
/**
* A simple rate limiter middleware based on the RateLimitService
* @param limit {number} - Number of requests allowed per window
* @param window {number} - Number of seconds to wait before allowing requests again
* @returns
*/
export default async function rateLimit(
req: MedusaRequest,
res: MedusaResponse,
next: NextFunction,
) {
try {
// 1️⃣ We resolve the RateLimitService from the container
const rateLimitService = req.scope.resolve<RateLimitService>('rateLimitService')
// 2️⃣ We create a key for the current request based on the IP address for example
const key = req.ip
const rateLimitKey = `rate_limit:${key}`
const allowed = await rateLimitService.limit(rateLimitKey)
// 3️⃣ If the request is not allowed, we return a 429 status code and a JSON response with an error message
if (!allowed) {
const retryAfter = await rateLimitService.ttl(rateLimitKey)
res.set('Retry-After', String(retryAfter))
res
.status(429)
.json({ error: 'Too many requests, please try again later.' })
return
}
// 4️⃣ Otherwise, we can continue, below I'm getting the remaining attempts for the current key for example
const remaining = await rateLimitService.getRemainingAttempts(rateLimitKey)
res.set('X-RateLimit-Limit', String(rateLimitService.getOptions().limit))
res.set('X-RateLimit-Remaining', String(remaining))
next()
} catch (error) {
next(error)
}
}
import { MiddlewaresConfig } from '@medusajs/medusa'
import rateLimit from './middlewares/rate-limit'
export const config: MiddlewaresConfig = {
routes: [
{
// This will limit the number of requests to 5 per 60 seconds on the auth route
matcher: '/store/auth',
middlewares: [rateLimit],
},
],
}
import { MiddlewaresConfig } from '@medusajs/medusa'
import { rateLimitRoutes } from '@perseidesjs/medusa-plugin-rate-limit'
export const config: MiddlewaresConfig = {
routes: [
{
// This will limit the number of requests to 5 per 60 seconds on the auth route using the default middleware
matcher: '/store/auth',
middlewares: [rateLimitRoutes],
},
],
}