Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 33 ยท Testing, Security and Production

Security and Performance

Harden and speed up a Medusa 2 backend: secrets, CORS, publishable keys, rate limiting, field selection, indexes, Redis cache, pooling and N+1 avoidance.

A store is a public target. Anyone can call your Store API, bots hammer login and cart endpoints, and a slow query on a product page costs real sales. Medusa gives you sensible defaults, but several settings are yours to get right before launch, and a few performance habits decide whether the backend stays fast under load.

This lesson covers security first (secrets, CORS, publishable keys, rate limiting) and then performance (asking only for the fields you need, indexes, caching and avoiding the N+1 pattern). Real configuration is read-only; the runnable stand-ins implement a token-bucket rate limiter and a cache wrapper so you can see the mechanics.

Secrets: JWT_SECRET and COOKIE_SECRET

Medusa signs tokens and session cookies with two secrets set in medusa-config.ts (read-only):

TypeScript
import { loadEnv, defineConfig } from "@medusajs/framework/utils"

loadEnv(process.env.NODE_ENV || "development", process.cwd())

module.exports = defineConfig({
  projectConfig: {
    databaseUrl: process.env.DATABASE_URL,
    redisUrl: process.env.REDIS_URL,
    http: {
      storeCors: process.env.STORE_CORS!,
      adminCors: process.env.ADMIN_CORS!,
      authCors: process.env.AUTH_CORS!,
      jwtSecret: process.env.JWT_SECRET || "supersecret",
      cookieSecret: process.env.COOKIE_SECRET || "supersecret",
    },
  },
})

Treat that || "supersecret" fallback as a development convenience only. In production:

  • Generate long random values (at least 32 random bytes each) and store them in your host's secret manager, never in git.
  • Use different values per environment, so a leaked staging secret cannot forge production tokens.
  • Fail at startup when they are missing, instead of silently using a default. The validator stand-in in Deploying Medusa does exactly that.
  • Rotating JWT_SECRET invalidates every issued token, which is the right emergency response to a leak.

The same rule covers DATABASE_URL, payment keys and webhook secrets: they come from the environment, and they never reach the Admin or storefront bundle. More on payment secrets in Payment Providers.

CORS

Browsers enforce CORS, so each client origin must be allowed. Medusa has three lists: storeCors for the storefront, adminCors for the dashboard and authCors for authentication routes. Each is a comma-separated list of origins (regular expressions are accepted too). Rules of thumb:

  1. Put exact origins, such as https://shop.example.com, never *.
  2. Keep the lists separate: the admin origin should not be able to call the Store API from a browser by accident, and the reverse.
  3. Remember CORS protects browsers only. A script or curl ignores it, so it is not authorization. Real protection is authentication and validation.

Publishable keys are not secrets

The Store API requires a publishable API key in the x-publishable-api-key header (The Store API). It scopes requests to one or more sales channels, and it is meant to be embedded in the storefront, so anyone can read it in the browser. That is fine: it grants no more than the public catalog already shows. Never confuse it with:

Credential Where it lives If leaked
Publishable key Storefront code and requests Harmless, scopes public catalog access
Admin API token or JWT Server side only Full control of the store
JWT_SECRET / COOKIE_SECRET Backend environment Attacker can forge tokens
Payment provider secret key Backend environment Fraudulent charges and refunds

Authentication and validation on custom routes

Anything you add under src/api is your responsibility. Routes under /admin should use the admin authentication middleware, routes for customer data need the customer actor type, and every body, query and path parameter should pass a Zod schema before any logic runs (Custom API Routes and Middleware). Never trust a customer id from the request body; take it from the authenticated actor. For general shop hardening, see Shop security.

Rate limiting

Medusa does not throttle requests by itself. Limit abuse at the edge first (a CDN or WAF rule on login, cart creation and discount-code endpoints), then add application limits for what the edge cannot know. A common algorithm is the token bucket: a bucket holds up to capacity tokens, refills at a steady rate and each request spends one. Bursts are allowed up to the capacity; sustained traffic is capped at the refill rate. In a multi-instance deployment the counters must live in a shared store such as Redis, otherwise each instance enforces its own limit.

Stand-in 1: a token-bucket limiter

The clock is injected, so the output is deterministic. Each key (for example an IP address) gets its own bucket.

JS A token bucket with a fake clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ask only for the fields you need

Over-fetching is the easiest performance mistake. Store routes accept a fields query parameter and Query takes a fields array (Query: Fields, Filters and Pagination). Compare (read-only):

