Raw
1 import { Table, CardList } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} From Medusa v1 to v2: Conceptual Differences`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn about the differences and changes between concepts in Medusa v1 to v2.
10
11 ## What to Expect in This Chapter
12
13 This chapter is designed to help developers migrate from Medusa v1 to v2 by understanding the conceptual differences between the two versions.
14
15 This chapter will cover:
16
17 - The general steps to update your project from Medusa v1 to v2.
18 - The changes in tools and plugins between Medusa v1 and v2.
19 - The high-level changes in the concepts and commerce features between Medusa v1 and v2.
20
21 By following this chapter, you'll learn about the general changes you need to make in your project, with links to read more about each topic. Only topics documented in the v1 documentation are covered.
22
23 This chapter is also useful for developers who are already familiar with Medusa v1 and want to learn about the main differences from Medusa v2. However, it doesn't cover all the new and improved concepts in Medusa v2. Instead, it's highly recommended to read the rest of this documentation to learn about them.
24
25 ---
26
27 ## Prerequisites
28
29 ### Node.js Version
30
31 While Medusa v1 supported Node.js v16+, Medusa v2 requires Node.js v20.19.0+ or v22.12.0+. So, make sure to update your Node.js version if it's older.
32
33 Refer to the [Node.js documentation](https://nodejs.org/en/docs/) for instructions on how to update your Node.js version.
34
35 ### New Database
36
37 Medusa v2 makes big changes to the database. So, your existing database will not be compatible with the database for your v2 project.
38
39 If you want to keep your product catalog, you should export the products from the admin dashboard, as explained in [this V1 User Guide](https://docs.medusajs.com/v1/user-guide/products/export). Then, you can import them into your new v2 project from the [Medusa Admin](!user-guide!/products/import).
40
41 For other data types, you'll probably need to migrate them manually through custom scripts. [Custom CLI scripts](../../fundamentals/custom-cli-scripts/page.mdx) may be useful for this.
42
43 ---
44
45 ## How to Upgrade from Medusa v1 to v2
46
47 In this section, you'll learn how to upgrade your Medusa project from v1 to v2.
48
49 <Note>
50
51 To create a fresh new Medusa v2 project, check out the [Installation chapter](../../installation/page.mdx).
52
53 </Note>
54
55 <Note type="warning">
56
57 It's highly recommended to fully go through this chapter before you actually update your application, as some v1 features may have been removed or heavily changed in v2. By doing so, you'll formulate a clearer plan for your migration process and its feasibility.
58
59 </Note>
60
61 ### 1. Update Dependencies in package.json
62
63 The first step is to update the dependencies in your `package.json`.
64
65 A basic v2 project has the following dependencies in `package.json`:
66
67 ```json
68 {
69 "dependencies": {
70 "@medusajs/admin-sdk": "2.8.2",
71 "@medusajs/cli": "2.8.2",
72 "@medusajs/framework": "2.8.2",
73 "@medusajs/medusa": "2.8.2"
74 },
75 "devDependencies": {
76 "@medusajs/test-utils": "2.8.2",
77 "@swc/core": "1.5.7",
78 "@swc/jest": "^0.2.36",
79 "@types/jest": "^29.5.13",
80 "@types/node": "^20.0.0",
81 "@types/react": "^18.3.2",
82 "@types/react-dom": "^18.2.25",
83 "jest": "^29.7.0",
84 "prop-types": "^15.8.1",
85 "react": "^18.2.0",
86 "react-dom": "^18.2.0",
87 "ts-node": "^10.9.2",
88 "typescript": "^5.6.2",
89 "vite": "^5.2.11",
90 "yalc": "^1.0.0-pre.53"
91 }
92 }
93 ```
94
95 The main changes are:
96
97 - You need to install the following Medusa packages (All these packages use the same version):
98 - `@medusajs/admin-sdk`
99 - `@medusajs/cli`
100 - `@medusajs/framework`
101 - `@medusajs/medusa`
102 - `@medusajs/test-utils` (as a dev dependency)
103 - You need to install the following extra packages for development and testing:
104 - `@swc/core@1.5.7`
105 - `@swc/jest@^0.2.36`
106 - `@types/node@^20.0.0`
107 - `jest@^29.7.0`
108 - `ts-node@^10.9.2`
109 - `typescript@^5.6.2`
110 - `vite@^5.2.11`
111 - `yalc@^1.0.0-pre.53`
112 - Other packages, such as `@types/react` and `@types/react-dom`, are necessary for admin development and TypeScript support.
113
114 <Note>
115
116 Notice that Medusa now uses MikroORM instead of TypeORM for database functionalities.
117
118 </Note>
119
120 Once you're done, run the following command to install the new dependencies:
121
122 ```bash npm2yarn
123 npm install
124 ```
125
126 <Note title="Medusa Module Dependencies" forceMultiline>
127
128 In Medusa v1, you needed to install Medusa modules like the Event, Product, or Pricing modules.
129
130 These modules are now available out of the box, and you don't need to install or configure them separately.
131
132 </Note>
133
134 ### 2. Update Script in package.json
135
136 Medusa v2 comes with changes and improvements to its CLI tool. So, update your `package.json` with the following scripts:
137
138 ```json
139 {
140 "scripts": {
141 "build": "medusa build",
142 "seed": "medusa exec ./src/scripts/seed.ts",
143 "start": "medusa start",
144 "dev": "medusa develop",
145 "test:integration:http": "TEST_TYPE=integration:http NODE_OPTIONS=--experimental-vm-modules jest --silent=false --runInBand --forceExit",
146 "test:integration:modules": "TEST_TYPE=integration:modules NODE_OPTIONS=--experimental-vm-modules jest --silent=false --runInBand --forceExit",
147 "test:unit": "TEST_TYPE=unit NODE_OPTIONS=--experimental-vm-modules jest --silent --runInBand --forceExit"
148 }
149 }
150 ```
151
152 Where:
153
154 - `build`: Builds the Medusa application for production.
155 - `seed`: Seeds the database with initial data.
156 - `start`: Starts the Medusa server in production.
157 - `dev`: Starts the Medusa server in development mode.
158 - `test:integration:http`: Runs HTTP integration tests.
159 - `test:integration:modules`: Runs module integration tests.
160 - `test:unit`: Runs unit tests.
161
162 You'll learn more about the [changes in the CLI tool later in this chapter](#medusa-cli-changes). You can also refer to the following documents to learn more about these changes:
163
164 - [Medusa CLI reference](!resources!/medusa-cli)
165 - [Build Medusa Application](../../build/page.mdx)
166 - [Integration and Module Tests](../../debugging-and-testing/testing-tools/page.mdx).
167
168 ### 3. TSConfig Changes
169
170 In Medusa v1, you had multiple TSConfig configuration files for different customization types. For example, you had `tsconfig.admin.json` for admin customizations and `tsconfig.server.json` for server customizations.
171
172 In Medusa v2, you only need one [root tsconfig.json](https://github.com/medusajs/medusa-starter-default/blob/master/tsconfig.json) file in your project. For admin customizations, you create a [src/admin/tsconfig.json file](https://github.com/medusajs/medusa-starter-default/blob/master/src/admin/tsconfig.json). Refer to each of those links for the recommended configurations.
173
174 ### 4. Update Configuration File
175
176 In Medusa v1, you configured your application in the `medusa-config.js` file. Medusa v2 supports this file as `medusa-config.ts`, so make sure to rename it.
177
178 `medusa-config.ts` now exports configurations created with the `defineConfig` utility. It also uses the [loadEnv](../../fundamentals/environment-variables/page.mdx) utility to load environment variables based on the current environment.
179
180 For example, this is the configuration file for a basic Medusa v2 project:
181
182 ```ts title="medusa-config.ts"
183 import { loadEnv, defineConfig } from "@medusajs/framework/utils"
184
185 loadEnv(process.env.NODE_ENV || "development", process.cwd())
186
187 module.exports = defineConfig({
188 projectConfig: {
189 databaseUrl: process.env.DATABASE_URL,
190 http: {
191 storeCors: process.env.STORE_CORS!,
192 adminCors: process.env.ADMIN_CORS!,
193 authCors: process.env.AUTH_CORS!,
194 jwtSecret: process.env.JWT_SECRET || "supersecret",
195 cookieSecret: process.env.COOKIE_SECRET || "supersecret",
196 },
197 },
198 })
199 ```
200
201 You can refer to the full list of configurations in the [Medusa Configurations](../../configurations/medusa-config/page.mdx) chapter. The following table highlights the main changes between v1 and v2:
202
203 <Table>
204 <Table.Header>
205 <Table.Row>
206 <Table.HeaderCell>
207 Medusa v1
208 </Table.HeaderCell>
209 <Table.HeaderCell>
210 Medusa v2
211 </Table.HeaderCell>
212 </Table.Row>
213 </Table.Header>
214 <Table.Body>
215 <Table.Row>
216 <Table.Cell>
217 `projectConfig.store_cors`
218 </Table.Cell>
219 <Table.Cell>
220 [projectConfig.http.storeCors](../../configurations/medusa-config/page.mdx#httpstorecors)
221 </Table.Cell>
222 </Table.Row>
223 <Table.Row>
224 <Table.Cell>
225 `projectConfig.admin_cors`
226 </Table.Cell>
227 <Table.Cell>
228 [projectConfig.http.adminCors](../../configurations/medusa-config/page.mdx#httpadmincors)
229 </Table.Cell>
230 </Table.Row>
231 <Table.Row>
232 <Table.Cell>
233 `projectConfig.auth_cors`
234 </Table.Cell>
235 <Table.Cell>
236 [projectConfig.http.authCors](../../configurations/medusa-config/page.mdx#httpauthcors)
237 </Table.Cell>
238 </Table.Row>
239 <Table.Row>
240 <Table.Cell>
241 `projectConfig.cookie_secret`
242 </Table.Cell>
243 <Table.Cell>
244 [projectConfig.http.cookieSecret](../../configurations/medusa-config/page.mdx#httpcookiesecret)
245 </Table.Cell>
246 </Table.Row>
247 <Table.Row>
248 <Table.Cell>
249 `projectConfig.jwt_secret`
250 </Table.Cell>
251 <Table.Cell>
252 [projectConfig.http.jwtSecret](../../configurations/medusa-config/page.mdx#httpjwtsecret)
253 </Table.Cell>
254 </Table.Row>
255 <Table.Row>
256 <Table.Cell>
257 `projectConfig.database_database`
258 </Table.Cell>
259 <Table.Cell>
260 [projectConfig.databaseName](../../configurations/medusa-config/page.mdx#databasename)
261 </Table.Cell>
262 </Table.Row>
263 <Table.Row>
264 <Table.Cell>
265 `projectConfig.database_url`
266 </Table.Cell>
267 <Table.Cell>
268 [projectConfig.databaseUrl](../../configurations/medusa-config/page.mdx#databaseurl)
269 </Table.Cell>
270 </Table.Row>
271 <Table.Row>
272 <Table.Cell>
273 `projectConfig.database_schema`
274 </Table.Cell>
275 <Table.Cell>
276 [projectConfig.databaseSchema](../../configurations/medusa-config/page.mdx#databaseschema)
277 </Table.Cell>
278 </Table.Row>
279 <Table.Row>
280 <Table.Cell>
281 `projectConfig.database_logging`
282 </Table.Cell>
283 <Table.Cell>
284 [projectConfig.databaseLogging](../../configurations/medusa-config/page.mdx#databaselogging)
285 </Table.Cell>
286 </Table.Row>
287 <Table.Row>
288 <Table.Cell>
289 `projectConfig.database_extra`
290 </Table.Cell>
291 <Table.Cell>
292 [projectConfig.databaseDriverOptions](../../configurations/medusa-config/page.mdx#databasedriveroptions)
293 </Table.Cell>
294 </Table.Row>
295 <Table.Row>
296 <Table.Cell>
297 `projectConfig.database_driver_options`
298 </Table.Cell>
299 <Table.Cell>
300 [projectConfig.databaseDriverOptions](../../configurations/medusa-config/page.mdx#databasedriveroptions)
301 </Table.Cell>
302 </Table.Row>
303 <Table.Row>
304 <Table.Cell>
305 `projectConfig.redis_url`
306 </Table.Cell>
307 <Table.Cell>
308 [projectConfig.redisUrl](../../configurations/medusa-config/page.mdx#redisurl)
309 </Table.Cell>
310 </Table.Row>
311 <Table.Row>
312 <Table.Cell>
313 `projectConfig.redis_prefix`
314 </Table.Cell>
315 <Table.Cell>
316 [projectConfig.redisPrefix](../../configurations/medusa-config/page.mdx#redisprefix)
317 </Table.Cell>
318 </Table.Row>
319 <Table.Row>
320 <Table.Cell>
321 `projectConfig.redis_options`
322 </Table.Cell>
323 <Table.Cell>
324 [projectConfig.redisOptions](../../configurations/medusa-config/page.mdx#redisoptions)
325 </Table.Cell>
326 </Table.Row>
327 <Table.Row>
328 <Table.Cell>
329 `projectConfig.session_options`
330 </Table.Cell>
331 <Table.Cell>
332 [projectConfig.sessionOptions](../../configurations/medusa-config/page.mdx#sessionoptions)
333 </Table.Cell>
334 </Table.Row>
335 <Table.Row>
336 <Table.Cell>
337 `projectConfig.http_compression`
338 </Table.Cell>
339 <Table.Cell>
340 [projectConfig.http.compression](../../configurations/medusa-config/page.mdx#httpcompression)
341 </Table.Cell>
342 </Table.Row>
343 <Table.Row>
344 <Table.Cell>
345 `projectConfig.jobs_batch_size`
346 </Table.Cell>
347 <Table.Cell>
348 No longer supported.
349 </Table.Cell>
350 </Table.Row>
351 <Table.Row>
352 <Table.Cell>
353 `projectConfig.worker_mode`
354 </Table.Cell>
355 <Table.Cell>
356 [projectConfig.workerMode](../../configurations/medusa-config/page.mdx#workermode)
357 </Table.Cell>
358 </Table.Row>
359 <Table.Row>
360 <Table.Cell>
361 `modules`
362 </Table.Cell>
363 <Table.Cell>
364 [Array of modules](../../configurations/medusa-config/page.mdx#module-configurations-modules)
365 </Table.Cell>
366 </Table.Row>
367 </Table.Body>
368 </Table>
369
370 #### Plugin Changes
371
372 While the `plugins` configuration hasn't changed, plugins available in Medusa v1 are not compatible with Medusa v2. These are covered later in the [Plugin Changes](#plugin-changes) section.
373
374 #### Module Changes
375
376 In Medusa v1, you had to configure modules like Inventory, Stock Location, Pricing, and Product. These modules are now available out of the box, and you don't need to install or configure them separately.
377
378 For the Cache and Event modules, refer to the [Redis Caching Module Provider](!resources!/infrastructure-modules/caching/providers/redis) and [Redis Event Module](!resources!/infrastructure-modules/event/redis) documentations to learn how to configure them in v2 if you had them configured in v1.
379
380 #### Feature Flags
381
382 Some features like product categories and tax inclusive pricing were disabled behind feature flags.
383
384 All of these features are now available out-of-the-box. So, you don't need to enable them in your configuration file anymore.
385
386 #### Admin Configurations
387
388 In v1, the admin dashboard was installed as a plugin with configurations. In v2, the Medusa Admin is available out-of-the-box with different configurations.
389
390 The [Medusa Admin Changes](#medusa-admin-changes) section covers the changes in the Medusa Admin configurations and customizations.
391
392 ### 5. Setup New Database
393
394 Now that you have updated your dependencies and configuration file, you need to set up the database for your v2 project.
395
396 This will not take into account entities and data customizations in your v1 project, as you still need to change those. Instead, it will only create the database and tables for your v2 project.
397
398 First, change your database environment variables to the following:
399
400 ```bash
401 DATABASE_URL=postgres://localhost/$DB_NAME
402 DB_NAME=medusa-v2
403 ```
404
405 You can change `medusa-v2` to any database name you prefer.
406
407 Then, run the following commands to create the database and tables:
408
409 ```bash npx2yarn
410 npx medusa db:setup
411 ```
412
413 This command will create the database and tables for your v2 project.
414
415 After that, you can start your Medusa application with the `dev` command. Note that you may have errors if you need to make implementation changes that are covered in the rest of this guide, so it's better to wait until you finish the v2 migration process before starting the Medusa application.
416
417 ### (Optional) 6. Seed with Demo Data
418
419 If you want to seed your Medusa v2 project with demo data, you can copy the content of [this file](https://github.com/medusajs/medusa-starter-default/blob/master/src/scripts/seed.ts) to your `src/scripts/seed.ts` file.
420
421 Then, run the following command to seed the database:
422
423 ```bash npm2yarn
424 npm run seed
425 ```
426
427 This will seed your database with demo data.
428
429 ---
430
431 ## Medusa Admin Changes
432
433 In this section, you'll learn about the changes in the Medusa Admin between v1 and v2.
434
435 <Note>
436
437 This section doesn't cover changes related to Medusa Admin customizations. They're covered later in the [Admin Customization Changes](#admin-customization-changes) section.
438
439 </Note>
440
441 The Medusa Admin is now available out-of-the-box. It's built with [Vite v7](https://vite.dev/) and runs at `http://localhost:9000/app` by default when you start your Medusa application.
442
443 ### Admin Configurations
444
445 You previously configured the admin dashboard when you added it as a plugin in Medusa v1.
446
447 In Medusa v2, you configure the Medusa Admin within the `defineConfig` utility in `medusa-config.ts`. `defineConfig` accepts an `admin` property to configure the Medusa Admin:
448
449 ```ts title="medusa-config.ts"
450 module.exports = defineConfig({
451 // ...
452 admin: {
453 // admin options...
454 },
455 })
456 ```
457
458 You can refer to the [Medusa Configuration](../../configurations/medusa-config/page.mdx#admin-configurations-admin) chapter to learn about all the admin configurations. The following table highlights the main changes between v1 and v2:
459
460 <Table>
461 <Table.Header>
462 <Table.Row>
463 <Table.HeaderCell>
464 Medusa v1
465 </Table.HeaderCell>
466 <Table.HeaderCell>
467 Medusa v2
468 </Table.HeaderCell>
469 </Table.Row>
470 </Table.Header>
471 <Table.Body>
472 <Table.Row>
473 <Table.Cell>
474 `serve`
475 </Table.Cell>
476 <Table.Cell>
477 [admin.disable](../../configurations/medusa-config/page.mdx#disable)
478 </Table.Cell>
479 </Table.Row>
480 <Table.Row>
481 <Table.Cell>
482 `autoRebuild`
483 </Table.Cell>
484 <Table.Cell>
485 No longer supported. The Medusa Admin is always built when you run the `medusa build` command.
486 </Table.Cell>
487 </Table.Row>
488 <Table.Row>
489 <Table.Cell>
490 `backend`
491 </Table.Cell>
492 <Table.Cell>
493 [admin.backendUrl](../../configurations/medusa-config/page.mdx#backendurl)
494 </Table.Cell>
495 </Table.Row>
496 <Table.Row>
497 <Table.Cell>
498 `outDir`
499 </Table.Cell>
500 <Table.Cell>
501 No longer supported. The Medusa Admin is now built in the `.medusa/server/public/admin` directory. Learn more in the [Build](../../build/page.mdx) chapter.
502 </Table.Cell>
503 </Table.Row>
504 <Table.Row>
505 <Table.Cell>
506 `develop` options
507 </Table.Cell>
508 <Table.Cell>
509 No longer supported. The [admin.vite](../../configurations/medusa-config/page.mdx#vite) property may be used to achieve similar results.
510 </Table.Cell>
511 </Table.Row>
512 </Table.Body>
513 </Table>
514
515 ### Admin Webpack Configurations
516
517 In v1, you were able to modify Webpack configurations of the admin dashboard.
518
519 Since Medusa Admin is now built with Vite, you can modify the Vite configurations with the `admin.vite` configuration. Learn more in the [Medusa Configuration](../../configurations/medusa-config/page.mdx#vite) chapter.
520
521 ### Admin CLI Tool
522
523 In Medusa v1, you used the `medusa-admin` CLI tool to build and run the admin dashboard.
524
525 In Medusa v2, the Medusa Admin doesn't have a CLI tool. Instead, running `medusa build` and `medusa develop` also builds and runs the Medusa Admin, respectively.
526
527 In addition, you can build the Medusa Admin separately from the Medusa application using the `--admin-only` option. Learn more in the [Build Medusa Application](../../build/page.mdx#separate-admin-build) chapter.
528
529 ---
530
531 ## Medusa CLI Changes
532
533 The Medusa CLI for v2 is now in the `@medusajs/cli` package. However, you don't need to install it globally. You can just use `npx medusa`, `yarn medusa`, or `pnpm medusa` in your Medusa projects.
534
535 Refer to the [Medusa CLI reference](!resources!/medusa-cli) for the full list of commands and options. The following table highlights the main changes between v1 and v2:
536
537 <Table>
538 <Table.Header>
539 <Table.Row>
540 <Table.HeaderCell>
541 Medusa v1
542 </Table.HeaderCell>
543 <Table.HeaderCell>
544 Medusa v2
545 </Table.HeaderCell>
546 </Table.Row>
547 </Table.Header>
548 <Table.Body>
549 <Table.Row>
550 <Table.Cell>
551 `migrations run`
552 </Table.Cell>
553 <Table.Cell>
554 [db:migrate](!resources!/medusa-cli/commands/db#dbmigrate)
555 </Table.Cell>
556 </Table.Row>
557 <Table.Row>
558 <Table.Cell>
559 `migrations revert`
560 </Table.Cell>
561 <Table.Cell>
562 [db:rollback](!resources!/medusa-cli/commands/db#dbrollback). However, this command reverts migrations of specific modules, not all migrations.
563 </Table.Cell>
564 </Table.Row>
565 <Table.Row>
566 <Table.Cell>
567 `migrations show`
568 </Table.Cell>
569 <Table.Cell>
570 No longer supported.
571 </Table.Cell>
572 </Table.Row>
573 <Table.Row>
574 <Table.Cell>
575 `seed`
576 </Table.Cell>
577 <Table.Cell>
578 No longer supported. However, you can create a [custom CLI script](../../fundamentals/custom-cli-scripts/page.mdx) and [seed data in it](../../fundamentals/custom-cli-scripts/seed-data/page.mdx).
579 </Table.Cell>
580 </Table.Row>
581 <Table.Row>
582 <Table.Cell>
583 `start-cluster`
584 </Table.Cell>
585 <Table.Cell>
586 [start --cluster \<number\>](!resources!/medusa-cli/commands/start)
587 </Table.Cell>
588 </Table.Row>
589 </Table.Body>
590 </Table>
591
592 ---
593
594 ## Plugin Changes
595
596 Medusa v2 supports plugins similar to Medusa v1, but with changes in its usage, development, and configuration.
597
598 In Medusa v1, you created plugins that contained customizations like services that integrated third-party providers, custom API routes, and more.
599
600 In Medusa v2, a plugin can contain customizations like modules that integrate third-party providers, custom API routes, workflows, and more. The plugin development experience has also been improved to resolve big pain points that developers faced in v1.
601
602 Refer to the [Plugins](../../fundamentals/plugins/page.mdx) chapter to learn more about plugins in Medusa v2.
603
604 The rest of this section will cover some of the main changes in plugins between v1 and v2.
605
606 ### Medusa Plugins Alternative
607
608 In v1, Medusa provided a set of plugins that you could use in your project. For example, the Stripe and SendGrid plugins.
609
610 In v2, some of these plugins are now available as module providers out-of-the-box. For example, the Stripe and SendGrid module providers. Other plugins may no longer be available, but you can still find guides to create them.
611
612 The following table highlights the alternatives for the Medusa v1 plugins:
613
614 <Table>
615 <Table.Header>
616 <Table.Row>
617 <Table.HeaderCell>
618 Medusa v1
619 </Table.HeaderCell>
620 <Table.HeaderCell>
621 v2 Alternative
622 </Table.HeaderCell>
623 </Table.Row>
624 </Table.Header>
625 <Table.Body>
626 <Table.Row>
627 <Table.Cell>
628 Algolia
629 </Table.Cell>
630 <Table.Cell>
631 [Guide](!resources!/integrations/guides/algolia)
632 </Table.Cell>
633 </Table.Row>
634 <Table.Row>
635 <Table.Cell>
636 Brightpearl
637 </Table.Cell>
638 <Table.Cell>
639 Not available, but you can follow the [ERP recipe](!resources!/recipes/erp).
640 </Table.Cell>
641 </Table.Row>
642 <Table.Row>
643 <Table.Cell>
644 Contenful
645 </Table.Cell>
646 <Table.Cell>
647 [Guide](!resources!/integrations/guides/contentful)
648 </Table.Cell>
649 </Table.Row>
650 <Table.Row>
651 <Table.Cell>
652 Discount Generator
653 </Table.Cell>
654 <Table.Cell>
655 Not available, but you can build it [as a module](../../fundamentals/modules/page.mdx).
656 </Table.Cell>
657 </Table.Row>
658 <Table.Row>
659 <Table.Cell>
660 IP Lookup
661 </Table.Cell>
662 <Table.Cell>
663 Not available, but you can build it [as a module](../../fundamentals/modules/page.mdx).
664 </Table.Cell>
665 </Table.Row>
666 <Table.Row>
667 <Table.Cell>
668 Klarna
669 </Table.Cell>
670 <Table.Cell>
671 Not available, but you can integrate it as a [Payment Module Provider](!resources!/references/payment/provider).
672 </Table.Cell>
673 </Table.Row>
674 <Table.Row>
675 <Table.Cell>
676 Local File
677 </Table.Cell>
678 <Table.Cell>
679 [Local File Module Provider](!resources!/infrastructure-modules/file/local).
680 </Table.Cell>
681 </Table.Row>
682 <Table.Row>
683 <Table.Cell>
684 Mailchimp
685 </Table.Cell>
686 <Table.Cell>
687 [Guide](!resources!/integrations/guides/mailchimp)
688 </Table.Cell>
689 </Table.Row>
690 <Table.Row>
691 <Table.Cell>
692 MinIO
693 </Table.Cell>
694 <Table.Cell>
695 [S3 (compatible APIs) File Module Provider](!resources!/infrastructure-modules/file/s3)
696 </Table.Cell>
697 </Table.Row>
698 <Table.Row>
699 <Table.Cell>
700 MeiliSearch
701 </Table.Cell>
702 <Table.Cell>
703 Not available, but you can integrate it [in a module](../../fundamentals/modules/page.mdx).
704 </Table.Cell>
705 </Table.Row>
706 <Table.Row>
707 <Table.Cell>
708 PayPal
709 </Table.Cell>
710 <Table.Cell>
711 Not available, but you can integrate it as a [Payment Module Provider](!resources!/references/payment/provider).
712 </Table.Cell>
713 </Table.Row>
714 <Table.Row>
715 <Table.Cell>
716 Restock Notification
717 </Table.Cell>
718 <Table.Cell>
719 [Guide](!resources!/recipes/commerce-automation/restock-notification)
720 </Table.Cell>
721 </Table.Row>
722 <Table.Row>
723 <Table.Cell>
724 S3
725 </Table.Cell>
726 <Table.Cell>
727 [S3 (compatible APIs) File Module Provider](!resources!/infrastructure-modules/file/s3)
728 </Table.Cell>
729 </Table.Row>
730 <Table.Row>
731 <Table.Cell>
732 Segment
733 </Table.Cell>
734 <Table.Cell>
735 [Guide](!resources!/integrations/guides/segment)
736 </Table.Cell>
737 </Table.Row>
738 <Table.Row>
739 <Table.Cell>
740 SendGrid
741 </Table.Cell>
742 <Table.Cell>
743 [SendGrid Module Provider](!resources!/infrastructure-modules/notification/sendgrid)
744 </Table.Cell>
745 </Table.Row>
746 <Table.Row>
747 <Table.Cell>
748 Shopify
749 </Table.Cell>
750 <Table.Cell>
751 Not available, but you can build it [as a module](../../fundamentals/modules/page.mdx).
752 </Table.Cell>
753 </Table.Row>
754 <Table.Row>
755 <Table.Cell>
756 Slack
757 </Table.Cell>
758 <Table.Cell>
759 [Guide](!resources!/integrations/guides/slack)
760 </Table.Cell>
761 </Table.Row>
762 <Table.Row>
763 <Table.Cell>
764 Spaces (DigitalOcean)
765 </Table.Cell>
766 <Table.Cell>
767 [S3 (compatible APIs) File Module Provider](!resources!/infrastructure-modules/file/s3).
768 </Table.Cell>
769 </Table.Row>
770 <Table.Row>
771 <Table.Cell>
772 Strapi
773 </Table.Cell>
774 <Table.Cell>
775 Not available, but you can integrate it [in a module](../../fundamentals/modules/page.mdx).
776 </Table.Cell>
777 </Table.Row>
778 <Table.Row>
779 <Table.Cell>
780 Stripe
781 </Table.Cell>
782 <Table.Cell>
783 [Stripe Payment Module Provider](!resources!/commerce-modules/payment/payment-provider/stripe)
784 </Table.Cell>
785 </Table.Row>
786 <Table.Row>
787 <Table.Cell>
788 Twilio
789 </Table.Cell>
790 <Table.Cell>
791 [Guide](!resources!/how-to-tutorials/tutorials/phone-auth#step-3-integrate-twilio-sms)
792 </Table.Cell>
793 </Table.Row>
794 <Table.Row>
795 <Table.Cell>
796 Wishlist
797 </Table.Cell>
798 <Table.Cell>
799 [Guide](!resources!/plugins/guides/wishlist)
800 </Table.Cell>
801 </Table.Row>
802 </Table.Body>
803 </Table>
804
805 You can also find Medusa and community integrations in the [Integrations](https://medusajs.com/integrations/) page.
806
807 ### Plugin Options
808
809 Similar to Medusa v1, you can pass options to plugins in Medusa v2.
810
811 However, plugin options are now only passed to modules and module providers created in a plugin.
812
813 So, if you previously accessed options in a plugin's subscriber, for example, that's not possible anymore. You need to access the options in a module or module provider instead, then use its service in the plugin's subscriber.
814
815 For example, this is how you can access options in a plugin's subscriber in v2:
816
817 ```ts title="src/subscribers/order-placed.ts"
818 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
819
820 export default async function orderPlacedHandler({
821 event: { data },
822 container,
823 }: SubscriberArgs<{ id: string }>) {
824 const customModuleService = container.resolve("custom")
825
826 const options = customModuleService.getOptions()
827
828 // Use the options in your logic...
829 }
830
831 export const config: SubscriberConfig = {
832 event: `order.placed`,
833 }
834 ```
835
836 Learn more in the [Create Plugin](../../fundamentals/plugins/create/page.mdx) chapter.
837
838 #### enableUI Option
839
840 Plugins in v1 accepted an `enableUI` option to configure whether a plugin's admin customizations should be shown.
841
842 In v2, this option is no longer supported. All admin customizations in a plugin will be shown in the Medusa Admin.
843
844 ---
845
846
847 ## Tool Changes
848
849 This section covers changes to tools that were available in Medusa v1.
850
851 <Table>
852 <Table.Header>
853 <Table.Row>
854 <Table.HeaderCell>
855 Medusa v1
856 </Table.HeaderCell>
857 <Table.HeaderCell>
858 Medusa v2
859 </Table.HeaderCell>
860 </Table.Row>
861 </Table.Header>
862 <Table.Body>
863 <Table.Row>
864 <Table.Cell>
865 JS Client
866 </Table.Cell>
867 <Table.Cell>
868 [JS SDK](!resources!/js-sdk)
869 </Table.Cell>
870 </Table.Row>
871 <Table.Row>
872 <Table.Cell>
873 Medusa React
874 </Table.Cell>
875 <Table.Cell>
876 No longer supported. Instead, you can [use the JS SDK with Tanstack Query](!resources!/js-sdk#use-tanstack-react-query-in-admin-customizations) or similar approaches.
877 </Table.Cell>
878 </Table.Row>
879 <Table.Row>
880 <Table.Cell>
881 Next.js Starter Template
882 </Table.Cell>
883 <Table.Cell>
884 [Next.js Starter Storefront](!resources!/nextjs-starter). The changes may be big to support v2 commerce changes.
885 </Table.Cell>
886 </Table.Row>
887 <Table.Row>
888 <Table.Cell>
889 Medusa Dev CLI
890 </Table.Cell>
891 <Table.Cell>
892 No longer supported.
893 </Table.Cell>
894 </Table.Row>
895 </Table.Body>
896 </Table>
897
898 ---
899
900 ## Changes in Concepts and Development
901
902 In the next sections, you'll learn about the changes in specific concepts and development practices between Medusa v1 and v2.
903
904 ### Entities, Services, and Modules
905
906 In Medusa v1, entities, services, and modules were created separately:
907
908 - You create an entity to add a new table to the database.
909 - You create a service to add new business logic to the Medusa application.
910 - You create a module to add new features to the Medusa application. It may include entities and services.
911
912 In Medusa v2, you create entities (now called data models) and services in a module. You can't create them separately anymore. The data models define new tables to add to the database, and the service provides data-management features for those data models.
913
914 In this section, you'll learn about the most important changes related to these concepts. You can also learn more in the [Modules](../../fundamentals/modules/page.mdx) chapter.
915
916 #### Modules
917
918 A module is a reusable package of functionalities related to a single domain or integration. For example, Medusa provides a Product Module for product-related data models and features.
919
920 So, if in Medusa v1 you had a `Brand` entity and a service to manage it, in v2, you create a Brand Module that defines a `Brand` data model and a service to manage it.
921
922 To learn how to create a module, refer to the [Modules](../../fundamentals/modules/page.mdx) chapter.
923
924 ![Diagram showcasing the directory structure difference between Medusa v1 and v2](https://res.cloudinary.com/dza7lstvk/image/upload/v1748277500/Medusa%20Book/modules-v1-v2_dsnzyl.jpg)
925
926 #### Data Models
927
928 In Medusa v1, you created data models (entities) using TypeORM.
929
930 In Medusa v2, you use Medusa's Data Model Language (DML) to create data models. It simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations.
931
932 For example:
933
934 ```ts title="src/modules/brand/models/brand.ts"
935 import { model } from "@medusajs/framework/utils"
936
937 export const Brand = model.define("brand", {
938 id: model.id().primaryKey(),
939 name: model.text(),
940 })
941 ```
942
943 Learn more about data models in the [Data Models](../../fundamentals/data-models/page.mdx) chapters.
944
945 #### Migrations
946
947 In Medusa v1, you had to write migrations manually to create or update tables in the database. Migrations were based on TypeORM.
948
949 In Medusa v2, you can use the Medusa CLI to generate migrations based on MikroORM. For example:
950
951 ```bash npx2yarn
952 npx medusa db:generate brand
953 ```
954
955 This generates migrations for data models in the Brand Module. Learn more in the [Migrations](../../fundamentals/data-models/write-migration/page.mdx) chapter.
956
957 #### Services
958
959 In Medusa v1, you created a service with business logic related to a feature within your Medusa project. For example, you created a `BrandService` at `src/services/brand.ts` to manage the `Brand` entity.
960
961 In Medusa v2, you can only create a service in a module, and the service either manages the module's data models in the database, or connects to third-party services.
962
963 For example, you create a `BrandService` in the Brand Module at `src/modules/brand/service.ts`:
964
965 ```ts title="src/modules/brand/service.ts"
966 import { MedusaService } from "@medusajs/framework/utils"
967 import { Brand } from "./models/brand"
968
969 class BrandModuleService extends MedusaService({
970 Brand,
971 }) {
972
973 }
974
975 export default BrandModuleService
976 ```
977
978 The service has automatically generated data-management methods by extending `MedusaService` from the Modules SDK. So, you now have methods like `retrieveBrand` and `createBrands` available in the service.
979
980 Learn more in the [Service Factory](../../fundamentals/modules/service-factory/page.mdx) chapter.
981
982 When you register the module in the Medusa application, the service is registered in the [Medusa container](../../fundamentals/medusa-container/page.mdx), allowing you to use its methods in workflows, subscribers, scheduled jobs, and API routes.
983
984 #### Repositories
985
986 In Medusa v1, you used the repository of a data model in a service to provide data-management features. For example, you used the `BrandRepository` to manage the `Brand` entity. Repositories were also based on TypeORM.
987
988 In Medusa v2, you generally don't need repositories for basic data-management features, as they're generated by the service factory. However, for more complex use cases, you can use the data model repository based on MikroORM.
989
990 For example:
991
992 ```ts title="src/modules/brand/service.ts"
993 import { InferTypeOf, DAL } from "@medusajs/framework/types"
994 import Post from "./models/post"
995
996 type Post = InferTypeOf<typeof Post>
997
998 type InjectedDependencies = {
999 postRepository: DAL.RepositoryService<Post>
1000 }
1001
1002 class BlogModuleService {
1003 protected postRepository_: DAL.RepositoryService<Post>
1004
1005 constructor({
1006 postRepository,
1007 }: InjectedDependencies) {
1008 super(...arguments)
1009 this.postRepository_ = postRepository
1010 }
1011 }
1012
1013 export default BlogModuleService
1014 ```
1015
1016 Learn more in the [Database Operations](../../fundamentals/modules/db-operations/page.mdx) chapter.
1017
1018 #### Module Isolation
1019
1020 In Medusa v1, you had access to all entities and services in the Medusa application. While this approach was flexible, it introduced complexities, was difficult to maintain, and resulted in hacky workarounds.
1021
1022 In Medusa v2, modules are isolated. This means that you can only access entities and services within the module. This isolation allows you to integrate modules into your application without side effects, while still providing you with the necessary flexibility to build your use cases.
1023
1024 The [Module Isolation](../../fundamentals/modules/isolation/page.mdx) chapter explains this concept in detail. The rest of this section gives a general overview of how module isolation affects your Medusa v1 customizations.
1025
1026 #### Extending Entities
1027
1028 In Medusa v1, you were able to extend entities by creating a new entity that extended the original one. For example, you could create a custom `Product` entity that extended the original `Product` entity to add a `brand` column.
1029
1030 In Medusa v2, you can no longer extend entities. Instead, you need to create a new data model that contains the columns you want to add. Then, you can create a [Module Link](../../fundamentals/module-links/page.mdx) that links your data model to the one you want to extend.
1031
1032 For example, you create a Brand Module that has a `Brand` data model. Then, you create a Module Link that links the `Brand` data model to the `Product` data model in the Product Module:
1033
1034 ```ts title="src/links/product-brand.ts"
1035 import BrandModule from "../modules/brand"
1036 import ProductModule from "@medusajs/medusa/product"
1037 import { defineLink } from "@medusajs/framework/utils"
1038
1039 export default defineLink(
1040 {
1041 linkable: ProductModule.linkable.product,
1042 isList: true,
1043 },
1044 BrandModule.linkable.brand
1045 )
1046 ```
1047
1048 You can then associate brands with a product, retrieve them in API routes and custom functionalities, and more.
1049
1050 Learn more in the [Module Links](../../fundamentals/module-links/page.mdx) chapter.
1051
1052 #### Extending Services
1053
1054 In Medusa v1, you were able to extend services by creating a new service that extended the original one. For example, you could create a custom `ProductService` that extended the original `ProductService` to add a new method.
1055
1056 In Medusa v2, you can no longer extend services. Instead, you need to [create a module](../../fundamentals/modules/page.mdx) with a service that contains the methods you want to add. Then, you can:
1057
1058 - Build [workflows](../../fundamentals/workflows/page.mdx) that use both services to achieve a custom feature.
1059 - Consume [Workflow Hooks](../../fundamentals/workflows/workflow-hooks/page.mdx) to run custom actions in existing workflows.
1060 - For more complex use cases, you can re-create an existing workflow and use your custom module's service in it.
1061
1062 For example, if you extended the `CartService` in v1 to add items with custom prices to the cart, you can instead build a custom workflow that uses your custom module to retrieve an item's price, then add it to the cart using the existing `addToCartWorkflow`:
1063
1064 ```ts
1065 import {
1066 createWorkflow,
1067 transform,
1068 WorkflowResponse,
1069 } from "@medusajs/framework/workflows-sdk"
1070 import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
1071 import {
1072 getCustomPriceStep,
1073 } from "./steps/get-custom-price"
1074
1075 type AddCustomToCartWorkflowInput = {
1076 cart_id: string
1077 item: {
1078 variant_id: string
1079 quantity: number
1080 metadata?: Record<string, unknown>
1081 }
1082 }
1083
1084 export const addCustomToCartWorkflow = createWorkflow(
1085 "add-custom-to-cart",
1086 ({ cart_id, item }: AddCustomToCartWorkflowInput) => {
1087 // assuming this step uses a custom module to get the price
1088 const price = getCustomPriceStep({
1089 variant: item.variant_id,
1090 currencyCode: "usd",
1091 quantity: item.quantity,
1092 })
1093
1094 const itemToAdd = transform({
1095 item,
1096 price,
1097 }, (data) => {
1098 return [{
1099 ...data.item,
1100 unit_price: data.price,
1101 }]
1102 })
1103
1104 addToCartWorkflow.runAsStep({
1105 input: {
1106 items: itemToAdd,
1107 cart_id,
1108 },
1109 })
1110 }
1111 )
1112 ```
1113
1114 Refer to the [Workflows](../../fundamentals/workflows/page.mdx) chapters to learn more about workflows in Medusa v2.
1115
1116 #### Integrating Third-Party Services
1117
1118 In Medusa v1, you integrated third-party services by creating a service under `src/services` and using it in your customizations.
1119
1120 In Medusa v2, you can integrate third-party services by creating a module with a service that contains the methods to interact with the third-party service. You can then use the module's service in a [workflow](../../fundamentals/workflows/page.mdx) to build custom features.
1121
1122 ![Directory structure change between v1 and v2](https://res.cloudinary.com/dza7lstvk/image/upload/v1748278103/Medusa%20Book/integrations-v1-v2_cjzkus.jpg)
1123
1124 ---
1125
1126 ### Medusa and Module Containers
1127
1128 In Medusa v1, you accessed dependencies from the container in all your customizations, such as services, API routes, and subscribers.
1129
1130 In Medusa v2, there are two containers:
1131
1132 <Table>
1133 <Table.Header>
1134 <Table.Row>
1135 <Table.HeaderCell>
1136 Container
1137 </Table.HeaderCell>
1138 <Table.HeaderCell>
1139 Description
1140 </Table.HeaderCell>
1141 <Table.HeaderCell>
1142 Accessed By
1143 </Table.HeaderCell>
1144 </Table.Row>
1145 </Table.Header>
1146 <Table.Body>
1147 <Table.Row>
1148 <Table.Cell>
1149 [Medusa container](../../fundamentals/medusa-container/page.mdx)
1150 </Table.Cell>
1151 <Table.Cell>
1152 Main container that contains Framework and commerce resources, such as services of registered modules.
1153 </Table.Cell>
1154 <Table.Cell>
1155 - Workflows
1156 - API routes
1157 - Subscribers
1158 - Scheduled jobs
1159 - Custom CLI scripts
1160 </Table.Cell>
1161 </Table.Row>
1162 <Table.Row>
1163 <Table.Cell>
1164 [Module container](../../fundamentals/modules/container/page.mdx)
1165 </Table.Cell>
1166 <Table.Cell>
1167 Container of a module. It contains some resources from the Framework, and resources implemented in the module.
1168 </Table.Cell>
1169 <Table.Cell>
1170 Services and loaders in the module.
1171 </Table.Cell>
1172 </Table.Row>
1173 </Table.Body>
1174 </Table>
1175
1176 You can view the list of resources in each container in the [Container Resources](!resources!/medusa-container-resources) reference.
1177
1178 ---
1179
1180 ### Workflow Changes
1181
1182 In Medusa v2, workflows are the main way to implement custom features spanning across modules and systems.
1183
1184 Workflows have been optimized for data reliability, flexibility, and orchestration across systems. You can learn more in the [Workflows](../../fundamentals/workflows/page.mdx) chapters.
1185
1186 This section highlights the main changes in workflows between v1 and v2.
1187
1188 #### Workflows SDK Imports
1189
1190 In Medusa v1, you imported all Workflows SDK functions and types from the `@medusajs/workflows-sdk` package.
1191
1192 In Medusa v2, you import them from the `@medusajs/framework/workflows-sdk` package. For example:
1193
1194 ```ts title="src/workflows/hello-world.ts"
1195 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1196 ```
1197
1198 #### Workflow Return Value
1199
1200 In Medusa v1, you returned any value from a workflow, such as a string or an object.
1201
1202 In Medusa v2, you must return an instance of `WorkflowResponse` from a workflow. The data passed to `WorkflowResponse`'s constructor is returned to the caller of the workflow.
1203
1204 For example:
1205
1206 ```ts title="src/workflows/hello-world.ts"
1207 import {
1208 createWorkflow,
1209 WorkflowResponse,
1210 } from "@medusajs/framework/workflows-sdk"
1211
1212 export const helloWorldWorkflow = createWorkflow(
1213 "hello-world",
1214 () => {
1215 return new WorkflowResponse("Hello, world!")
1216 }
1217 )
1218
1219 // in API route, for example:
1220 import type {
1221 MedusaRequest,
1222 MedusaResponse,
1223 } from "@medusajs/framework/http"
1224
1225 export const GET = (
1226 req: MedusaRequest,
1227 res: MedusaResponse
1228 ) => {
1229 // message is "Hello, world!"
1230 const { result: message } = await helloWorldWorkflow(req.scope)
1231 .run()
1232
1233 res.json({
1234 message,
1235 })
1236 }
1237 ```
1238
1239 #### New Workflow Features
1240
1241 - [Use when-then in workflows to run steps if a condition is satisfied](../../fundamentals/workflows/conditions/page.mdx).
1242 - [Consume hooks to run custom steps in existing workflows](../../fundamentals/workflows/workflow-hooks/page.mdx).
1243 - [Create long-running workflows that run asynchronously in the background](../../fundamentals/workflows/long-running-workflow/page.mdx).
1244
1245 ---
1246
1247 ### API Route Changes
1248
1249 API routes are generally similar in Medusa v1 and v2, but with minor changes.
1250
1251 You can learn more about creating API routes in the [API Routes](../../fundamentals/api-routes/page.mdx) chapters. This section highlights the main changes in API routes between v1 and v2.
1252
1253 #### HTTP Imports
1254
1255 In Medusa v1, you imported API-route related types and functions from the `@medusajs/medusa` package.
1256
1257 In Medusa v2, you import them from the `@medusajs/framework/http` package. For example:
1258
1259 ```ts title="src/api/store/custom/route.ts"
1260 import type {
1261 MedusaRequest,
1262 MedusaResponse,
1263 } from "@medusajs/framework/http"
1264 ```
1265
1266 #### Protected API Routes
1267
1268 In Medusa v1, routes starting with `/store/me` and `/admin` were protected by default.
1269
1270 In Medusa v2, routes starting with `/store/customers/me` are accessible by registered customers, and `/admin` routes are accessible by admin users.
1271
1272 In an API route, you can access the logged in user or customer using the `auth_context.actor_id` property of `AuthenticatedMedusaRequest`. For example:
1273
1274 ```ts title="src/api/store/custom/route.ts"
1275 import type {
1276 AuthenticatedMedusaRequest,
1277 MedusaResponse,
1278 } from "@medusajs/framework/http"
1279
1280 export const GET = async (
1281 req: AuthenticatedMedusaRequest,
1282 res: MedusaResponse
1283 ) => {
1284 const id = req.auth_context?.actor_id
1285
1286 // ...
1287 }
1288 ```
1289
1290 Learn more in the [Protected API Routes](../../fundamentals/api-routes/protected-routes/page.mdx) chapter.
1291
1292 #### Authentication Middlewares
1293
1294 In Medusa v1, you had three middlewares to protect API routes:
1295
1296 - `authenticate` to protect API routes for admin users.
1297 - `authenticateCustomer` to optionally authenticate customers.
1298 - `requireCustomerAuthentication` to require customer authentication.
1299
1300 In Medusa v2, you can use a single `authenticate` middleware for the three use cases. For example:
1301
1302 ```ts title="src/api/middlewares.ts"
1303 import {
1304 defineMiddlewares,
1305 authenticate,
1306 } from "@medusajs/framework/http"
1307
1308 export default defineMiddlewares({
1309 routes: [
1310 {
1311 matcher: "/custom/admin*",
1312 middlewares: [authenticate("user", ["session", "bearer", "api-key"])],
1313 },
1314 {
1315 matcher: "/custom/customer*",
1316 // equivalent to requireCustomerAuthentication
1317 middlewares: [authenticate("customer", ["session", "bearer"])],
1318 },
1319 {
1320 matcher: "/custom/all-customers*",
1321 // equivalent to authenticateCustomer
1322 middlewares: [authenticate("customer", ["session", "bearer"], {
1323 allowUnauthenticated: true,
1324 })],
1325 },
1326 ],
1327 })
1328 ```
1329
1330 Learn more in the [Protected API Routes](../../fundamentals/api-routes/protected-routes/page.mdx) chapter.
1331
1332 #### Middlewares
1333
1334 In Medusa v1, you created middlewares by exporting an object in the `src/api/middlewares.ts` file.
1335
1336 In Medusa v2, you create middlewares by exporting an object created with `defineMiddlewares`, which accepts an object with the same properties as in v1. For example:
1337
1338 ```ts title="src/api/middlewares.ts"
1339 import {
1340 defineMiddlewares,
1341 MedusaNextFunction,
1342 MedusaRequest,
1343 MedusaResponse,
1344 } from "@medusajs/framework/http"
1345
1346 export default defineMiddlewares({
1347 routes: [
1348 {
1349 matcher: "/custom*",
1350 middlewares: [
1351 (
1352 req: MedusaRequest,
1353 res: MedusaResponse,
1354 next: MedusaNextFunction
1355 ) => {
1356 console.log("Received a request!")
1357
1358 next()
1359 },
1360 ],
1361 },
1362 ],
1363 })
1364 ```
1365
1366 Learn more in the [Middlewares](../../fundamentals/api-routes/middlewares/page.mdx) chapter.
1367
1368 #### Disable Body Parser
1369
1370 In Medusa v1, you disabled the body parser in API routes by setting `bodyParser: false` in the route's middleware configuration.
1371
1372 In Medusa v2, `bodyParser: false` still disables the body parser the same way. If you only need access to the raw request body instead of disabling parsing entirely, set `bodyParser.preserveRawBody` to `true` in the route's middleware configuration instead. For example:
1373
1374 ```ts title="src/api/middlewares.ts"
1375 import { defineMiddlewares } from "@medusajs/framework/http"
1376
1377 export default defineMiddlewares({
1378 routes: [
1379 {
1380 method: ["POST"],
1381 bodyParser: { preserveRawBody: true },
1382 matcher: "/custom",
1383 },
1384 ],
1385 })
1386 ```
1387
1388 Learn more in the [Body Parser](../../fundamentals/api-routes/parse-body/page.mdx) chapter.
1389
1390 #### Extending Validators
1391
1392 In Medusa v1, you passed custom request parameters to Medusa's API routes by extending a request's validator.
1393
1394 In Medusa v2, some Medusa API routes support passing additional data in the request body. You can then configure the validation of that additional data and consume them in the hooks of the workflow used in the API route.
1395
1396 For example:
1397
1398 ```ts title="src/api/middlewares.ts"
1399 import { defineMiddlewares } from "@medusajs/framework/http"
1400 import { z } from "@medusajs/framework/zod"
1401
1402 export default defineMiddlewares({
1403 routes: [
1404 {
1405 method: "POST",
1406 matcher: "/admin/products",
1407 additionalDataValidator: {
1408 brand: z.string().optional(),
1409 },
1410 },
1411 ],
1412 })
1413 ```
1414
1415 In this example, you allow passing a `brand` property as additional data to the `/admin/products` API route.
1416
1417 You can learn more in the [Additional Data](../../fundamentals/api-routes/additional-data/page.mdx) chapter.
1418
1419 If a route doesn't support passing additional data, you need to [replicate it](../../fundamentals/api-routes/override/page.mdx) to support your custom use case.
1420
1421 ---
1422
1423 ### Events and Subscribers Changes
1424
1425 Events and subscribers are similar in Medusa v1 and v2, but with minor changes.
1426
1427 You can learn more in the [Events and Subscribers](../../fundamentals/events-and-subscribers/page.mdx) chapters. This section highlights the main changes in events and subscribers between v1 and v2.
1428
1429 #### Emitted Events
1430
1431 Medusa v2 doesn't emit the same events as v1. Refer to the [Events Reference](!resources!/references/events) for the full list of events emitted in v2.
1432
1433 #### Subscriber Type Imports
1434
1435 In Medusa v1, you imported subscriber types from the `@medusajs/medusa` package.
1436
1437 In Medusa v2, you import them from the `@medusajs/framework` package. For example:
1438
1439 ```ts title="src/subscribers/order-placed.ts"
1440 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1441 ```
1442
1443 #### Subscriber Parameter Change
1444
1445 In Medusa v1, a subscriber function received an object parameter that has `eventName` and `data` properties.
1446
1447 In Medusa v2, the subscriber function receives an object parameter that has an `event` property. The `event` property contains the event name and data. For example:
1448
1449 ```ts title="src/subscribers/order-placed.ts"
1450 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1451
1452 export default async function orderPlacedHandler({
1453 event: { data },
1454 container,
1455 }: SubscriberArgs<{ id: string }>) {
1456 // ...
1457 }
1458
1459 export const config: SubscriberConfig = {
1460 event: `order.placed`,
1461 }
1462 ```
1463
1464 Also, the `pluginOptions` property is no longer passed in the subscriber's parameter. Instead, you can access the options passed to a plugin within its modules' services, which you can resolve in a subscriber.
1465
1466 Learn more in the [Events and Subscribers](../../fundamentals/events-and-subscribers/page.mdx) chapter.
1467
1468 #### Subscriber Implementation Change
1469
1470 In Medusa v1, you implemented functionalities, such as sending confirmation email, directly within a subscriber.
1471
1472 In Medusa v2, you should implement these functionalities in a [workflow](../../fundamentals/workflows/page.mdx) and call the workflow in the subscriber. By using workflows, you benefit from rollback mechanism, among other features.
1473
1474 For example:
1475
1476 ```ts title="src/subscribers/order-placed.ts"
1477 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1478 import {
1479 sendOrderConfirmationWorkflow,
1480 } from "../workflows/send-order-confirmation"
1481
1482 export default async function orderPlacedHandler({
1483 event: { data },
1484 container,
1485 }: SubscriberArgs<{ id: string }>) {
1486 await sendOrderConfirmationWorkflow(container)
1487 .run({
1488 input: {
1489 id: data.id,
1490 },
1491 })
1492 }
1493
1494 export const config: SubscriberConfig = {
1495 event: `order.placed`,
1496 }
1497 ```
1498
1499 #### Emitting Events
1500
1501 In Medusa v1, you emitted events in services and API routes by resolving the Event Module's service from the container.
1502
1503 In Medusa v2, you should emit events in workflows instead. For example:
1504
1505 ```ts title="src/workflows/hello-world.ts"
1506 import {
1507 createWorkflow,
1508 } from "@medusajs/framework/workflows-sdk"
1509 import {
1510 emitEventStep,
1511 } from "@medusajs/medusa/core-flows"
1512
1513 const helloWorldWorkflow = createWorkflow(
1514 "hello-world",
1515 () => {
1516 // ...
1517
1518 emitEventStep({
1519 eventName: "custom.created",
1520 data: {
1521 id: "123",
1522 // other data payload
1523 },
1524 })
1525 }
1526 )
1527 ```
1528
1529 If you need to emit events in a service, you can add the Event Module as a dependency of your module. Then, you can resolve the Event Module's service from the module container and emit the event. This approach is only recommended for events related to under-the-hood processes.
1530
1531 Learn more in the [Emit Events](../../fundamentals/events-and-subscribers/emit-event/page.mdx) chapter.
1532
1533 ---
1534
1535 ### Loader Changes
1536
1537 In Medusa v1, you created loaders in the `src/loaders` directory to perform tasks at application startup.
1538
1539 In Medusa v2, loaders can only be created in a module. You can create loaders in the `src/modules/<module-name>/loaders` directory. That also means the loader can only access resources in the module's container.
1540
1541 Learn more in the [Loaders](../../fundamentals/modules/loaders/page.mdx) chapter.
1542
1543 #### Loader Parameter Changes
1544
1545 In Medusa v1, a loader function receives two parameters: `container` and `config`. If the loader was created in a module, it also received a `logger` parameter.
1546
1547 In Medusa v2, a loader function receives a single object parameter that has a `container` and `options` properties. The `options` property contains the properties passed to the module.
1548
1549 For example:
1550
1551 ```ts title="src/modules/hello/loaders/hello-world.ts"
1552 import {
1553 LoaderOptions,
1554 } from "@medusajs/framework/types"
1555 import {
1556 ContainerRegistrationKeys,
1557 } from "@medusajs/framework/utils"
1558
1559 export default async function helloWorldLoader({
1560 container,
1561 options,
1562 }: LoaderOptions) {
1563 const logger = container.resolve(
1564 ContainerRegistrationKeys.LOGGER
1565 )
1566
1567 logger.info("[HELLO MODULE] Just started the Medusa application!")
1568 }
1569 ```
1570
1571 ---
1572
1573 ### Scheduled Job Changes
1574
1575 Scheduled jobs are similar in Medusa v1 and v2, but with minor changes.
1576
1577 You can learn more about scheduled jobs in the [Scheduled Jobs](../../fundamentals/scheduled-jobs/page.mdx) chapters. This section highlights the main changes in scheduled jobs between v1 and v2.
1578
1579 #### Scheduled Job Parameter Changes
1580
1581 In Medusa v1, a scheduled job function received an object of parameters.
1582
1583 In Medusa v2, a scheduled job function receives only the Medusa container as a parameter. For example:
1584
1585 ```ts title="src/jobs/hello-world.ts"
1586 import { MedusaContainer } from "@medusajs/framework/types"
1587 import {
1588 ContainerRegistrationKeys,
1589 } from "@medusajs/framework/utils"
1590
1591 export default async function greetingJob(container: MedusaContainer) {
1592 const logger = container.resolve(
1593 ContainerRegistrationKeys.LOGGER
1594 )
1595
1596 logger.info("Greeting!")
1597 }
1598
1599 export const config = {
1600 name: "greeting-every-minute",
1601 schedule: "* * * * *",
1602 }
1603 ```
1604
1605 The `pluginOptions` property is no longer available, as you can access the options passed to a plugin within its modules' services, which you can resolve in a scheduled job.
1606
1607 The `data` property is also no longer available, as you can't pass data in the scheduled job's configuration anymore.
1608
1609 #### Scheduled Job Configuration Changes
1610
1611 In Medusa v2, the `data` property is removed from the scheduled job's configuration object.
1612
1613 #### Scheduled Job Implementation Changes
1614
1615 In Medusa v1, you implemented functionalities directly in the job function.
1616
1617 In Medusa v2, you should implement these functionalities in a [workflow](../../fundamentals/workflows/page.mdx) and call the workflow in the scheduled job. By using workflows, you benefit from rollback mechanism, among other features.
1618
1619 For example:
1620
1621 ```ts title="src/jobs/sync-products.ts"
1622 import { MedusaContainer } from "@medusajs/framework/types"
1623 import { syncProductToErpWorkflow } from "../workflows/sync-products-to-erp"
1624
1625 export default async function syncProductsJob(container: MedusaContainer) {
1626 await syncProductToErpWorkflow(container)
1627 .run()
1628 }
1629
1630 export const config = {
1631 name: "sync-products-job",
1632 schedule: "0 0 * * *",
1633 }
1634 ```
1635
1636 ---
1637
1638 ### Removed Concepts and Alternatives
1639
1640 The following table highlights concepts that have been removed or changed in Medusa v2 and their alternatives:
1641
1642 <Table>
1643 <Table.Header>
1644 <Table.Row>
1645 <Table.HeaderCell>
1646 Medusa v1
1647 </Table.HeaderCell>
1648 <Table.HeaderCell>
1649 Medusa v2
1650 </Table.HeaderCell>
1651 </Table.Row>
1652 </Table.Header>
1653 <Table.Body>
1654 <Table.Row>
1655 <Table.Cell>
1656 Batch Jobs and Strategies
1657 </Table.Cell>
1658 <Table.Cell>
1659 [Long-Running Workflows](../../fundamentals/workflows/long-running-workflow/page.mdx)
1660 </Table.Cell>
1661 </Table.Row>
1662 <Table.Row>
1663 <Table.Cell>
1664 File Service
1665 </Table.Cell>
1666 <Table.Cell>
1667 [File Module Provider](!resources!/infrastructure-modules/file)
1668 </Table.Cell>
1669 </Table.Row>
1670 <Table.Row>
1671 <Table.Cell>
1672 Notification Provider Service
1673 </Table.Cell>
1674 <Table.Cell>
1675 [Notification Module Provider](!resources!/infrastructure-modules/notification)
1676 </Table.Cell>
1677 </Table.Row>
1678 <Table.Row>
1679 <Table.Cell>
1680 Search Service
1681 </Table.Cell>
1682 <Table.Cell>
1683 Can be integrated as a [module](../../fundamentals/modules/page.mdx).
1684 </Table.Cell>
1685 </Table.Row>
1686 </Table.Body>
1687 </Table>
1688
1689 ---
1690
1691 ### Admin Customization Changes
1692
1693 This section covers changes to the admin customizations between Medusa v1 and v2.
1694
1695 #### Custom Admin Environment Variables
1696
1697 In Medusa v1, you set custom environment variables to be passed to the admin dashboard by prefixing them with `MEDUSA_ADMIN_`.
1698
1699 In Medusa v2, you can set custom environment variables to be passed to the admin dashboard by prefixing them with `VITE_`. Learn more in the [Admin Environment Variables](../../fundamentals/admin/environment-variables/page.mdx) chapter.
1700
1701 #### Admin Widgets
1702
1703 Due to design changes in the Medusa Admin, some widget injection zones may have been changed or removed. Refer to the [Admin Widgets Injection Zones](!resources!/admin-widget-injection-zones) reference for the full list of injection zones in v2.
1704
1705 Also, In Medusa v1, you exported in the widget's file a `config` object with the widget's configurations, such as its injection zone.
1706
1707 In Medusa v2, you export a configuration object defined with `defineWidgetConfig` from the Admin Extension SDK. For example:
1708
1709 ```tsx title="src/admin/widgets/product-widget.tsx" highlights={[["9"], ["10"], ["11"]]}
1710 import { defineWidgetConfig } from "@medusajs/admin-sdk"
1711
1712 // The widget
1713 const ProductWidget = () => {
1714 // ...
1715 }
1716
1717 // The widget's configurations
1718 export const config = defineWidgetConfig({
1719 zone: "product.details",
1720 })
1721
1722 export default ProductWidget
1723 ```
1724
1725 The function accepts an object with a `zone` property, indicating the zone to inject the widget.
1726
1727 Refer to the [Admin Widgets](../../fundamentals/admin/widgets/page.mdx) chapter to learn more about creating widgets in Medusa v2.
1728
1729 ### Admin UI Routes
1730
1731 In Medusa v1, UI Routes were prefixed by `/a`. For example, a route created at `src/admin/routes/custom/page.tsx` would be available at `http://localhost:9000/a/custom`.
1732
1733 In Medusa v2, the `/a` prefix has been removed. So, that same route would be available at `http://localhost:9000/app/custom` (where `/app` is the path to the admin dashboard, not a prefix).
1734
1735 Also, in v1, you exported a `config` object with the route's configurations to show the route in the dashboard's sidebar.
1736
1737 In v2, you export a configuration object defined with `defineRouteConfig` from the Admin Extension SDK. For example:
1738
1739 ```tsx title="src/admin/routes/custom/page.tsx" highlights={[["8"], ["9"], ["10"], ["11"]]}
1740 import { defineRouteConfig } from "@medusajs/admin-sdk"
1741 import { ChatBubbleLeftRight } from "@medusajs/icons"
1742
1743 const CustomPage = () => {
1744 // ...
1745 }
1746
1747 export const config = defineRouteConfig({
1748 label: "Custom Route",
1749 icon: ChatBubbleLeftRight,
1750 })
1751
1752 export default CustomPage
1753 ```
1754
1755 The `defineRouteConfig` function accepts an object with the following properties:
1756
1757 - `label`: The label of the route to show in the sidebar.
1758 - `icon`: The icon to use in the sidebar for the route.
1759
1760 Refer to the [Admin UI Routes](../../fundamentals/admin/ui-routes/page.mdx) chapter to learn more about creating UI routes in Medusa v2.
1761
1762 ### Admin Setting Routes
1763
1764 In Medusa v1, you created setting pages under the `src/admin/settings` directory with their own configurations.
1765
1766 In Medusa v2, setting pages are UI routes created under the `src/admin/routes/settings` directory.
1767
1768 For example, if you had a `src/admin/settings/custom/page.tsx` file in v1, you should move it to `src/admin/routes/settings/custom/page.tsx` in v2. The file's content will be the same as a UI route.
1769
1770 For example:
1771
1772 ```tsx title="src/admin/routes/settings/custom/page.tsx" highlights={[["14"], ["15"], ["16"]]}
1773 import { defineRouteConfig } from "@medusajs/admin-sdk"
1774 import { Container, Heading } from "@medusajs/ui"
1775
1776 const CustomSettingPage = () => {
1777 return (
1778 <Container className="divide-y p-0">
1779 <div className="flex items-center justify-between px-6 py-4">
1780 <Heading level="h1">Custom Setting Page</Heading>
1781 </div>
1782 </Container>
1783 )
1784 }
1785
1786 export const config = defineRouteConfig({
1787 label: "Custom",
1788 })
1789
1790 export default CustomSettingPage
1791 ```
1792
1793 In v1, you exported a `config` object that showed a setting page as a card in the settings page. In v2, you export the same configuration object as a UI route.
1794
1795 Learn more about creating setting pages in the [Admin UI Routes](../../fundamentals/admin/ui-routes/page.mdx#create-settings-page) chapter.
1796
1797 ### notify Props in Widgets, UI Routes, and Settings
1798
1799 In Medusa v1, admin widgets, UI routes, and setting pages received a `notify` prop to show notifications in the admin dashboard.
1800
1801 This prop is no longer passed in v2. Instead, use the [toast utility from Medusa UI](!ui!/components/toast) to show notifications.
1802
1803 For example:
1804
1805 ```tsx title="src/admin/widgets/product-details.tsx" highlights={[["7"], ["8"], ["9"]]}
1806 import { toast } from "@medusajs/ui"
1807 import { defineWidgetConfig } from "@medusajs/admin-sdk"
1808
1809 // The widget
1810 const ProductWidget = () => {
1811 const handleOnClick = () => {
1812 toast.info("Info", {
1813 description: "The quick brown fox jumps over the lazy dog.",
1814 })
1815 }
1816 // ...
1817 }
1818
1819 // The widget's configurations
1820 export const config = defineWidgetConfig({
1821 zone: "product.details",
1822 })
1823
1824 export default ProductWidget
1825 ```
1826
1827 Learn more about the `toast` utility in the [Medusa UI Toasts](!ui!/components/toast) documentation.
1828
1829 ### Sending Requests to Medusa Server
1830
1831 In Medusa v1, you used Medusa React to send requests to the Medusa server.
1832
1833 Medusa v2 no longer supports Medusa React. Instead, you can use the JS SDK with Tanstack Query to send requests from your admin customizations to the Medusa server.
1834
1835 Learn more in the [Admin Development Tips](../../fundamentals/admin/tips/page.mdx#send-requests-to-api-routes) chapter.
1836
1837 ### Admin Languages
1838
1839 Medusa Admin v2 supports different languages out-of-the-box, and you can contribute with new translations.
1840
1841 Refer to the [User Guide](!user-guide!/tips/languages) for the list of languages supported in the Medusa Admin.
1842
1843 ---
1844
1845 ## Commerce Features Changes
1846
1847 In Medusa v2, commerce features are implemented as [Commerce Modules](!resources!/commerce-modules). For example, the [Product Module](!resources!/commerce-modules/product) implements the product-related features, whereas the [Cart Module](!resources!/commerce-modules/cart) implements the cart-related features.
1848
1849 So, it's difficult to cover all changes in commerce features between v1 and v2. Instead, this section will highlight changes to customizations that were documented in the Medusa v1 documentation.
1850
1851 To learn about all commerce features in Medusa v2, refer to the [Commerce Modules](!resources!/commerce-modules) documentation.
1852
1853 ### Providers are now Module Providers
1854
1855 In Medusa v1, you created providers for payment, fulfillment, and tax in services under `src/services`.
1856
1857 In Medusa v2, you create these providers as module providers that belong to the Payment, Fulfillment, and Tax modules respectively.
1858
1859 Refer to the following guides to learn how to create these module providers:
1860
1861 - [Payment Module Provider](!resources!/commerce-modules/payment/payment-provider)
1862 - [Fulfillment Module Provider](!resources!/commerce-modules/fulfillment/fulfillment-provider)
1863 - [Tax Module Provider](!resources!/commerce-modules/tax/tax-provider)
1864
1865 ### Overridden Cart Completion
1866
1867 In Medusa v1, you were able to override the cart completion strategy to customize the cart completion process.
1868
1869 In Medusa v2, the cart completion process is now implemented in the [completeCartWorkflow](!resources!/references/medusa-workflows/completeCartWorkflow). There are two ways you can customize the completion process:
1870
1871 - [Consuming hooks](../../fundamentals/workflows/workflow-hooks/page.mdx) like the [validate](!resources!/references/medusa-workflows/completeCartWorkflow#validate) hook. This is useful if you only want to make changes in key points of the cart completion process.
1872 - You can view available hooks in the [completeCartWorkflow reference](!resources!/references/medusa-workflows/completeCartWorkflow#hooks)
1873 - For more complex use cases, you can create a new workflow with the desired functionality. Then, you can [replicate the complete cart API route](../../fundamentals/api-routes/override/page.mdx) and use it in your storefront.
1874
1875 ### Overridden Tax Calculation
1876
1877 In Medusa v1, you were able to override the tax calculation strategy to customize the tax calculation process.
1878
1879 In Medusa v2, the tax calculation process is now implemented in a [Tax Module Provider](!resources!/commerce-modules/tax/tax-provider). So, you can [create a custom tax provider](!resources!/references/tax/provider) with the calculation logic you want, then [use it in a tax region](!user-guide!/settings/tax-regions#edit-tax-region).
1880
1881 ### Overridden Price Selection
1882
1883 In Medusa v1, you were able to override the price selection strategy to customize the price selection process.
1884
1885 In Medusa v2, the price selection process is now implemented in the [Pricing Module's calculate method](!resources!/commerce-modules/pricing/price-calculation). The Pricing Module allows you to set [flexible rules and tiers](!resources!/commerce-modules/pricing/price-rules) to support your use case.
1886
1887 If your use case is complex and these rules are not enough, you can create a new [module](../../fundamentals/modules/page.mdx) with the necessary logic, then use that module in your custom workflows.
1888
1889 ## Prices are Stored in Major Units
1890
1891 In Medusa v1, prices were stored in the smallest currency unit. For example, a price of $10.00 was stored as `1000` (cents).
1892
1893 In Medusa v2, prices are stored in the major unit. For example, a price of $10.00 is stored as `10` (dollars).
1894
1895 Learn more in the [Pricing Concepts](!resources!/commerce-modules/pricing/concepts) guide.
1896
1897 ### Gift Card Features
1898
1899 Medusa v1 has gift card features out-of-the-box.
1900
1901 In Medusa v2, gift card features are now only available to [Cloud](https://medusajs.com/cloud/) users.
1902
1903 ---
1904
1905 ## Deployment Changes
1906
1907 The deployment process in Medusa v2 is similar to v1, but with some changes. For example, the Medusa server is now deployed with Medusa Admin.
1908
1909 Medusa also provides [Cloud](https://medusajs.com/cloud/), a managed services offering that makes deploying and operating Medusa applications possible without having to worry about configuring, scaling, and maintaining infrastructure.
1910
1911 Refer to the [Deployment](!resources!/deployment) documentation to learn about the deployment process for Medusa applications and Next.js Starter Storefront.