Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 33 ยท Practice and Review

Medusa Cheat Sheet

A quick Medusa 2 reference: CLI commands, folder conventions, medusa-config options, route, subscriber, job, workflow, module and link skeletons, API endpoints and env vars.

This page is a lookup sheet, not a lesson. Use it when you remember that something exists but not its exact spelling: the command that runs migrations, the folder a job belongs in, the shape of a subscriber. Each section links to the lesson that explains the idea. Names, flags and import paths change between Medusa releases, so treat the tables as a memory aid and confirm the exact values in the documentation for your installed version before you depend on them.

Medusa needs a Node server and Postgres, so it cannot run here. Everything real below is read-only. Two stand-ins in Node.js at the end model conventions that are easy to get wrong: how file paths become routes, and how a scaffold decides where files go. They are learning aids, not Medusa's own code.

flowchart LR
    N["Need something"] --> C["CLI table"]
    N --> F["Folder map"]
    N --> S["Skeletons"]
    N --> E["Endpoints and env vars"]

Jump to the table that matches what you are looking for.

CLI commands

Run these with npx medusa ... (or through your package scripts) from the project folder. See Create a Medusa Project.

Command What it does
npx create-medusa-app@latest Creates a new project, and can set up a storefront and database
npx medusa develop Starts the backend in development mode with reload
npx medusa build Builds the backend and the admin for production
npx medusa start Starts the built backend
npx medusa db:migrate Runs pending migrations, including module and link tables
npx medusa db:generate <module> Generates a migration for a custom module
npx medusa db:sync-links Syncs link tables with your link definitions
npx medusa user -e <email> -p <password> Creates an admin user
npx medusa exec ./src/scripts/my-script.ts Runs a one-off script with the container available

The build output is what you deploy; see Deploying Medusa.

Folder conventions

Path Holds
medusa-config.ts Project configuration: database, Redis, CORS, secrets, modules, plugins
src/api/ File-based API routes (route.ts) and middlewares.ts
src/modules/<name>/ A custom module: models/, service.ts, index.ts, migrations/
src/workflows/ Workflows, with steps often in a steps/ subfolder
src/subscribers/ Event subscribers
src/jobs/ Scheduled jobs
src/links/ Module link definitions
src/admin/ Admin extensions: widgets/, routes/
src/scripts/ Scripts for medusa exec, such as seed scripts

Background: Architecture: Modules, Workflows and the Container.

medusa-config.ts at a glance

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

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

export default defineConfig({
  projectConfig: {
    databaseUrl: process.env.DATABASE_URL,
    redisUrl: process.env.REDIS_URL,
    workerMode: process.env.MEDUSA_WORKER_MODE as "shared" | "worker" | "server",
    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",
    },
  },
  admin: {
    disable: process.env.DISABLE_MEDUSA_ADMIN === "true",
    backendUrl: process.env.MEDUSA_BACKEND_URL,
  },
  modules: [
    { resolve: "./src/modules/review" },
  ],
})
Option Purpose
projectConfig.databaseUrl Postgres connection string
projectConfig.redisUrl Redis for events, cache and workflow engine in production
projectConfig.workerMode shared, server or worker instance role
projectConfig.http.* CORS lists, JWT and cookie secrets
admin.disable Do not serve the admin from this instance
modules Custom modules and provider configuration for built-in ones
plugins Installed plugins

Never ship the placeholder secrets; see Security and Performance.

Skeletons

API route (src/api/store/reviews/route.ts)

TypeScript
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"

export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
  const query = req.scope.resolve("query")
  const { data } = await query.graph({ entity: "review", fields: ["id", "rating"] })
  res.json({ reviews: data })
}

Exported names are HTTP methods. Folders in brackets, such as [id], become path parameters available in req.params. See Custom API Routes and Middleware.

Middleware (src/api/middlewares.ts)

TypeScript
import { defineMiddlewares, validateAndTransformBody } from "@medusajs/framework/http"
import { z } from "zod"

const PostReview = z.object({ rating: z.number().min(1).max(5) })

export default defineMiddlewares({
  routes: [
    { matcher: "/store/reviews", method: "POST", middlewares: [validateAndTransformBody(PostReview)] },
  ],
})

Subscriber (src/subscribers/order-placed.ts)

TypeScript
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"

export default async function orderPlacedHandler({ event: { data }, container }: SubscriberArgs<{ id: string }>) {
  const logger = container.resolve("logger")
  logger.info(`Order placed: ${data.id}`)
}

export const config: SubscriberConfig = { event: "order.placed" }

See Events and Subscribers.

Scheduled job (src/jobs/nightly-sync.ts)

TypeScript
import type { MedusaContainer } from "@medusajs/framework/types"

export default async function nightlySync(container: MedusaContainer) {
  container.resolve("logger").info("Sync started")
}

export const config = { name: "nightly-sync", schedule: "0 2 * * *" }

See Scheduled Jobs.

Workflow with a step (src/workflows/create-review.ts)

TypeScript
import { createStep, createWorkflow, StepResponse, WorkflowResponse } from "@medusajs/framework/workflows-sdk"