TypeScript
// Heavy: pulls everything, including relations nobody renders
const { data } = await query.graph({ entity: "product", fields: ["*"] })

// Light: exactly what the product card shows
const { data: cards } = await query.graph({
  entity: "product",
  fields: ["id", "title", "handle", "thumbnail", "variants.id"],
  pagination: { take: 24, skip: 0 },
})

Always paginate list endpoints with a bounded take; an unbounded list over a large catalog is a denial-of-service on yourself.

Indexes

Medusa's own tables ship with the indexes the core needs. For your custom models, index the columns you filter or join on. In a data model you can declare indexes on properties (read-only):

TypeScript
import { model } from "@medusajs/framework/utils"

export const Review = model
  .define("review", {
    id: model.id().primaryKey(),
    product_id: model.text().index(),
    status: model.enum(["pending", "approved", "rejected"]).default("pending"),
    rating: model.number(),
  })

A column such as product_id is queried on every product page, so it earns an index. Do not index everything: each index slows writes and uses space. Use EXPLAIN on slow queries in Postgres before guessing.

Caching with the Redis cache module

Data that is expensive to compute and tolerates slight staleness (a category tree, a shipping-rate table, an external lookup) belongs in a cache. Medusa has a cache module with an in-memory default for development and a Redis implementation for production. In code you resolve it from the container and use get, set and invalidate (read-only):

TypeScript
const cache = container.resolve(Modules.CACHE)

const key = `reviews-summary:${productId}`
let summary = await cache.get<{ average: number; count: number }>(key)
if (!summary) {
  summary = await computeSummary(productId)
  await cache.set(key, summary, 300) // 5 minutes
}

Two rules: give every entry a TTL, and invalidate on writes that change the data. Never cache per-customer data under a shared key. Cache behavior details and option names vary between releases, so confirm them for the version you run.

Stand-in 2: a cache wrapper

A reusable "get or compute" wrapper with TTL and explicit invalidation, using an injected clock.

JS A cache wrapper with TTL and invalidation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Connection pooling

Every Medusa process opens connections to Postgres, and Postgres handles only a limited number. With several server and worker instances the total can exceed it quickly, and then requests fail with "too many connections". Remedies: size pools per instance so instances x pool size stays below the database limit (the project config exposes driver options for this; check the docs for your version), and put a pooler such as PgBouncer in front when you scale out. Managed Postgres plans usually document their connection limit.

N+1 means one query to fetch a list, then one more per row. With modules it is easy to write by accident:

TypeScript
// N+1: one call per product
for (const product of products) {
  product.reviews = await reviewService.listReviews({ product_id: product.id })
}

Instead, ask for linked data in a single Query call, or filter once with an array of ids:

TypeScript
const reviews = await reviewService.listReviews({
  product_id: products.map((p) => p.id),
})

If a link exists (Module Links), fields: ["id", "title", "reviews.*"] lets Medusa batch the retrieval for you. The stand-in in Query: Fields, Filters and Pagination shows how such a join works across modules.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the publishable API key safe to ship in a storefront?

    Publishable keys identify which sales channels a Store API request may see. They are designed to be public, unlike admin tokens and secrets.
  2. 2. What does CORS protect against?

    CORS is enforced by browsers. A script or curl ignores it, so you still need authentication, validation and rate limiting.
  3. 3. A token bucket with capacity 3 and refill 1 per second receives 4 requests at once from one IP. What happens?

    The bucket starts full with three tokens; each request spends one. The fourth finds it empty and must wait about a second.
  4. 4. Which change removes an N+1 pattern?

    N+1 is one query per row. Fetching all related rows in one call, by id list or through a link, replaces the loop with a constant number of queries.
  5. 5. What is a sound habit for cached data?

    A TTL bounds staleness and explicit invalidation fixes it right after writes. Shared keys for personal data would leak one customer's data to another.

Summary

  • Set strong, per-environment JWT_SECRET and COOKIE_SECRET values; never keep the development fallback in production.
  • List exact CORS origins for store, admin and auth; remember CORS is not authorization.
  • Publishable keys are public by design; admin tokens, secrets and payment keys are not.
  • Add rate limiting at the edge and in the app, with shared counters when you run several instances.
  • Select only needed fields, paginate with a bounded take, and index columns you filter on.
  • Cache with TTLs and invalidation, size connection pools carefully and avoid N+1 queries.

Next: Deploying Medusa