All jobs

Add Rate Limiting to a Medusa Store API

Yes. An agent adds express-rate-limit to a Medusa v2 backend through defineMiddlewares, limits the auth and cart routes per client, tests the 429 and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the backend's middleware layer first. In a project laid out like medusajs/dtc-starter, the repository is a pnpm 10 and Turborepo workspace with apps/backend (@dtc/backend) and apps/storefront, Node 22.23 or later in engines. The backend runs @medusajs/medusa and @medusajs/framework 2.22.2, whose own dependencies are Express 4.21 and path-to-regexp 8; its scripts are medusa develop, medusa build, medusa start and three Jest runs, of which test:integration:http matches integration-tests/http/*.spec.ts (a directory holding only setup.js today) using @medusajs/test-utils. medusa-config.ts sets databaseUrl, the three CORS origins, jwtSecret and cookieSecret, and nothing about proxies or limits, because the config's http block has no such option. src/api/middlewares.ts already exports defineMiddlewares with one route: configureStoreSearch on POST /store/search, beside the custom store/custom and admin/custom routes; .env.template lists REDIS_URL. The storefront's src/lib/data/cart.ts calls /store/carts through the JS SDK with the publishable key, which shows which store routes real traffic hits.

It installs express-rate-limit 8 in apps/backend, which works with the Express 4 the framework ships, and builds limiters in src/api/middlewares.ts as plain Express middleware, since Medusa's middleware functions take MedusaRequest, MedusaResponse and MedusaNextFunction and anything Express accepts fits. Each limiter sets windowMs, limit, standardHeaders: 'draft-8' for the combined RateLimit header and legacyHeaders: false; the default key is the client IP through the library's ipKeyGenerator, which masks IPv6 to a /56 so one visitor cannot rotate through a subnet. The routes get different budgets: a tight one on /auth/* with method: ['POST'] for login and registration attempts, a moderate one on POST /store/carts and POST /store/customers, and one on the existing /store/search matcher, where it sits before configureStoreSearch in the middlewares array. Admin routes are left alone, and the matchers are strings compiled by path-to-regexp, so /auth/* is written as a wildcard.

Two deployment details decide whether the limiter counts the right client. Behind a proxy, Express reads X-Forwarded-For only when trust proxy is set, and express-rate-limit logs ERR_ERL_UNEXPECTED_X_FORWARDED_FOR when the header arrives with the setting off, which would make the limit global instead of per visitor. Medusa exposes no config for it, but the Express app is reachable as req.app from any middleware, so the agent adds a tiny global middleware that sets trust proxy from a TRUST_PROXY_HOPS variable once, documents it in .env.template, and sets it to 0 by default so a direct deployment stays strict. The second is the store: the default memory store is per process, and a backend in workerMode: 'server' behind a load balancer would count each instance separately, so the agent wires rate-limit-redis on REDIS_URL when that variable is present and keeps memory otherwise.

The test is integration-tests/http/rate-limit.spec.ts with medusaIntegrationTestRunner: it posts to /auth/customer/emailpass past the limit, expects a 429 with a RateLimit header and the JSON message, and checks that GET /store/regions is untouched. The sandbox has no Docker, so the agent installs PostgreSQL with apt-get for the test runner's database, runs pnpm test:integration:http and pnpm build in apps/backend, and opens the pull request.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add rate limiting to the store and auth routes of this Medusa v2 backend. Read package.json, pnpm-workspace.yaml, apps/backend/package.json, apps/backend/medusa-config.ts, apps/backend/src/api/middlewares.ts, the route files under apps/backend/src/api, apps/backend/jest.config.js, apps/backend/integration-tests, apps/backend/.env.template and apps/storefront/src/lib/data/cart.ts first. Install express-rate-limit in the backend and add limiters in src/api/middlewares.ts through defineMiddlewares: a strict limit on POST /auth/* for login and registration, a moderate limit on POST /store/carts and POST /store/customers, and one on /store/search placed before the existing search middleware. Use draft-8 standard headers, no legacy headers, the library's IP key generator, and leave admin routes alone. Set Express's trust proxy from a TRUST_PROXY_HOPS variable defaulting to 0, use a Redis store when REDIS_URL is set and memory otherwise, and document both in .env.template. Write an integration test with medusaIntegrationTestRunner that proves the 429 and the RateLimit header on an auth route and that an unlimited store route still answers, install PostgreSQL in the sandbox, run the http integration tests and medusa build, and open a pull request that lists each route with its window and limit and quotes the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request changes apps/backend/package.json and pnpm-lock.yaml, rewrites apps/backend/src/api/middlewares.ts to add the limiters beside the existing search route, adds two lines to .env.template, and adds integration-tests/http/rate-limit.spec.ts. Its description lists each matcher with its window and limit, explains the trust proxy variable and the Redis store, and quotes the Jest output from the sandbox.

A reviewer checks the budgets against real traffic (a storefront that creates a cart on every first visit needs a looser cart limit than the login route), sets TRUST_PROXY_HOPS for their platform, and confirms REDIS_URL is set wherever more than one backend instance runs. They also check that the limiter sits before configureStoreSearch so a blocked search request never reaches the index.

From then on a credential-stuffing burst against /auth/customer/emailpass gets 429s with a Retry-After, while the admin dashboard and normal shoppers see no change.

Run it on every Linear issue labelled rate-limit

Sign in to Linear once with POST /me/connections {"type": "app", "name": "linear"} and finish the authorize URL in the console. Then add an automation to the Project with this prompt and a linear trigger on linear.issue.labeled, naming the label in config.labels. The trigger adds the issue after the prompt and fills in no placeholder, so the agent reads the route, window and limit from the issue while the prompt stays fixed. Only a label set by someone in your Rush org fires it, and the automation's max_runs_per_hour caps how many issues it takes on in an hour.

From your own server instead, a handler that receives Linear's webhook for the label sends POST /o/{org}/sessions with the repository and https://linear.app/<workspace>/issue/ENG-42 in resources, which puts the issue text in the prompt through your Linear connection, and a request_id that is a UUID v5 of the issue id so a redelivery returns the run already started. Give that key a webhook_url and Rush POSTs run.completed or run.failed when the turn ends, with data.session_url to read for the pull request link.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The middleware is a dozen lines; the correctness is in the surroundings: whether the key is the visitor or the load balancer, whether the count is per process or shared, which routes the storefront really hits, and whether the limiter runs before or after the framework's own middleware. The agent reads the config, the route tree and the storefront's data layer, runs the backend's own integration test runner against a Postgres it installs itself, and the 429 it observed is quoted in the pull request.

A store with several backends, or a team that wants the same policy on each of its Medusa projects, starts this request against each repository at once and reviews pull requests that differ only in the routes each app exposes.

Frequently asked questions

Why not limit everything under /store?

Product listing and region lookups are what every shopper does on every page, and a global budget would throttle browsing before it slows an attacker. The limits go where abuse costs something: login and registration, cart and customer creation, and search. A follow-up message can add a route.

What does TRUST_PROXY_HOPS do?

It sets Express's trust proxy to the number of proxies between the visitor and the backend, so req.ip is the visitor's address and not the load balancer's. With it unset, every request behind a proxy shares one key and the limit becomes global, which express-rate-limit flags in its log. Medusa's config has no setting for this, so the agent sets it through req.app in a global middleware.

Does the limit hold across several backend instances?

Only with a shared store. The default memory store counts per process, so two server instances each allow the full budget. When REDIS_URL is set the agent uses rate-limit-redis, and the counts are shared; without it the pull request says the limit is per instance.

How is it tested?

With medusaIntegrationTestRunner from @medusajs/test-utils, the same harness the starter's test:integration:http script expects, against a PostgreSQL the agent installs in the sandbox. The spec posts past the auth limit, asserts the 429 and the RateLimit header, and asserts that GET /store/regions still answers 200.

More Medusa jobs

The same job on other stacks

Keep reading