Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 33 ยท Customizing the Backend

Custom Modules and Data Models

Build a custom Medusa module: define data models with model.define, generate a CRUD service with MedusaService, register the module, run migrations and resolve it.

Medusa's commerce features come from modules, and your own features should too. A custom module is a self-contained package of code inside your project that owns some data and the logic around it: a product review system, a loyalty ledger, a store-locator, a B2B quote desk. It gets its own database tables, its own service, and a name in the container, and nothing else can reach into its tables.

This lesson builds the anatomy of a module in five steps: data models, the service, the module definition, registration, and migrations. You will also see how a route or workflow gets hold of the service. The real code needs a Medusa project with Postgres, so it is read-only. The runnable stand-ins implement the ideas behind model.define and MedusaService in plain Node, so you can see what is generated for you and why. They are not Medusa's code.

The shape of a module

A module is a folder under src/modules:

TEXT
src/modules/review/
  models/
    review.ts        data models
  service.ts         the service class
  index.ts           the module definition
  migrations/        generated SQL migrations

The folder name is also the module's identity inside the project. Keep it short, lowercase and a single word if you can (review, loyalty). Why an isolated module and not just tables you query from a route? Because the same rules that keep the Product and Order modules independent now apply to your code: you can test it alone, swap its implementation, and never write a join that welds it to someone else's schema (cross-module relations use module links). This is the module layer from Architecture: Modules, Workflows and the Container.

Step 1: data models

You describe a table with model.define. The first argument is the table name, the second is an object of properties:

TypeScript
// src/modules/review/models/review.ts
import { model } from "@medusajs/framework/utils"

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

Each property is built from a property type and refined with chained modifiers:

Type Stores Notes
model.id() a prefixed unique id Use with .primaryKey().
model.text() strings The workhorse.
model.number() integers For ratings, counts, quantities.
model.float() floating-point numbers Avoid for money.
model.bigNumber() big decimal numbers Use for money-like values so no precision is lost (see Money as Integers).
model.boolean() true/false
model.enum([...]) one of a fixed set Validates values.
model.dateTime() timestamps
model.json() arbitrary JSON Good for metadata, bad for things you filter on.
model.array() a list of strings

Modifiers include .nullable(), .default(value), .unique(), .index() and .primaryKey(). Columns are NOT NULL unless you say .nullable(), which is a good default: opt in to missing values deliberately. Every model also gets created_at, updated_at and deleted_at columns automatically, and rows are soft-deleted by default (they get a deleted_at and are hidden from normal lists).

Relations connect models inside the same module: model.hasMany, model.hasOne, model.belongsTo and model.manyToMany. For example, a Review can have many ReviewImage rows, each with a belongsTo back to the review. Relations to models in other modules do not go here; use a link.

Step 2: the service

The service is the module's public API. You rarely write CRUD by hand. Extend the generated base class MedusaService, passing it your models:

TypeScript
// src/modules/review/service.ts
import { MedusaService } from "@medusajs/framework/utils"
import { Review } from "./models/review"

class ReviewModuleService extends MedusaService({ Review }) {
  async approve(id: string) {
    return await this.updateReviews({ id, status: "approved" })
  }
}

export default ReviewModuleService

For each model key you pass, the base class generates a family of methods named after it. For Review you get methods such as createReviews, retrieveReview, listReviews, listAndCountReviews, updateReviews, deleteReviews, softDeleteReviews and restoreReviews. Note the pattern: the plural form for operations on many, the singular for retrieve. They accept filters and options much like the filters and pagination you met in Query. Add your own methods for rules that are specific to the module (approve above), and keep them about this module's data. A method that needs products or orders belongs in a workflow, which can call several modules.

Step 3: the module definition

index.ts turns the service into a module and gives it a name:

TypeScript
// 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,
})

REVIEW_MODULE is the key under which the service will live in the container. Exporting it as a constant means routes import the constant instead of repeating a string that can be mistyped.

Step 4: register it

Medusa only loads modules you list in medusa-config.ts:

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

module.exports = defineConfig({
  projectConfig: { /* ... */ },
  modules: [
    { resolve: "./src/modules/review" },
  ],
})

Commerce modules are included by default, so you list only your own (and any provider modules). If you forget this step, the module's models exist but the service will not be in the container and resolve will fail with an unknown-registration error.

Step 5: migrations

Models describe tables; migrations create them. You do not write the SQL. The CLI compares your models with the previous state and generates a migration file:

Terminal
npx medusa db:generate review
npx medusa db:migrate

db:generate <module> writes a migration inside src/modules/review/migrations. Commit it. db:migrate applies pending migrations for all modules and links. When you change a model later, you generate another migration; you do not edit old ones that have already run in a shared environment. Run db:migrate as a step of every deployment before the new code serves traffic (see Deploying Medusa). Renames and type changes can lose data if done carelessly, so read the generated SQL before applying it in production.

Using the module

Anywhere you have a container, resolve the service by its key:

TypeScript
import { REVIEW_MODULE } from "../../modules/review"
import type ReviewModuleService from "../../modules/review/service"

export async function GET(req: MedusaRequest, res: MedusaResponse) {
  const reviews: ReviewModuleService = req.scope.resolve(REVIEW_MODULE)
  const [items, count] = await reviews.listAndCountReviews(
    { status: "approved" },
    { take: 10, skip: 0 }
  )
  res.json({ reviews: items, count })
}

The same resolve works in custom routes, subscribers, jobs and workflow steps. In a workflow step you resolve from the step's container argument instead.

flowchart LR
    M["models/review.ts<br/>model.define"] --> S["service.ts<br/>MedusaService generates CRUD"]
    S --> D["index.ts<br/>Module(name, service)"]
    D --> C["medusa-config.ts<br/>modules list"]
    M --> G["db:generate"]
    G --> MG["migrations/*.ts"]
    MG --> DB["db:migrate"]
    C --> R["container.resolve(name)"]

Models feed both the generated service and the generated migration; registration puts the service in the container.

Stand-in 1: from model definition to schema

A model definition is data. Everything Medusa does with it (the table, the validation, the migration) is derived from that data. This stand-in builds a miniature model DSL with the same chaining style, then derives a CREATE TABLE statement and a "diff" migration when you add a column. It is not Medusa's code and the SQL is a simplification.

Node.js A mini model.define that derives SQL

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 second migration adds only what changed. The same principle is why you never hand-edit old migrations: each one is a step in a history that every environment replays in order. The stand-in's diff function would also emit a drop column line (with a warning comment) if you removed a property from v2; real tools will not stop you from losing data either.

Stand-in 2: a service generated from models

MedusaService({ Review }) hands you methods you did not write. Here is the trick behind it: a function that takes model definitions and builds a class with methods named from the model name. The stand-in keeps rows in memory, validates writes against the model, supports filters with arrays, and soft-deletes.

Node.js A MedusaService-style CRUD generator

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.

Look at what you did not write: createReviews, listReviews, listAndCountReviews, retrieveReview, updateReviews and softDeleteReviews. You only wrote approve, the rule that is specific to your domain. Real MedusaService generates more methods, takes richer options (relations, ordering, transaction contexts) and persists to Postgres, but the mental model is the same.

Common mistakes

  • Not registering the module. The service is only in the container when medusa-config.ts lists it.
  • Forgetting migrations. Changing a model changes nothing in the database until you run db:generate and db:migrate.
  • Putting cross-module logic in the module service. A module should know only its own data; orchestrate in workflows and link instead.
  • Using model.float() for money. Use big numbers or integers in minor units.
  • Storing filterable data in json. Make it a real column and index it.
  • Editing applied migrations. Add a new migration instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What generates the methods createReviews and listReviews?

    MedusaService({ Review }) builds a family of CRUD methods named after each model. You only add methods for rules specific to your module.
  2. 2. You added a column to a model and restarted the server. The column does not exist in the database. Why?

    Models describe the desired schema, and migrations apply it. Run db:generate for the module and then db:migrate.
  3. 3. Where do you tell Medusa to load your custom module?

    The modules array lists the custom modules by their path (resolve). Without it the service is never registered in the container.
  4. 4. Which is the best place for a rule that needs data from your review module and the Order module?

    Modules are isolated, so orchestration across modules belongs in workflows (and links), not inside one module's service.

Summary

  • A custom module lives in src/modules/<name> and consists of models, a service, a module definition and migrations.
  • model.define describes tables with property types and modifiers; columns are required unless marked .nullable().
  • MedusaService generates CRUD methods per model; add only your domain-specific methods.
  • Register the module in medusa-config.ts, then db:generate and db:migrate to create its tables.
  • Resolve the service by its key from the container in routes, subscribers, jobs and workflow steps.

Next, connect your module's data to commerce data with Module Links.