1 import { CardList, SplitSections, SplitSection, CodeTabs, CodeTab, SplitList } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Framework Overview`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn about the Medusa Framework and how it facilitates building customizations in your Medusa application.
10
11 ## What is the Medusa Framework?
12
13 All commerce application require some degree of customization. So, it's important to choose a platform that facilitates building those customizations.
14
15 When you build customizations with other ecommerce platforms, they require you to pull data through HTTP APIs, run custom logic that span across systems in a separate application, and manually ensure data consistency across systems. This adds significant overhead and slows down development as you spend time managing complex distributed systems.
16
17 The Medusa Framework eliminates this overhead by providing powerful low-level APIs and tools that let you build any type of customization directly within your Medusa project. You can build custom features, orchestrate operations and query data seamlessly across systems, extend core functionality, and automate tasks in your Medusa application.
18
19 With the Medusa Framework, you can focus your efforts on building meaningful business customizations and continuously delivering new features.
20
21 Using the Medusa Framework, you can build customizations like:
22
23 - [Product Reviews](!resources!/how-to-tutorials/tutorials/product-reviews)
24 - [Deep integration with an ERP system](!resources!/recipes/erp)
25 - [CMS integration with seamless content retrieval](!resources!/integrations/guides/sanity)
26 - [Custom item pricing in the cart](!resources!/examples/guides/custom-item-price)
27 - [Automated restock notifications](!resources!/recipes/commerce-automation/restock-notification)
28 - [Re-usable payment provider integrations](!resources!/references/payment/provider)
29
30 ### Framework Concepts and Tools
31
32 <SplitList
33 items={[
34 {
35 title: "Medusa Container",
36 link: "/learn/fundamentals/medusa-container",
37 },
38 {
39 title: "Modules",
40 link: "/learn/fundamentals/modules",
41 },
42 {
43 title: "Module Links",
44 link: "/learn/fundamentals/module-links",
45 },
46 {
47 title: "Query",
48 link: "/learn/fundamentals/query",
49 },
50 {
51 title: "Data Models",
52 link: "/learn/fundamentals/data-models",
53 },
54 {
55 title: "Workflows",
56 link: "/learn/fundamentals/workflows",
57 },
58 {
59 title: "API Routes",
60 link: "/learn/fundamentals/api-routes",
61 },
62 {
63 title: "Events and Subscribers",
64 link: "/learn/fundamentals/events-and-subscribers",
65 },
66 {
67 title: "Scheduled Jobs",
68 link: "/learn/fundamentals/scheduled-jobs",
69 },
70 {
71 title: "Plugins",
72 link: "/learn/fundamentals/plugins",
73 }
74 ]}
75 listsNum={2}
76 />
77
78 ---
79
80 ## Build Custom Features
81
82 The Medusa Framework allows you to build custom features tailored to your business needs.
83
84 To create a custom feature, you can create a [module](../modules/page.mdx) that contains your feature's data models and the logic to manage them. A module is integrated into your Medusa application without side effects.
85
86 <CodeTabs group="module-customizations">
87 <CodeTab label="Data Model" value="data-model">
88
89 export const modelHighlights = [
90 ["3", "Post", "Create a data model with Medusa's Data Model Language (DML)."]
91 ]
92
93 ```ts highlights={modelHighlights}
94 import { model } from "@medusajs/framework/utils"
95
96 export const Post = model.define("post", {
97 id: model.id().primaryKey(),
98 title: model.text(),
99 })
100 ```
101
102 </CodeTab>
103
104 <CodeTab label="Service" value="service">
105
106 export const serviceHighlights = [
107 ["4", "MedusaService", "Save time by extending the `MedusaService` for basic CRUD operations."]
108 ]
109
110 ```ts highlights={serviceHighlights}
111 import { MedusaService } from "@medusajs/framework/utils"
112 import { Post } from "./post"
113
114 export class BlogModuleService extends MedusaService({
115 Post,
116 }){
117 // CRUD methods generated by MedusaService
118 }
119 ```
120
121 </CodeTab>
122
123 <CodeTab label="Module Definition" value="module">
124
125 ```ts
126 import { Module } from "@medusajs/framework/utils"
127 import { BlogModuleService } from "./service"
128
129 export const BLOG_MODULE = "blog"
130
131 export default Module(BLOG_MODULE, {
132 service: BlogModuleService,
133 })
134 ```
135
136 </CodeTab>
137
138 </CodeTabs>
139
140 Then, you can build commerce features and flows in [workflows](../workflows/page.mdx) that use your module. By using workflows, you benefit from features like [rollback mechanism](../workflows/compensation-function/page.mdx) and [retry configuration](../workflows/retry-failed-steps/page.mdx).
141
142 <CodeTabs group="workflow-customizations">
143 <CodeTab label="Step" value="step">
144
145 export const stepHighlights = [
146 ["19", "", "Define the rollback logic for any step."]
147 ]
148
149 ```ts highlights={stepHighlights}
150 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
151 import { BlogModuleService, BLOG_MODULE } from "../../modules/blog"
152
153 type Input = {
154 title: string
155 }
156
157 export const createPostStep = createStep(
158 "create-post",
159 async (input: Input, { container }) => {
160 const blogModuleService: BlogModuleService = container.resolve(
161 BLOG_MODULE
162 )
163
164 const post = await blogModuleService.createPosts(input.title)
165
166 return new StepResponse(post, post.id)
167 },
168 async (postId, { container }) => {
169 if (!postId) {
170 return
171 }
172
173 const blogModuleService: BlogModuleService = container.resolve(
174 BLOG_MODULE
175 )
176
177 await blogModuleService.deletePosts(postId)
178 }
179 )
180 ```
181
182 </CodeTab>
183 <CodeTab label="Workflow" value="workflow">
184
185 ```ts
186 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
187 import { createPostStep } from "./steps"
188
189 type Input = {
190 title: string
191 }
192
193 export const createPostWorkflow = createWorkflow(
194 "create-post",
195 (input: Input) => {
196 const post = createPostStep(input)
197
198 return new WorkflowResponse(post)
199 }
200 )
201 ```
202
203 </CodeTab>
204 </CodeTabs>
205
206 Finally, you can expose your custom feature with [API routes](../api-routes/page.mdx) that are built on top of your module and workflows.
207
208 ```ts title="API Route Example"
209 import type {
210 MedusaRequest,
211 MedusaResponse,
212 } from "@medusajs/framework/http"
213 import { createPostWorkflow } from "../../../workflows/create-post"
214
215 type PostRequestBody = {
216 title: string
217 }
218
219 export const POST = async (
220 req: MedusaRequest<PostRequestBody>,
221 res: MedusaResponse
222 ) => {
223 const { result } = await createPostWorkflow(req.scope)
224 .run({
225 input: result.validatedBody,
226 })
227
228 return res.json(result)
229 }
230 ```
231
232 ### Examples
233
234 The following tutorials are step-by-step guides that show you how to build custom features using the Medusa Framework.
235
236 <CardList
237 items={[
238 {
239 title: "Product Reviews",
240 text: "Build a product reviews feature in your Medusa application.",
241 href: "!resources!/how-to-tutorials/tutorials/product-reviews",
242 },
243 {
244 title: "Wishlist",
245 text: "Build a wishlist feature in your Medusa application.",
246 href: "!resources!/plugins/guides/wishlist",
247 }
248 ]}
249 />
250
251 ### Start Learning
252
253 To learn more about the different concepts useful for building custom features, check out the following chapters:
254
255 <CardList
256 items={[
257 {
258 title: "Modules",
259 href: "/learn/fundamentals/modules",
260 },
261 {
262 title: "Workflows",
263 href: "/learn/fundamentals/workflows",
264 },
265 {
266 title: "API Routes",
267 href: "/learn/fundamentals/api-routes",
268 }
269 ]}
270 />
271
272 ---
273
274 ## Extend Existing Features
275
276 The Medusa Framework is flexible and extensible, allowing you to extend and build on top of existing models and features.
277
278 To associate new properties and relations with an existing model, you can create a [module](../modules/page.mdx) with data models that define these additions. Then, you can define a [module link](../module-links/page.mdx) that associates two data models from separate modules.
279
280 <CodeTabs group="module-extensions">
281 <CodeTab label="Module Link" value="module-link">
282
283 export const defineLinkHighlights = [
284 ["5", "defineLink", "Define a link between products and brands."]
285 ]
286
287 ```ts highlights={defineLinkHighlights}
288 import BrandModule from "../modules/brand"
289 import ProductModule from "@medusajs/medusa/product"
290 import { defineLink } from "@medusajs/framework/utils"
291
292 export default defineLink(
293 {
294 linkable: ProductModule.linkable.product,
295 isList: true,
296 },
297 BrandModule.linkable.brand
298 )
299 ```
300
301 </CodeTab>
302
303 <CodeTab label="Data Model" value="data-model">
304
305 ```ts
306 import { model } from "@medusajs/framework/utils"
307
308 export const Brand = model.define("brand", {
309 id: model.id().primaryKey(),
310 name: model.text(),
311 })
312 ```
313
314 </CodeTab>
315
316 <CodeTab label="Service" value="service">
317
318 ```ts
319 import { MedusaService } from "@medusajs/framework/utils"
320 import { Brand } from "./models/brand"
321
322 class BrandModuleService extends MedusaService({
323 Brand,
324 }) {
325
326 }
327
328 export default BrandModuleService
329 ```
330
331 </CodeTab>
332
333 <CodeTab label="Module Definition" value="module">
334
335 ```ts
336 import { Module } from "@medusajs/framework/utils"
337 import BrandModuleService from "./service"
338
339 export const BRAND_MODULE = "brand"
340
341 export default Module(BRAND_MODULE, {
342 service: BrandModuleService,
343 })
344 ```
345
346 </CodeTab>
347 </CodeTabs>
348
349 Then, you can [hook into existing workflows](../workflows/workflow-hooks/page.mdx) to perform custom actions as part of existing features and flows. For example, you can create a brand when a product is created.
350
351 export const hookHighlights = [
352 ["8", "productsCreated", "Perform a custom action within the product creation flow."],
353 ["9", "additional_data", "Custom data passed in the HTTP request body."]
354 ]
355
356 ```ts title="Workflow Hook Example" highlights={hookHighlights}
357 import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
358 import { StepResponse } from "@medusajs/framework/workflows-sdk"
359 import { Modules } from "@medusajs/framework/utils"
360 import { LinkDefinition } from "@medusajs/framework/types"
361 import { BRAND_MODULE } from "../../modules/brand"
362 import BrandModuleService from "../../modules/brand/service"
363
364 createProductsWorkflow.hooks.productsCreated(
365 (async ({ products, additional_data }, { container }) => {
366 if (!additional_data?.brand_id) {
367 return new StepResponse([], [])
368 }
369
370 const brandModuleService: BrandModuleService = container.resolve(
371 BRAND_MODULE
372 )
373
374 const brand = await brandModuleService.createBrands({
375 name: additional_data.brand_name,
376 })
377 })
378 )
379 ```
380
381 You can also build custom workflows using your custom module and Medusa's modules, and use [existing workflows and steps](!resources!/medusa-workflows-reference) within your custom workflows.
382
383 ### Examples
384
385 The following tutorials are step-by-step guides that show you how to extend existing features using the Medusa Framework.
386
387 <CardList
388 items={[
389 {
390 title: "Custom Item Pricing",
391 text: "Add products with custom items to the cart.",
392 href: "!resources!/examples/guides/custom-item-price",
393 },
394 {
395 title: "Loyalty Points System",
396 text: "Reward and allow customers to redeem loyalty points.",
397 href: "!resources!/how-to-tutorials/tutorials/loyalty-points",
398 }
399 ]}
400 />
401
402 ### Start Learning
403
404 To learn more about the different concepts useful for extending features, check out the following chapters:
405
406 <CardList
407 items={[
408 {
409 title: "Modules",
410 href: "/learn/fundamentals/modules",
411 },
412 {
413 title: "Module Links",
414 href: "/learn/fundamentals/module-links",
415 },
416 {
417 title: "Workflow Hooks",
418 href: "/learn/fundamentals/workflows/workflow-hooks",
419 }
420 ]}
421 />
422
423 ---
424
425 ## Integrate Third-Party Services
426
427 The Medusa Framework provides the tools and infrastructure to build a middleware solution for your commerce ecosystem. You can integrate third-party services, perform operations across systems, and query data from multiple sources.
428
429 ### Orchestrate Operations Across Systems
430
431 The Medusa Framework solves one of the biggest hurdles for ecommerce platforms: orchestrating operations across systems. Medusa has a built-in durable execution engine to help complete tasks that span multiple systems.
432
433 You can integrate a third-party service in a [module](../modules/page.mdx). This module provides an interface to perform operations with the third-party service.
434
435 <CodeTabs group="third-party-integration">
436 <CodeTab label="Service" value="service">
437
438 export const erpServiceHighlights = [
439 ["5", "ErpModuleService", "Create a service that connects to the ERP system."],
440 ]
441
442 ```ts highlights={erpServiceHighlights}
443 type Options = {
444 apiKey: string
445 }
446
447 export default class ErpModuleService {
448 private options: Options
449 private client
450
451 constructor({}, options: Options) {
452 this.options = options
453 // TODO initialize client that connects to ERP
454 }
455
456 async getProducts() {
457 // assuming client has a method to fetch products
458 return this.client.getProducts()
459 }
460
461 // TODO add more methods
462 }
463 ```
464
465 </CodeTab>
466
467 <CodeTab label="Module Definition" value="module">
468
469 ```ts
470 import { Module } from "@medusajs/framework/utils"
471 import ErpModuleService from "./service"
472
473 export const ERP_MODULE = "erp"
474
475 export default Module(ERP_MODULE, {
476 service: ErpModuleService,
477 })
478 ```
479
480 </CodeTab>
481 </CodeTabs>
482
483 Then, you can build [workflows](../workflows/page.mdx) that perform operations across systems. In the workflow, you can use your module to interact with the integrated third-party service.
484
485 For example, you can create a workflow that syncs products from your ERP system to your Medusa application.
486
487 <CodeTabs group="erp-sync-workflow">
488
489 <CodeTab label="Workflow" value="workflow">
490
491 export const erpWorkflowHighlights = [
492 ["11", "getProductsFromErpStep", "Get products from the ERP system."],
493 ["13", "transform", "Prepare the products to be created in Medusa."],
494 ["32", "createProductsWorkflow", "Create the ERP products in Medusa."],
495 ]
496
497 ```ts highlights={erpWorkflowHighlights}
498 import {
499 createWorkflow,
500 WorkflowResponse,
501 transform,
502 } from "@medusajs/framework/workflows-sdk"
503 import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
504
505 export const syncFromErpWorkflow = createWorkflow(
506 "sync-from-erp",
507 () => {
508 const erpProducts = getProductsFromErpStep()
509
510 const productsToCreate = transform({
511 erpProducts,
512 }, (data) => {
513 // TODO prepare ERP products to be created in Medusa
514 return data.erpProducts.map((erpProduct) => {
515 return {
516 title: erpProduct.title,
517 external_id: erpProduct.id,
518 variants: erpProduct.variants.map((variant) => ({
519 title: variant.title,
520 metadata: {
521 external_id: variant.id,
522 },
523 })),
524 // other data...
525 }
526 })
527 })
528
529 createProductsWorkflow.runAsStep({
530 input: {
531 products: productsToCreate,
532 },
533 })
534
535 return new WorkflowResponse({
536 erpProducts,
537 })
538 }
539 )
540 ```
541
542 </CodeTab>
543 <CodeTab label="Step" value="step">
544
545 ```ts
546 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
547 import { ERP_MODULE } from "../../modules/erp"
548 import { ErpModuleService } from "../../modules/erp/service"
549
550 const getProductsFromErpStep = createStep(
551 "get-products-from-erp",
552 async (_, { container }) => {
553 const erpModuleService: ErpModuleService = container.resolve(
554 ERP_MODULE
555 )
556
557 const products = await erpModuleService.getProducts()
558
559 return new StepResponse(products)
560 }
561 )
562 ```
563
564 </CodeTab>
565 </CodeTabs>
566
567 By using a workflow to manage operations across systems, you benefit from features like [rollback mechanism](../workflows/compensation-function/page.mdx), [background long-running execution](../workflows/long-running-workflow/page.mdx), [retry configuration](../workflows/retry-failed-steps/page.mdx), and more. This is essential for building a middleware solution that performs operations across systems, as you don't have to worry about data inconsistencies or failures.
568
569 You can then execute this workflow at a specific interval using [scheduled jobs](../scheduled-jobs/page.mdx) or when an event occurs using [events and subscribers](../events-and-subscribers/page.mdx). You can also expose its features to client applications using an [API route](../api-routes/page.mdx).
570
571 <CodeTabs group="erp-sync-api">
572 <CodeTab label="Scheduled Job" value="scheduled-job">
573
574 export const syncProductsJobHighlights = [
575 ["6", "syncProductsJob", "Sync products once a day."],
576 ]
577
578 ```ts highlights={syncProductsJobHighlights}
579 import {
580 MedusaContainer,
581 } from "@medusajs/framework/types"
582 import { syncFromErpWorkflow } from "../workflows/sync-from-erp"
583
584 export default async function syncProductsJob(container: MedusaContainer) {
585 await syncFromErpWorkflow(container).run({})
586 }
587
588 export const config = {
589 name: "daily-product-sync",
590 schedule: "0 0 * * *", // Every day at midnight
591 }
592 ```
593
594 </CodeTab>
595
596 <CodeTab label="Event Subscriber" value="event-subscriber">
597
598 export const productsCreatedHandlerHighlights = [
599 ["4", "productsCreatedHandler", "Sync products when they are created."],
600 ]
601
602 ```ts highlights={productsCreatedHandlerHighlights}
603 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
604 import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
605
606 export default async function productsCreatedHandler({
607 event: { data },
608 container,
609 }: SubscriberArgs<{ id: string }[]>) {
610 await syncFromErpWorkflow(container).run({})
611 }
612
613 export const config: SubscriberConfig = {
614 event: `product.created`,
615 }
616 ```
617
618 </CodeTab>
619
620 <CodeTab label="API Route" value="api-route">
621
622 export const apiRouteHighlights = [
623 ["7", "POST", "Expose a REST API route to sync products."],
624 ]
625
626 ```ts highlights={apiRouteHighlights}
627 import type {
628 MedusaRequest,
629 MedusaResponse,
630 } from "@medusajs/framework/http"
631 import { syncFromErpWorkflow } from "../../../workflows/sync-from-erp"
632
633 export const POST = async (
634 req: MedusaRequest,
635 res: MedusaResponse
636 ) => {
637 const { result } = await syncFromErpWorkflow(req.scope).run({})
638
639 return res.status(200).json(result)
640 }
641 ```
642
643 </CodeTab>
644 </CodeTabs>
645
646 #### Examples
647
648 The following tutorials are step-by-step guides that show you how to orchestrate operations across third-party services using the Medusa Framework.
649
650 <CardList
651 items={[
652 {
653 title: "Migrate Data from Magento",
654 text: "Migrate data from Magento to your Medusa application.",
655 href: "!resources!/integrations/guides/magento",
656 },
657 {
658 title: "Integrate Third-Party Services",
659 text: "Integrate CMS, Fulfillment, Payment, and other third-party services.",
660 href: "!resources!/integrations",
661 }
662 ]}
663 className="mb-2"
664 />
665
666 #### Start Learning
667
668 To learn more about the different concepts useful for integrating third-party services, check out the following chapters:
669
670 <CardList
671 items={[
672 {
673 title: "Modules",
674 href: "/learn/fundamentals/modules",
675 },
676 {
677 title: "Workflows",
678 href: "/learn/fundamentals/workflows",
679 },
680 {
681 title: "API Routes",
682 href: "/learn/fundamentals/api-routes",
683 },
684 {
685 title: "Events and Subscribers",
686 href: "/learn/fundamentals/events-and-subscribers",
687 },
688 {
689 title: "Scheduled Jobs",
690 href: "/learn/fundamentals/scheduled-jobs",
691 }
692 ]}
693 className="mb-2"
694 />
695
696 ### Query Data Across Systems
697
698 Another essential feature for integrating third-party services is querying data across those systems efficiently.
699
700 The Framework allows you to build links not only between Medusa data models, but also virtual data models using [read-only module links](../module-links/read-only/page.mdx). You can build a [module](../modules/page.mdx) that provides the logic to query data from a third-party service, then create a read-only link between an existing data model and a virtual one from the third-party service.
701
702 <CodeTabs group="erp-query">
703 <CodeTab label="Read-Only Link" value="read-only-link">
704
705 export const readOnlyLinkHighlights = [
706 ["5", "defineLink", "Define a read-only link between products and brands from a third-party service."],
707 ]
708
709 ```ts highlights={readOnlyLinkHighlights}
710 import BrandModule from "../modules/brand"
711 import ProductModule from "@medusajs/medusa/product"
712 import { defineLink } from "@medusajs/framework/utils"
713
714 export default defineLink(
715 {
716 linkable: ProductModule.linkable.product,
717 field: "id",
718 },
719 {
720 ...BrandModule.linkable.brand.id,
721 primaryKey: "product_id",
722 },
723 {
724 readOnly: true,
725 }
726 )
727 ```
728
729 </CodeTab>
730
731 <CodeTab label="Module Service" value="module-service">
732
733 export const brandModuleService = [
734 ["12", "list", "Provide a method in the service to retrieve\nthe data from the third-party service."],
735 ]
736
737 ```ts highlights={brandModuleService}
738 type BrandModuleOptions = {
739 apiKey: string
740 }
741
742 export default class BrandModuleService {
743 private client
744
745 constructor({}, options: BrandModuleOptions) {
746 this.client = new Client(options)
747 }
748
749 async list(
750 filter: {
751 id: string | string[]
752 }
753 ) {
754 return this.client.getBrands(filter)
755 /**
756 * Example of returned data:
757 *
758 * [
759 * {
760 * "id": "brand_123",
761 * "name": "Brand 123",
762 * "product_id": "prod_321"
763 * },
764 * {
765 * "id": "post_456",
766 * "name": "Brand 456",
767 * "product_id": "prod_654"
768 * }
769 * ]
770 */
771 }
772 }
773 ```
774
775 </CodeTab>
776
777 <CodeTab label="Module Definition" value="module">
778
779 ```ts
780 import { Module } from "@medusajs/framework/utils"
781 import BrandModuleService from "./service"
782
783 export const BRAND_MODULE = "brand"
784
785 export default Module(BRAND_MODULE, {
786 service: BrandModuleService,
787 })
788 ```
789
790 </CodeTab>
791 </CodeTabs>
792
793 Then, you can use [Query](../query/page.mdx) to retrieve a product and its brand from the third-party service in a single query.
794
795 export const queryHighlights = [
796 ["1", "graph", "Query a product and its brand from the\nthird-party service in a single query."],
797 ]
798
799 ```ts title="Query Example" highlights={queryHighlights}
800 const { result } = await query.graph({
801 entity: "product",
802 fields: ["id", "brand.*"],
803 filters: {
804 id: "prod_123",
805 },
806 })
807
808 // result = [{
809 // id: "prod_123",
810 // brand: {
811 // id: "brand_123",
812 // name: "Brand 123",
813 // product_id: "prod_123"
814 // }
815 // ...
816 // }]
817 ```
818
819 Query simplifies the process of retrieving data across systems, as you can retrieve data from multiple sources in a single query.
820
821 #### Examples
822
823 The following tutorials are step-by-step guides that show you how to query data across systems using the Medusa Framework.
824
825 <CardList
826 items={[
827 {
828 title: "Integrate Sanity CMS",
829 text: "Query data from third-party services using read-only links.",
830 href: "!resources!/integrations/guides/sanity",
831 }
832 ]}
833 className="mb-2"
834 />
835
836 #### Start Learning
837
838 To learn more about the different concepts useful for querying data across systems, check out the following chapters:
839
840 <CardList
841 items={[
842 {
843 title: "Modules",
844 href: "/learn/fundamentals/modules",
845 },
846 {
847 title: "Read-Only Links",
848 href: "/learn/fundamentals/module-links/read-only",
849 },
850 {
851 title: "Query",
852 href: "/learn/fundamentals/query",
853 }
854 ]}
855 className="mb-2"
856 />
857
858 ---
859
860 ## Automate Tasks
861
862 The Medusa Framework provides the tools to automate tasks in your Medusa application. Automation is useful when you want to perform a task periodically, such as syncing data, or when an event occurs, such as sending a confirmation email when an order is placed.
863
864 To build the task to be automated, you first create a [workflow](../workflows/page.mdx) that contains the task's logic, such as syncing data or sending an email.
865
866 <CodeTabs group="automate-tasks">
867 <CodeTab label="Step" value="step">
868
869 ```ts
870 import { Modules } from "@medusajs/framework/utils"
871 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
872 import { CreateNotificationDTO } from "@medusajs/framework/types"
873
874 export const sendNotificationStep = createStep(
875 "send-notification",
876 async (data: CreateNotificationDTO[], { container }) => {
877 const notificationModuleService = container.resolve(
878 Modules.NOTIFICATION
879 )
880 const notification = await notificationModuleService.createNotifications(
881 data
882 )
883 return new StepResponse(notification)
884 }
885 )
886 ```
887
888 </CodeTab>
889 <CodeTab label="Workflow" value="workflow">
890
891 ```ts
892 import {
893 createWorkflow,
894 WorkflowResponse,
895 } from "@medusajs/framework/workflows-sdk"
896 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
897 import { sendNotificationStep } from "./steps/send-notification"
898
899 type WorkflowInput = {
900 id: string
901 }
902
903 export const sendOrderConfirmationWorkflow = createWorkflow(
904 "send-order-confirmation",
905 ({ id }: WorkflowInput) => {
906 const { data: orders } = useQueryGraphStep({
907 entity: "order",
908 fields: [
909 "id",
910 "email",
911 "currency_code",
912 "total",
913 "items.*",
914 ],
915 filters: {
916 id,
917 },
918 })
919
920 const notification = sendNotificationStep([{
921 to: orders[0].email,
922 channel: "email",
923 template: "order-placed",
924 data: {
925 order: orders[0],
926 },
927 }])
928
929 return new WorkflowResponse(notification)
930 }
931 )
932 ```
933 </CodeTab>
934 </CodeTabs>
935
936 Then, you can execute this workflow when an event occurs using a [subscriber](../events-and-subscribers/page.mdx), or at a specific interval using a [scheduled job](../scheduled-jobs/page.mdx).
937
938 <CodeTabs group="automate-tasks-examples">
939 <CodeTab label="Event Subscriber" value="event-subscriber">
940
941 export const orderPlacedHandlerHighlights = [
942 ["7", "orderPlacedHandler", "Send an order confirmation email when an order is placed."],
943 ]
944
945 ```ts highlights={orderPlacedHandlerHighlights}
946 import type {
947 SubscriberArgs,
948 SubscriberConfig,
949 } from "@medusajs/framework"
950 import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
951
952 export default async function orderPlacedHandler({
953 event: { data },
954 container,
955 }: SubscriberArgs<{ id: string }>) {
956 await sendOrderConfirmationWorkflow(container)
957 .run({
958 input: {
959 id: data.id,
960 },
961 })
962 }
963
964 export const config: SubscriberConfig = {
965 event: "order.placed",
966 }
967 ```
968
969 </CodeTab>
970
971 <CodeTab label="Scheduled Job" value="scheduled-job">
972
973 export const orderConfirmationJobHighlights = [
974 ["6", "orderConfirmationJob", "Send an order confirmation email once a day."],
975 ]
976
977 ```ts highlights={orderConfirmationJobHighlights}
978 import type {
979 MedusaContainer,
980 } from "@medusajs/framework/types"
981 import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
982
983 export default async function orderConfirmationJob(
984 container: MedusaContainer
985 ) {
986 await sendOrderConfirmationWorkflow(container).run({
987 input: {
988 id: "order_123",
989 },
990 })
991 }
992 export const config = {
993 name: "order-confirmation-job",
994 schedule: "0 0 * * *", // Every day at midnight
995 }
996 ```
997
998 </CodeTab>
999 </CodeTabs>
1000
1001 ### Examples
1002
1003 The following guides are step-by-step guides that show you how to automate tasks using the Medusa Framework.
1004
1005 <CardList
1006 items={[
1007 {
1008 title: "Restock Notifications",
1009 text: "Send restock notifications to customers when a product is back in stock.",
1010 href: "!resources!/recipes/commerce-automation/restock-notification",
1011 },
1012 {
1013 title: "Sync Data from and to ERP",
1014 text: "Sync data between your Medusa application and an ERP system.",
1015 href: "!resources!/recipes/erp#sync-products-from-erp",
1016 }
1017 ]}
1018 />
1019
1020 ### Start Learning
1021
1022 To learn more about the different concepts useful for automating tasks, check out the following chapters:
1023
1024 <CardList
1025 items={[
1026 {
1027 title: "Workflows",
1028 href: "/learn/fundamentals/workflows",
1029 },
1030 {
1031 title: "Events and Subscribers",
1032 href: "/learn/fundamentals/events-and-subscribers",
1033 },
1034 {
1035 title: "Scheduled Jobs",
1036 href: "/learn/fundamentals/scheduled-jobs",
1037 }
1038 ]}
1039 />
1040
1041 ---
1042
1043 ## Re-Use Customizations Across Applications
1044
1045 If you have custom features that you want to re-use across multiple Medusa applications, or you want to publish your customizations for the community to use, you can build a [plugin](../plugins/page.mdx).
1046
1047 A plugin encapsulates your customizations in a single package. The customizations include [modules](../modules/page.mdx), [workflows](../workflows/page.mdx), [API routes](../api-routes/page.mdx), and more.
1048
1049 ![Diagram showcasing a wishlist plugin installed in a Medusa application](https://res.cloudinary.com/dza7lstvk/image/upload/v1737540762/Medusa%20Book/plugin-diagram_oepiis.jpg)
1050
1051 You can then publish that plugin to NPM and install it in any Medusa application. This allows you to re-use your customizations efficiently across multiple projects, or share them with the community.
1052
1053 ### Examples
1054
1055 The following tutorials are step-by-step guides that show you how to build plugins using the Medusa Framework.
1056
1057 <CardList
1058 items={[
1059 {
1060 title: "Wishlist Plugin",
1061 text: "Build a wishlist plugin for your Medusa application.",
1062 href: "!resources!/plugins/guides/wishlist",
1063 },
1064 {
1065 title: "Migrate Data from Magento Plugin",
1066 text: "Build a plugin that migrates data from Magento to your Medusa application.",
1067 href: "!resources!/integrations/guides/magento",
1068 }
1069 ]}
1070 />
1071
1072 ### Start Learning
1073
1074 To learn more about the different concepts useful for building plugins, check out the following chapters:
1075
1076 <CardList
1077 items={[
1078 {
1079 title: "Plugins",
1080 href: "/learn/fundamentals/plugins",
1081 },
1082 ]}
1083 itemsPerRow={1}
1084 />