const saveStep = createStep(
  "save-review",
  async (input: { rating: number }, { container }) => {
    const review = await container.resolve("review").createReviews(input)
    return new StepResponse(review, review.id)
  },
  async (id, { container }) => {
    if (id) await container.resolve("review").deleteReviews(id)
  },
)

export const createReviewWorkflow = createWorkflow("create-review", (input: { rating: number }) => {
  const review = saveStep(input)
  return new WorkflowResponse(review)
})

Run it from a route with await createReviewWorkflow(req.scope).run({ input }). See Workflows and Steps and Compensation, Rollback and Long-Running Workflows.

TypeScript
// src/modules/review/models/review.ts
import { model } from "@medusajs/framework/utils"
export const Review = model.define("review", {
  id: model.id().primaryKey(),
  rating: model.number(),
})

// src/modules/review/service.ts
import { MedusaService } from "@medusajs/framework/utils"
import { Review } from "./models/review"
export default class ReviewModuleService extends MedusaService({ Review }) {}

// src/modules/review/index.ts
import { Module } from "@medusajs/framework/utils"
import ReviewModuleService from "./service"
export const REVIEW_MODULE = "review"
export default Module(REVIEW_MODULE, { service: ReviewModuleService })

// src/links/product-review.ts
import { defineLink } from "@medusajs/framework/utils"
import ProductModule from "@medusajs/medusa/product"
import ReviewModule from "../modules/review"
export default defineLink(ProductModule.linkable.product, ReviewModule.linkable.review)

After adding a module: register it in medusa-config.ts, then run npx medusa db:generate review and npx medusa db:migrate. See Custom Modules and Data Models and Module Links.

API endpoints

Store routes need the x-publishable-api-key header. Admin routes need an authenticated admin (bearer token or session). See The Store API and The Admin API and Authentication.

Task Request
List products GET /store/products
List regions GET /store/regions
Create a cart POST /store/carts
Add a line item POST /store/carts/{id}/line-items
Choose a shipping method POST /store/carts/{id}/shipping-methods
Create a payment collection POST /store/payment-collections
Add a payment session POST /store/payment-collections/{id}/payment-sessions
Complete the cart POST /store/carts/{id}/complete
Register or log in a customer POST /auth/customer/emailpass (and /register)
Current customer GET /store/customers/me
Log in an admin POST /auth/user/emailpass
List or create products (admin) GET / POST /admin/products
List orders (admin) GET /admin/orders
Inventory items (admin) /admin/inventory-items
Stock locations, sales channels /admin/stock-locations, /admin/sales-channels
Publishable and secret keys /admin/api-keys

Common query parameters: fields (choose returned fields), limit and offset (pagination), region_id (calculate prices), q (search).

Environment variables

Variable Used for
DATABASE_URL Postgres connection
REDIS_URL Redis connection
JWT_SECRET, COOKIE_SECRET Signing tokens and cookies; keep secret and unique per environment
STORE_CORS, ADMIN_CORS, AUTH_CORS Allowed browser origins
MEDUSA_WORKER_MODE shared, server or worker
DISABLE_MEDUSA_ADMIN Turn the admin off on an instance
MEDUSA_BACKEND_URL Public URL of the backend, used by the admin

Stand-in 1: from file paths to routes

Medusa derives routes from file locations under src/api. This stand-in applies the same conventions to a list of files and the methods they export, which is a quick way to double-check where a route will appear.

Node.js File paths to routes

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.

Only files named route.ts define routes. Helpers and middlewares.ts are skipped, and bracketed folders become parameters.

Stand-in 2: where does this file go?

New developers often put a job in the subscribers folder or forget the config export. This stand-in is a tiny scaffold that knows the folder for each kind of file and which export it needs.

Node.js A scaffold that knows the conventions

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command applies pending migrations, including link tables?

    db:migrate runs migrations for modules and links. start only launches a built server, build compiles it and exec runs a script.
  2. 2. Where does a file with export const GET belong for the URL /store/reviews/:id?

    Routes live under src/api, the folder path becomes the URL, bracketed folders become parameters and the file must be named route.ts.
  3. 3. Which export must a scheduled job file have besides its default function?

    The config export tells Medusa the job's name and its cron schedule.
  4. 4. Which header must storefront requests to the Store API carry?

    The publishable key scopes storefront requests to sales channels. It is safe to ship in browser code, unlike JWT_SECRET.
  5. 5. What does MEDUSA_WORKER_MODE control?

    Splitting server and worker roles lets HTTP traffic and background work scale separately.

Summary

  • The CLI covers creating a project, running it, building it, migrating and creating admin users.
  • Folders carry meaning: src/api for routes, src/modules for modules, src/workflows, src/subscribers, src/jobs and src/links.
  • Subscribers and jobs need a default function plus a config export; routes export HTTP method names.
  • Store requests carry a publishable key; admin requests need authentication; secrets stay on the server.
  • When a detail feels uncertain, confirm it against the documentation for your installed Medusa version.

To revisit the whole track, go back to What Is Medusa?.