Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 33 ยท Getting Started

Create a Medusa Project

Create a Medusa 2 project step by step: requirements, create-medusa-app, the folder layout, medusa-config.ts, CLI commands and environment variables.

Setting up Medusa takes a few minutes, but each piece that appears on disk has a job. If you know what the folders are for before you open them, the rest of the track reads much more easily. This lesson covers what you need installed, how to create a project, what the generated folders mean, how medusa-config.ts works and which CLI commands you will use every day.

Because Medusa needs Postgres and a Node project, none of it can run on this site. The commands and configuration below are read-only. Two runnable stand-ins at the end show the ideas: one validates a configuration object, the other maps file paths to the API routes they create.

What you need

  • Node.js in a version that the Medusa release supports (a current LTS release is the safe choice; the installer checks this).
  • PostgreSQL. Medusa 2 stores all its data in Postgres. There is no SQLite or MySQL option.
  • Redis, but only later. In development Medusa falls back to in-memory versions of the event bus, cache and workflow engine. In production you want Redis-backed modules so several server processes can share events and workflow state (Deploying Medusa).
  • A package manager (npm, yarn or pnpm) and Git.

Creating the project

The official generator asks for a project name, offers to add the Next.js starter storefront, creates the database and runs the first migrations.

Terminal
npx create-medusa-app@latest my-store
# answer the prompts: project name, Postgres connection, storefront yes/no
cd my-store
npx medusa develop

The server listens on port 9000 by default. The Admin dashboard is served under /app of that server. The first time you visit it, you need an admin user. You can create one with the CLI (use your own email and a strong password):

Terminal
npx medusa user --email [email protected] --password "choose-a-long-password"

The folder layout

A generated project has a src folder with one subfolder for each kind of customization. You add files; Medusa discovers them by location, so there is no manual registration for most of them.

TEXT
my-store/
  medusa-config.ts      main configuration
  .env                  secrets and URLs (never commit)
  package.json          scripts: dev, build, start, seed
  src/
    admin/              dashboard widgets and pages (React)
    api/                custom API routes and middlewares
    jobs/               scheduled jobs (cron)
    links/              links between modules' records
    modules/            your own modules and data models
    scripts/            one-off scripts run with "medusa exec"
    subscribers/        event handlers
    workflows/          multi-step operations
flowchart TD
    C["medusa-config.ts<br/>+ .env"] --> S["Medusa server"]
    A["src/api<br/>routes"] --> S
    W["src/workflows"] --> S
    M["src/modules"] --> S
    SU["src/subscribers"] --> S
    J["src/jobs"] --> S
    L["src/links"] --> S
    S --> P[("Postgres")]
    S --> R[("Redis, in production")]

Every folder under src feeds the same server, which reads the configuration to find its database and secrets.

Each of these folders gets its own lesson: routes in Custom API Routes and Middleware, modules in Custom Modules and Data Models, links in Module Links, workflows in Workflows and Steps, subscribers in Events and Subscribers and jobs in Scheduled Jobs.

medusa-config.ts

The configuration file exports the result of defineConfig. A trimmed example looks like this (read-only; yours may contain more keys):

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,
    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",
    },
  },
  modules: [
    // optional: swap or add modules, for example Redis-backed ones
  ],
})

Three groups of settings matter at first:

  • databaseUrl points at Postgres. Without it nothing starts.
  • CORS lists (storeCors, adminCors, authCors) are comma-separated origins allowed to call each part of the API from a browser. A storefront on a different origin that is missing from storeCors fails with a browser error even though the server is healthy.
  • jwtSecret and cookieSecret sign tokens and session cookies. The fallback value supersecret is fine on your laptop and a serious vulnerability in production (Security and Performance).

The modules array is where you register your own modules or replace defaults. Commerce modules such as Product and Cart are loaded without being listed.

Everyday CLI commands

All commands run through npx medusa (or your package scripts).

Command What it does
medusa develop Starts the server with file watching for development
medusa db:create Creates the database named in the connection string
medusa db:migrate Applies pending migrations, including those of your modules
medusa db:generate <module> Generates a migration for a custom module's data models
medusa user Creates an admin user
medusa exec <file> Runs a script from src/scripts with the container available
medusa build and medusa start Production build and start

A common rhythm while developing a custom module is: edit the model, run db:generate, run db:migrate, restart. After a git pull that adds migrations, run db:migrate again, or the new code will fail on missing tables.

Environment variables

The .env file holds values that differ between machines. A typical development file contains these names (values are examples only):

TEXT
DATABASE_URL=postgres://postgres:password@localhost:5432/medusa-store
STORE_CORS=http://localhost:8000
ADMIN_CORS=http://localhost:5173,http://localhost:9000
AUTH_CORS=http://localhost:5173,http://localhost:9000,http://localhost:8000
JWT_SECRET=change-me
COOKIE_SECRET=change-me-too
REDIS_URL=redis://localhost:6379

Never commit this file. In production the values come from the host's secret store.

Stand-in 1: validating a configuration object

Medusa's own defineConfig fills in defaults and the server fails fast when something essential is missing. The stand-in below is not Medusa's implementation; it shows the same style of checks so you can see what a good configuration validator looks for.

JS Validate a project configuration

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

No output.

Stand-in 2: from file path to route

Medusa builds API routes from the folder structure under src/api: a file named route.ts exports functions named after HTTP methods, and folder names become URL segments, with [id] meaning a path parameter. The helper below reproduces that naming rule so you can predict the URL for any file. It is a stand-in for the idea; the real loader does more.

JS Predict the route for a file

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

No output.

Common mistakes

  • Forgetting db:migrate after pulling changes, which produces "relation does not exist" errors.
  • Leaving the default secrets in a deployed environment.
  • Omitting the storefront origin from STORE_CORS.
  • Looking for MySQL or SQLite support: Medusa 2 needs Postgres.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which database does Medusa 2 require?

    Medusa 2 stores its data in PostgreSQL only. Redis is a separate, mostly production-time dependency for events, caching and workflow state.
  2. 2. Where do custom API routes live in a project?

    Files named route.ts under src/api become routes, and the folder path becomes the URL. Modules are for data models and services.
  3. 3. A storefront on another origin gets a browser CORS error while the server is healthy. What should you check first?

    storeCors lists the origins allowed to call the Store API from a browser. A missing origin blocks the request in the browser.
  4. 4. When do you run medusa db:migrate?

    Migrations bring the database schema in line with the code. New code without its migrations fails on missing tables or columns.

Summary

  • Medusa 2 needs Node and PostgreSQL; Redis becomes important in production.
  • create-medusa-app creates the project, the database and the first migrations; medusa develop starts the server on port 9000.
  • Folders under src (api, modules, workflows, subscribers, jobs, links, admin, scripts) are discovered by location.
  • medusa-config.ts holds the database URL, CORS lists, secrets and the module list; values come from .env.
  • Change the default secrets before deploying, and run db:migrate whenever migrations change.

Next: Architecture: Modules, Workflows and the Container