1 export const metadata = {
2 title: `${pageNumber} Modules`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you’ll learn about modules and how to create them.
8
9 ## What is a Module?
10
11 A module is a reusable package of functionalities related to a single domain or integration. Medusa comes with multiple pre-built modules for core commerce needs, such as the [Cart Module](!resources!/commerce-modules/cart) that holds the data models and business logic for cart operations.
12
13 When building a commerce application, you often need to introduce custom behavior specific to your products, tech stack, or your general ways of working. In other commerce platforms, introducing custom business logic and data models requires setting up separate applications to manage these customizations.
14
15 Medusa removes this overhead by allowing you to easily write custom modules that integrate into the Medusa application without affecting the existing setup. You can also re-use your modules across Medusa projects.
16
17 As you learn more about Medusa, you will see that modules are central to customizations and integrations. With modules, your Medusa application can turn into a middleware solution for your commerce ecosystem.
18
19 <Note title="Use a module if" type="success">
20
21 - You want to build a custom feature related to a single domain or integrate a third-party service.
22
23 </Note>
24
25 <Note title="Don't use a module if" type="error">
26
27 - You want to create a reusable package of customizations that include not only modules, but also API routes, workflows, and other customizations. Instead, use a [plugin](../plugins/page.mdx).
28
29 </Note>
30
31 ---
32
33 ## How to Create a Module?
34
35 In a module, you define data models that represent new tables in the database, and you manage these models in a class called a service. Then, the Medusa application registers the module's service in the [Medusa container](../../fundamentals/medusa-container/page.mdx) so that you can build commerce flows and features around the functionalities provided by the module.
36
37 In this section, you'll build a Blog Module that has a `Post` data model and a service to manage that data model. You'll also expose an API endpoint to create a blog post.
38
39 Modules are created in a sub-directory of `src/modules`. So, start by creating the directory `src/modules/blog`.
40
41 ### 1. Create Data Model
42
43 A data model represents a table in the database. You create data models using Medusa's data modeling language (DML). It simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations.
44
45 You create a data model in a TypeScript or JavaScript file under the `models` directory of a module. So, to create a `Post` data model in the Blog Module, create the file `src/modules/blog/models/post.ts` with the following content:
46
47 ![Blog module directory structure showing the organized file hierarchy with the newly created 'models' folder containing the 'post.ts' data model file, which defines the data model for blog posts using Medusa's data modeling language](https://res.cloudinary.com/dza7lstvk/image/upload/v1732806790/Medusa%20Book/blog-dir-overview-1_jfvovj.jpg)
48
49 ```ts title="src/modules/blog/models/post.ts"
50 import { model } from "@medusajs/framework/utils"
51
52 const Post = model.define("post", {
53 id: model.id().primaryKey(),
54 title: model.text(),
55 })
56
57 export default Post
58 ```
59
60 You define the data model using the `define` method of the DML. It accepts two parameters:
61
62 1. The first one is the name of the data model's table in the database. Use snake-case names.
63 2. The second is an object, which is the data model's schema. The schema's properties are defined using the `model`'s methods, such as `text` and `id`.
64 - Data models automatically have the date properties `created_at`, `updated_at`, and `deleted_at`, so you don't need to add them manually.
65
66 <Note title="Tip">
67
68 Learn about other property types in [this chapter](../../fundamentals/data-models/properties/page.mdx#property-types).
69
70 </Note>
71
72 The code snippet above defines a `Post` data model with `id` and `title` properties.
73
74 ### 2. Create Service
75
76 You perform database operations on your data models in a service, which is a class exported by the module and acts like an interface to its functionalities. Medusa registers the service in its [container](../../fundamentals/medusa-container/page.mdx), allowing you to resolve and use it when building custom commerce flows.
77
78 You define a service in a `service.ts` or `service.js` file at the root of your module's directory. So, to create the Blog Module's service, create the file `src/modules/blog/service.ts` with the following content:
79
80 ![Updated directory overview after adding the service](https://res.cloudinary.com/dza7lstvk/image/upload/v1732807230/Medusa%20Book/blog-dir-overview-2_avzb9l.jpg)
81
82 export const highlights = [
83 ["4", "MedusaService", "The service factory function."],
84 ["5", "Post", "The data models to generate data-management methods for."]
85 ]
86
87 ```ts title="src/modules/blog/service.ts" highlights={highlights}
88 import { MedusaService } from "@medusajs/framework/utils"
89 import Post from "./models/post"
90
91 class BlogModuleService extends MedusaService({
92 Post,
93 }){
94 }
95
96 export default BlogModuleService
97 ```
98
99 Your module's service extends a class generated by `MedusaService` from the Modules SDK. This class comes with generated methods for data-management Create, Read, Update, and Delete (CRUD) operations on each of your modules, saving you time that can be spent on building custom business logic.
100
101 The `MedusaService` function accepts an object of data models to generate methods for. You can pass all data models in your module in this object.
102
103 For example, the `BlogModuleService` now has a `createPosts` method to create post records, and a `retrievePost` method to retrieve a post record. The suffix of each method (except for `retrieve`) is the pluralized name of the data model.
104
105 <Note>
106
107 Find all methods generated by the `MedusaService` in [this reference](!resources!/service-factory-reference)
108
109 </Note>
110
111 If a module doesn't have data models, such as when it's integrating a third-party service, it doesn't need to extend `MedusaService`.
112
113 ### 3. Export Module Definition
114
115 The final piece to a module is its definition, which is exported in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its main service. Medusa will then register the main service in the container under the module's name.
116
117 So, to export the definition of the Blog Module, create the file `src/modules/blog/index.ts` with the following content:
118
119 ![Updated directory overview after adding the module definition](https://res.cloudinary.com/dza7lstvk/image/upload/v1732808511/Medusa%20Book/blog-dir-overview-3_dcgjaa.jpg)
120
121 export const moduleDefinitionHighlights = [
122 ["4", "BLOG_MODULE", "Export the module's name to reference it in other customizations."],
123 ["6", "BLOG_MODULE", "Specify the module's name."],
124 ["7", "service", "Specify the module's main service."]
125 ]
126
127 ```ts title="src/modules/blog/index.ts" highlights={moduleDefinitionHighlights}
128 import BlogModuleService from "./service"
129 import { Module } from "@medusajs/framework/utils"
130
131 export const BLOG_MODULE = "blog"
132
133 export default Module(BLOG_MODULE, {
134 service: BlogModuleService,
135 })
136 ```
137
138 You use `Module` from the Modules SDK to create the module's definition. It accepts two parameters:
139
140 1. The name that the module's main service is registered under (`blog`). The module name can contain only alphanumeric characters and underscores.
141 2. An object with a required property `service` indicating the module's main service.
142
143 <Note title="Tip">
144
145 You export `BLOG_MODULE` to reference the module's name more reliably when resolving its service in other customizations.
146
147 </Note>
148
149 ### 4. Add Module to Medusa's Configurations
150
151 <Note>
152
153 If you're creating the module in a plugin, this step isn't required as the module is registered when the plugin is registered. Learn more about plugins in [this documentation](../plugins/page.mdx).
154
155 </Note>
156
157 Once you finish building the module, add it to Medusa's configurations to start using it. Medusa will then register the module's main service in the Medusa container, allowing you to resolve and use it in other customizations.
158
159 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
160
161 ```ts title="medusa-config.ts" highlights={[["7"]]}
162 module.exports = defineConfig({
163 projectConfig: {
164 // ...
165 },
166 modules: [
167 {
168 resolve: "./src/modules/blog",
169 },
170 ],
171 })
172 ```
173
174 Each object in the `modules` array has a `resolve` property, whose value is either a path to the module's directory, or an `npm` package’s name.
175
176 ### 5. Generate Migrations
177
178 Since data models represent tables in the database, you define how they're created in the database with migrations. A migration is a TypeScript or JavaScript file that defines database changes made by a module.
179
180 Migrations are useful when you re-use a module or you're working in a team, so that when one member of a team makes a database change, everyone else can reflect it on their side by running the migrations.
181
182 You don't have to write migrations yourself. Medusa's CLI tool has a command that generates the migrations for you. You can also use this command again when you make changes to the module at a later point, and it will generate new migrations for that change.
183
184 To generate a migration for the Blog Module, run the following command in your Medusa application's directory:
185
186 <Note>
187
188 If you're creating the module in a plugin, use the [plugin\:db\:generate command](!resources!/medusa-cli/commands/plugin#plugindbgenerate) instead.
189
190 </Note>
191
192 ```bash npx2yarn
193 npx medusa db:generate blog
194 ```
195
196 The `db:generate` command of the Medusa CLI accepts one or more module names to generate the migration for. It will create a migration file for the Blog Module in the directory `src/modules/blog/migrations` similar to the following:
197
198 <Note>
199
200 As of [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0), MikroORM dependencies are included in the `@medusajs/framework` package. If you're using an older version of Medusa, change the import statement to `@mikro-orm/migrations`.
201
202 </Note>
203
204 ```ts
205 import { Migration } from "@medusajs/framework/mikro-orm/migrations"
206
207 export class Migration20241121103722 extends Migration {
208
209 async up(): Promise<void> {
210 this.addSql("create table if not exists \"post\" (\"id\" text not null, \"title\" text not null, \"created_at\" timestamptz not null default now(), \"updated_at\" timestamptz not null default now(), \"deleted_at\" timestamptz null, constraint \"post_pkey\" primary key (\"id\"));")
211 }
212
213 async down(): Promise<void> {
214 this.addSql("drop table if exists \"post\" cascade;")
215 }
216
217 }
218 ```
219
220 In the migration class, the `up` method creates the table `post` and defines its columns using PostgreSQL syntax. The `down` method drops the table.
221
222 ### 6. Run Migrations
223
224 To reflect the changes in the generated migration file on the database, run the `db:migrate` command:
225
226 <Note>
227
228 If you're creating the module in a plugin, run this command on the Medusa application that the plugin is installed in.
229
230 </Note>
231
232 ```bash npx2yarn
233 npx medusa db:migrate
234 ```
235
236 This creates the `post` table in the database.
237
238 ---
239
240 ## Test the Module
241
242 Since the module's main service is registered in the Medusa container, you can resolve it in other customizations to use its methods.
243
244 To test out the Blog Module, you'll add the functionality to create a post in a [workflow](../../fundamentals/workflows/page.mdx), which is a special function that performs a task in a series of steps with rollback logic. Then, you'll expose an [API route](../api-routes/page.mdx) that creates a blog post by executing the workflow.
245
246 <Note title="Why use a workflow?">
247
248 By building a commerce feature in a workflow, you can execute it in other customizations while ensuring data consistency across systems. If an error occurs during execution, every step has its own rollback logic to undo its actions. Workflows have other special features which you can learn about in [this chapter](../../fundamentals/workflows/page.mdx).
249
250 </Note>
251
252 To create the workflow, create the file `src/workflows/create-post.ts` with the following content:
253
254 export const workflowHighlights = [
255 ["14", "createPostStep", "Define a step that creates a post using the Blog Module."],
256 ["17", "resolve", "Resolve the Blog Module's service from the Medusa container."],
257 ["19", "createPosts", "Create a blog post using the Blog Module service's generated method."],
258 ["25", "", "Add a compensation function that only runs if an error occurs in the workflow."],
259 ["31", "deletePosts", "Delete the post if an error occurs using the Blog Module service's generated method."],
260 ["35", "createWorkflow", "Create and workflow that can be executed to create a blog post."],
261 ["38", "createPostStep", "Execute the `createPostStep` to create the post."]
262 ]
263
264 ```ts title="src/workflows/create-post.ts" highlights={workflowHighlights}
265 import {
266 createStep,
267 createWorkflow,
268 StepResponse,
269 WorkflowResponse,
270 } from "@medusajs/framework/workflows-sdk"
271 import { BLOG_MODULE } from "../modules/blog"
272 import BlogModuleService from "../modules/blog/service"
273
274 type CreatePostWorkflowInput = {
275 title: string
276 }
277
278 const createPostStep = createStep(
279 "create-post",
280 async ({ title }: CreatePostWorkflowInput, { container }) => {
281 const blogModuleService: BlogModuleService = container.resolve(BLOG_MODULE)
282
283 const post = await blogModuleService.createPosts({
284 title,
285 })
286
287 return new StepResponse(post, post)
288 },
289 async (post, { container }) => {
290 if (!post) {
291 return
292 }
293 const blogModuleService: BlogModuleService = container.resolve(BLOG_MODULE)
294
295 await blogModuleService.deletePosts(post.id)
296 }
297 )
298
299 export const createPostWorkflow = createWorkflow(
300 "create-post",
301 (postInput: CreatePostWorkflowInput) => {
302 const post = createPostStep(postInput)
303
304 return new WorkflowResponse(post)
305 }
306 )
307 ```
308
309 The workflow has a single step `createPostStep` that creates a post. In the step, you resolve the Blog Module's service from the Medusa container, which the step receives as a parameter. Then, you create the post using the method `createPosts` of the service, which was generated by `MedusaService`.
310
311 The step also has a compensation function, which is a function passed as a third-parameter to `createStep` that implements the logic to rollback the change made by a step in case an error occurs during the workflow's execution.
312
313 You'll now execute that workflow in an API route to expose the feature of creating blog posts to clients. To create an API route, create the file `src/api/blog/posts/route.ts` with the following content:
314
315 ```ts title="src/api/blog/posts/route.ts"
316 import type {
317 MedusaRequest,
318 MedusaResponse,
319 } from "@medusajs/framework/http"
320 import {
321 createPostWorkflow,
322 } from "../../../workflows/create-post"
323
324 export async function POST(
325 req: MedusaRequest,
326 res: MedusaResponse
327 ) {
328 const { result: post } = await createPostWorkflow(req.scope)
329 .run({
330 input: {
331 title: "My Post",
332 },
333 })
334
335 res.json({
336 post,
337 })
338 }
339 ```
340
341 This adds a `POST` API route at `/blog/posts`. In the API route, you execute the `createPostWorkflow` by invoking it, passing it the Medusa container in `req.scope`, then invoking the `run` method. In the `run` method, you pass the workflow's input in the `input` property.
342
343 To test this out, start the Medusa application:
344
345 ```bash npm2yarn
346 npm run dev
347 ```
348
349 Then, send a `POST` request to `/blog/posts`:
350
351 ```bash
352 curl -X POST http://localhost:9000/blog/posts
353 ```
354
355 This will create a post and return it in the response:
356
357 ```json
358 {
359 "post": {
360 "id": "123...",
361 "title": "My Post",
362 "created_at": "...",
363 "updated_at": "..."
364 }
365 }
366 ```
367
368 You can also execute the workflow from a [subscriber](../../fundamentals/events-and-subscribers/page.mdx) when an event occurs, or from a [scheduled job](../../fundamentals/scheduled-jobs/page.mdx) to run it at a specified interval.