Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 33 ยท Customizing the Backend

Custom API Routes and Middleware

Add your own Medusa endpoints with file-based routes, params, Zod validation, defineMiddlewares, authenticate, MedusaError and CORS, plus runnable router stand-ins.

Sooner or later a storefront needs something the built-in routes do not offer: "wishlist for the logged-in customer", "stock by city", "product reviews". In Medusa you add an HTTP endpoint by creating a file. There is no router to register and no controller class: the file's path is the URL, and the functions it exports are the handlers.

This lesson shows how routes are discovered, how to read params and bodies safely, how to validate with Zod, how middlewares attach to routes, how to reject unauthenticated callers, how errors become HTTP responses, and what CORS does. The real code needs a Medusa project, so it is read-only. Two stand-ins you can run reproduce the mechanics (path-to-route mapping, and validation plus error handling) in plain Node. They are teaching models of the ideas, not Medusa's implementation.

Routes are files

Everything under src/api becomes a route. The folder path is the URL; the file must be named route.ts:

File URL
src/api/store/hello/route.ts /store/hello
src/api/admin/reports/route.ts /admin/reports
src/api/store/reviews/[id]/route.ts /store/reviews/:id
src/api/webhooks/shipping/route.ts /webhooks/shipping

A folder name in square brackets is a path parameter. The prefix decides the default protection: /admin/* routes require an authenticated admin user, /store/* routes require a publishable API key (see The Store API), and anything else, such as /webhooks, is open until you protect it. Do not put your own endpoints under /auth; that prefix is reserved for the Auth Module.

A route file exports one function per HTTP method, named in upper case:

TypeScript
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { MedusaError } from "@medusajs/framework/utils"
import { REVIEW_MODULE } from "../../../../modules/review"

export async function GET(req: MedusaRequest, res: MedusaResponse) {
  const reviewService = req.scope.resolve(REVIEW_MODULE)

  const review = await reviewService.retrieveReview(req.params.id).catch(() => null)
  if (!review) {
    throw new MedusaError(MedusaError.Types.NOT_FOUND, `Review ${req.params.id} was not found`)
  }

  res.json({ review })
}

Three things to notice:

  • req.params.id comes from the [id] folder.
  • req.scope is the request-scoped container. You resolve services from it exactly as described in Architecture: Modules, Workflows and the Container. The scope also carries per-request data such as the authenticated actor, so always use req.scope, never a global.
  • Throwing a MedusaError is the normal way to fail. You do not build the error response yourself.

Supported method names are GET, POST, PUT, PATCH, DELETE, OPTIONS and HEAD. Keep handlers thin: parse input, call a service or a workflow, return JSON. Business rules belong in services and workflows so a subscriber, a job or another route can reuse them.

Validating the body with Zod

Never trust req.body. Medusa uses Zod schemas together with a validation middleware, which parses the body and stores the typed result on req.validatedBody:

TypeScript
// src/api/store/reviews/route.ts
import { z } from "zod"

export const PostReviewSchema = z.object({
  product_id: z.string(),
  rating: z.number().int().min(1).max(5),
  comment: z.string().max(2000).optional(),
})

export type PostReviewBody = z.infer<typeof PostReviewSchema>
TypeScript
// src/api/store/reviews/route.ts (continued)
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"

export async function POST(
  req: MedusaRequest<PostReviewBody>,
  res: MedusaResponse
) {
  const { product_id, rating, comment } = req.validatedBody
  // ... call a workflow here ...
  res.status(201).json({ ok: true })
}

Query strings have their own helper, validateAndTransformQuery, which also understands the standard fields, limit and offset parameters. Whichever you use, remember what validation guarantees: the shape is right. Whether the product exists, whether the customer may review it, and whether they already did are business rules you still check in the handler or workflow.

Middlewares and defineMiddlewares

Validation is attached in one central file, src/api/middlewares.ts, with defineMiddlewares:

TypeScript
import { defineMiddlewares, validateAndTransformBody, authenticate } from "@medusajs/framework/http"
import { PostReviewSchema } from "./store/reviews/route"

export default defineMiddlewares({
  routes: [
    {
      matcher: "/store/reviews",
      method: "POST",
      middlewares: [
        authenticate("customer", ["session", "bearer"]),
        validateAndTransformBody(PostReviewSchema),
      ],
    },
    {
      matcher: "/store/reviews/:id",
      method: ["PUT", "DELETE"],
      middlewares: [authenticate("customer", ["session", "bearer"])],
    },
  ],
})

Each entry says: for requests matching this path and method, run these functions first, in order. A middleware is a function (req, res, next). Calling next() continues, throwing or responding stops the chain. The order here matters: the request is authenticated before the body is parsed, so strangers cannot probe your validation messages.

authenticate(actorType, methods) is the guard. It reads the bearer token or session cookie described in The Admin API and Authentication, checks that the actor is of the given type ("customer", "user" or a custom one), and puts the actor on the request. It also accepts an allowUnauthenticated option for routes that behave differently when logged in. Inside the handler, the customer's id is available from the auth context on the request (for example req.auth_context.actor_id), and you should use that, never an id sent in the body, to decide whose data to change. Trusting a customer_id in the body is the classic way to let one shopper edit another's records.

Middlewares can also be global (a matcher for a whole prefix) and can do generic jobs: logging, rate limiting (see Security and Performance) or parsing a raw body for webhook signatures. For signature checks you need the exact bytes the sender signed, so configure the route to keep the raw body, as explained in Webhooks and Signatures.

flowchart LR
    R["HTTP request"] --> M1["authenticate"]
    M1 --> M2["validateAndTransformBody"]
    M2 --> H["route.ts handler"]
    H --> S["Service or workflow"]
    M1 -.->|"401"| E["Error handler"]
    M2 -.->|"400"| E
    H -.->|"MedusaError"| E
    E --> X["JSON error response"]

Middlewares run in the order you list them; any of them can stop the request and hand an error to the error handler.

Errors become HTTP responses

Throw MedusaError with a type and a message. The framework's error handler turns the type into a status code and a JSON body with type and message. Common types include INVALID_DATA (400), NOT_FOUND (404), NOT_ALLOWED, UNAUTHORIZED (401), CONFLICT (409) and UNEXPECTED_STATE; exact status mappings are defined by the framework, so use the type that describes the problem and let it choose. Two habits help:

  • Write messages for developers and API clients, without leaking internals such as SQL, file paths or other customers' data.
  • Do not catch an error just to return res.status(500). Let it propagate so the framework logs it consistently.

CORS

Browsers refuse to let a page on https://shop.example.com read responses from https://api.example.com unless the API opts in with CORS headers. Medusa configures this in medusa-config.ts under the HTTP settings, separately for the three audiences:

TypeScript
module.exports = defineConfig({
  projectConfig: {
    http: {
      storeCors: process.env.STORE_CORS!,   // your storefront origin(s)
      adminCors: process.env.ADMIN_CORS!,   // the admin dashboard origin
      authCors: process.env.AUTH_CORS!,     // origins allowed to call /auth
      jwtSecret: process.env.JWT_SECRET!,
      cookieSecret: process.env.COOKIE_SECRET!,
    },
  },
})

Each value is a comma-separated list of allowed origins. CORS protects browsers; a script on a server ignores it. Never rely on CORS as authentication, and do not use * with cookies. Custom routes under /store and /admin pick up the matching setting automatically. Routes elsewhere (for example /webhooks) need a cors middleware of your own if a browser will call them.

Stand-in 1: files become routes

The mapping from file paths to URL patterns is simple, and writing it once removes the magic. This stand-in takes a list of file paths (as src/api would contain), builds route patterns, and matches incoming requests, including [id] params and method dispatch.

Node.js From route.ts files to URL patterns

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The unknown method gives 405 and the unknown path gives 404. In real Medusa the framework does the equivalent for you, and the same folder-name convention is what you saw in the table above.

Stand-in 2: validation, authentication and error handling

The second stand-in builds a middleware chain. A small hand-written schema checker stands in for Zod (no npm packages are available here), authenticate checks an actor type, and a MedusaError-like class carries a type that the error handler maps to a status. The statuses in this table are the stand-in's own.

Node.js Middleware chain with validation and errors

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the ok case the body even contains a forged customer_id: "cus_1". It is ignored, because the handler reads the actor from the authentication context, so the review is recorded for cus_2. That is exactly the habit to copy in real routes. The again case shows a business rule (a conflict) that no schema could catch.

Common mistakes

  • Wrong file name. Only route.ts is a route. index.ts or routes.ts is silently ignored.
  • Forgetting the middleware entry. A Zod schema alone does nothing until defineMiddlewares attaches it to the matcher and method.
  • Reading ids from the body. Use the authenticated actor for ownership checks.
  • Business logic in the route. Put it in a service or workflow so subscribers and jobs can reuse it.
  • Treating CORS as security. It only controls what browsers may read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which file creates a handler for GET /store/reviews/:id?

    Routes live in src/api, the folder path is the URL, a folder in square brackets is a path parameter, and the file must be called route.ts.
  2. 2. What does validateAndTransformBody(Schema) do?

    It checks the shape of the request body and gives the handler typed data. Business checks such as whether the product exists remain your job.
  3. 3. In a POST that creates a review, where should the customer id come from?

    Ids sent by the client can be forged. The actor attached by the authenticate middleware is established by the server.
  4. 4. What is the right way to signal that a requested record does not exist?

    Throwing a typed MedusaError lets the framework produce a consistent JSON error with the right status code.
  5. 5. What does CORS configuration protect against?

    CORS is a browser rule. Any non-browser client ignores it, so authentication still has to protect your data.

Summary

  • A route.ts file under src/api defines an endpoint; folders in square brackets are params, and exported GET, POST and other functions are the handlers.
  • defineMiddlewares in src/api/middlewares.ts attaches authenticate, validateAndTransformBody and your own middleware to matchers and methods, in the order you list them.
  • Validate shape with Zod, check business rules in handlers or workflows, and take identity from the authenticated actor.
  • Throw MedusaError with a meaningful type; the framework turns it into an HTTP response.
  • Configure storeCors, adminCors and authCors for browsers, and never treat CORS as authentication.

Next, give your routes their own data with Custom Modules and Data Models.