Raw
1 ---
2 sidebar_label: "Integrate Strapi"
3 tags:
4 - server
5 - tutorial
6 - product
7 products:
8 - product
9 ---
10
11 import { Card, Prerequisites, Details, WorkflowDiagram, H3 } from "docs-ui"
12 import { Github } from "@medusajs/icons"
13
14 export const metadata = {
15 title: `Integrate Strapi (CMS) with Medusa`,
16 }
17
18 # {metadata.title}
19
20 In this tutorial, you'll learn how to integrate [Strapi](https://strapi.io/) with Medusa.
21
22 <Note>
23
24 This guide has been revisited to support [Medusa v2.16.0](https://github.com/medusajs/medusa/releases/tag/v2.16.0) which introduced global product options.
25
26 </Note>
27
28 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa also facilitates integrating third-party services that enrich your application with features specific to your unique business use case.
29
30 By integrating Strapi, you can manage your products' content with powerful content management capabilities, including custom fields, media, localization, and more.
31
32 <Note>
33
34 This guide was built with Strapi v5.30.1. If you're using a different version and you run into issues, consider [opening an issue](https://github.com/medusajs/medusa/issues/new?template=docs.yml).
35
36 </Note>
37
38 ## Summary
39
40 By following this tutorial, you'll learn how to:
41
42 - Install and set up Medusa.
43 - Install and set up Strapi.
44 - Integrate Strapi with Medusa to interact with Strapi's API.
45 - Implement two-way synchronization of product data between Medusa and Strapi:
46 - Handle product events to sync data from Medusa to Strapi.
47 - Handle Strapi webhooks to sync data from Strapi to Medusa.
48 - Display product data from Strapi in the Next.js Starter Storefront.
49
50 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer, but you're expected to have knowledge in Strapi, as its concepts are not explained in the tutorial.
51
52 ![Diagram illustrating the flow of data between Medusa, Strapi, admin, and customer (storefront)](https://res.cloudinary.com/dza7lstvk/image/upload/v1763375209/Medusa%20Resources/strapi-summary_pioikw.jpg)
53
54 <Card
55 title="Full Code"
56 text="Find the full code of the guide in this repository."
57 href="https://github.com/medusajs/examples/tree/main/strapi-integration"
58 icon={Github}
59 />
60
61
62 ---
63
64 ## Step 1: Install a Medusa Application
65
66 <Prerequisites items={[
67 {
68 text: "Node.js v20.19.0+ or v22.12.0+ (Versions supported by Strapi)",
69 link: "https://nodejs.org/en/download"
70 },
71 {
72 text: "Git CLI tool",
73 link: "https://git-scm.com/downloads"
74 },
75 {
76 text: "PostgreSQL",
77 link: "https://www.postgresql.org/download/"
78 }
79 ]} />
80
81 Start by installing the Medusa application on your machine with the following command:
82
83 ```bash
84 npx create-medusa-app@latest
85 ```
86
87 First, you'll be asked for the project's name. Then, when prompted about installing the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
88
89 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
90
91 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
92
93 <Note title="Ran into Errors?">
94
95 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
96
97 </Note>
98
99 <Note>
100
101 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
102
103 </Note>
104
105 ---
106
107 ## Step 2: Set Up Strapi
108
109 In this step, you'll install and set up Strapi to manage your product content.
110
111 ### a. Install Strapi
112
113 In a separate directory from your Medusa application, run the following command to create a new Strapi project:
114
115 ```bash
116 npx create-strapi@latest my-strapi-app
117 ```
118
119 You can pick the default options during the installation process. Once the installation is complete, navigate to the newly created directory:
120
121 ```bash
122 cd my-strapi-app
123 ```
124
125 ### b. Setup Strapi
126
127 Next, you'll start Strapi and create a new admin user.
128
129 Run the following command to start Strapi:
130
131 ```bash badgeLabel="Strapi" badgeColor="orange"
132 npm run dev
133 ```
134
135 This command starts Strapi in development mode and opens the admin panel setup page in your default browser.
136
137 On this page, you can create a new admin user to log in to the Strapi admin panel. You'll return to the admin panel later to manage settings and content.
138
139 ### c. Define Product Content Type
140
141 In this section, you'll define a content type for products in Strapi. These products will be synced from Medusa, allowing you to manage their content using Strapi's CMS features.
142
143 You'll use `schema.json` files to define content types.
144
145 #### Product schema.json
146
147 To create the schema for the Product content type, create the file `src/api/product/content-types/product/schema.json` with the following content:
148
149 ```json title="src/api/product/content-types/product/schema.json" badgeLabel="Strapi" badgeColor="orange"
150 {
151 "kind": "collectionType",
152 "collectionName": "products",
153 "info": {
154 "singularName": "product",
155 "pluralName": "products",
156 "displayName": "Product",
157 "description": "Products from Medusa"
158 },
159 "options": {
160 "draftAndPublish": false
161 },
162 "pluginOptions": {},
163 "attributes": {
164 "medusaId": {
165 "type": "string",
166 "required": true,
167 "unique": true
168 },
169 "title": {
170 "type": "string",
171 "required": true
172 },
173 "subtitle": {
174 "type": "string"
175 },
176 "description": {
177 "type": "richtext"
178 },
179 "handle": {
180 "type": "uid",
181 "targetField": "title"
182 },
183 "images": {
184 "type": "media",
185 "multiple": true,
186 "required": false,
187 "allowedTypes": ["images"]
188 },
189 "thumbnail": {
190 "type": "media",
191 "multiple": false,
192 "required": false,
193 "allowedTypes": ["images"]
194 },
195 "locale": {
196 "type": "string",
197 "default": "en"
198 },
199 "variants": {
200 "type": "relation",
201 "relation": "oneToMany",
202 "target": "api::product-variant.product-variant",
203 "mappedBy": "product"
204 },
205 "options": {
206 "type": "relation",
207 "relation": "manyToMany",
208 "target": "api::product-option.product-option",
209 "inversedBy": "product"
210 }
211 }
212 }
213 ```
214
215 You define the following fields for the Product content type:
216
217 1. `medusaId`: A unique identifier that maps to the Medusa product ID.
218 2. `title`: The product's title.
219 3. `subtitle`: A subtitle for the product.
220 4. `description`: A rich text field for the product's description.
221 5. `handle`: A unique identifier for the product used in URLs.
222 6. `images`: A media field to store multiple images of the product.
223 7. `thumbnail`: A media field to store a single thumbnail image of the product.
224 8. `locale`: A string field to support localization.
225 9. `variants`: A one-to-many relation to the Product Variant content type, which you'll define later.
226 10. `options`: A many-to-many relation to the Product Option content type, which you'll define later.
227
228 #### Product Lifecycle Hooks
229
230 Next, you'll handle product deletion by deleting associated product variants and options.
231
232 Create the file `src/api/product/content-types/product/lifecycles.ts` with the following content:
233
234 ```ts title="src/api/product/content-types/product/lifecycles.ts" badgeLabel="Strapi" badgeColor="orange"
235 export default {
236 async beforeDelete(event) {
237 const { where } = event.params
238
239 // Find the product with its relations
240 const product = await strapi.db.query("api::product.product").findOne({
241 where: {
242 id: where.id,
243 },
244 populate: {
245 variants: true,
246 options: true,
247 },
248 })
249
250 if (product) {
251 // Delete all variants
252 if (product.variants && product.variants.length > 0) {
253 for (const variant of product.variants) {
254 await strapi.documents("api::product-variant.product-variant").delete({
255 documentId: variant.documentId,
256 })
257 }
258 }
259
260 // Delete all options (their values will
261 // be cascade deleted by the option lifecycle)
262 if (product.options && product.options.length > 0) {
263 for (const option of product.options) {
264 await strapi.documents("api::product-option.product-option").delete({
265 documentId: option.documentId,
266 })
267 }
268 }
269 }
270 },
271 }
272 ```
273
274 You define a `beforeDelete` lifecycle hook that deletes all associated product variants and options when a product is deleted.
275
276 #### Product Controllers
277
278 Next, you'll create custom controllers to handle product management.
279
280 Create the file `src/api/product/controllers/product.ts` with the following content:
281
282 ```ts title="src/api/product/controllers/product.ts" badgeLabel="Strapi" badgeColor="orange"
283 import { factories } from "@strapi/strapi"
284
285 export default factories.createCoreController("api::product.product")
286 ```
287
288 This code creates a core controller for the Product content type using Strapi's factory method.
289
290 #### Product Services
291
292 Next, you'll create custom services to handle product management.
293
294 Create the file `src/api/product/services/product.ts` with the following content:
295
296 ```ts title="src/api/product/services/product.ts" badgeLabel="Strapi" badgeColor="orange"
297 import { factories } from "@strapi/strapi"
298
299 export default factories.createCoreService("api::product.product")
300 ```
301
302 This code creates a core service for the Product content type using Strapi's factory method.
303
304 #### Product Routes
305
306 Next, you'll create custom routes to handle product management.
307
308 Create the file `src/api/product/routes/product.ts` with the following content:
309
310 ```ts title="src/api/product/routes/product.ts" badgeLabel="Strapi" badgeColor="orange"
311 import { factories } from "@strapi/strapi"
312
313 export default factories.createCoreRouter("api::product.product")
314 ```
315
316 This code creates a core router for the Product content type using Strapi's factory method.
317
318 ### c. Define Product Variant Content Type
319
320 Next, you'll define a content type for product variants in Strapi.
321
322 #### Product Variant schema.json
323
324 To create the schema for the Product Variant content type, create the file `src/api/product-variant/content-types/product-variant/schema.json` with the following content:
325
326 ```json title="src/api/product-variant/content-types/product-variant/schema.json" badgeLabel="Strapi" badgeColor="orange"
327 {
328 "kind": "collectionType",
329 "collectionName": "product_variants",
330 "info": {
331 "singularName": "product-variant",
332 "pluralName": "product-variants",
333 "displayName": "Product Variant",
334 "description": "Product variants from Medusa"
335 },
336 "options": {
337 "draftAndPublish": false
338 },
339 "pluginOptions": {},
340 "attributes": {
341 "medusaId": {
342 "type": "string",
343 "required": true,
344 "unique": true
345 },
346 "title": {
347 "type": "string",
348 "required": true
349 },
350 "sku": {
351 "type": "string"
352 },
353 "images": {
354 "type": "media",
355 "multiple": true,
356 "required": false,
357 "allowedTypes": ["images"]
358 },
359 "thumbnail": {
360 "type": "media",
361 "multiple": false,
362 "required": false,
363 "allowedTypes": ["images"]
364 },
365 "locale": {
366 "type": "string",
367 "default": "en"
368 },
369 "product": {
370 "type": "relation",
371 "relation": "manyToOne",
372 "target": "api::product.product",
373 "inversedBy": "variants"
374 },
375 "option_values": {
376 "type": "relation",
377 "relation": "manyToMany",
378 "target": "api::product-option-value.product-option-value",
379 "inversedBy": "variants"
380 }
381 }
382 }
383 ```
384
385 You define the following fields for the Product Variant content type:
386
387 1. `medusaId`: A unique identifier that maps to the Medusa product variant ID.
388 2. `title`: The variant's title.
389 3. `sku`: The stock keeping unit for the variant.
390 4. `images`: A media field to store multiple images of the variant.
391 5. `thumbnail`: A media field to store a single thumbnail image of the variant.
392 6. `locale`: A string field to support localization.
393 7. `product`: A many-to-one relation to the Product content type.
394 8. `option_values`: A many-to-many relation to the Product Option Value content type, which you'll define later.
395
396 #### Product Variant Controllers
397
398 Next, you'll create custom controllers to handle product variant management.
399
400 Create the file `src/api/product-variant/controllers/product-variant.ts` with the following content:
401
402 ```ts title="src/api/product-variant/controllers/product-variant.ts" badgeLabel="Strapi" badgeColor="orange"
403 import { factories } from "@strapi/strapi"
404
405 export default factories.createCoreController("api::product-variant.product-variant")
406 ```
407
408 This code creates a core controller for the Product Variant content type using Strapi's factory method.
409
410 #### Product Variant Services
411
412 Next, you'll create custom services to handle product variant management.
413
414 Create the file `src/api/product-variant/services/product-variant.ts` with the following content:
415
416 ```ts title="src/api/product-variant/services/product-variant.ts" badgeLabel="Strapi" badgeColor="orange"
417 import { factories } from "@strapi/strapi"
418
419 export default factories.createCoreService("api::product-variant.product-variant")
420 ```
421
422 This code creates a core service for the Product Variant content type using Strapi's factory method.
423
424 #### Product Variant Routes
425
426 Next, you'll create custom routes to handle product variant management.
427
428 Create the file `src/api/product-variant/routes/product-variant.ts` with the following content:
429
430 ```ts title="src/api/product-variant/routes/product-variant.ts" badgeLabel="Strapi" badgeColor="orange"
431 import { factories } from "@strapi/strapi"
432
433 export default factories.createCoreRouter("api::product-variant.product-variant")
434 ```
435
436 This code creates a core router for the Product Variant content type using Strapi's factory method.
437
438 ### d. Define Product Option Content Type
439
440 Next, you'll define a content type for product options in Strapi.
441
442 #### Product Option schema.json
443
444 To create the schema for the Product Option content type, create the file `src/api/product-option/content-types/product-option/schema.json` with the following content:
445
446 ```json title="src/api/product-option/content-types/product-option/schema.json" badgeLabel="Strapi" badgeColor="orange"
447 {
448 "kind": "collectionType",
449 "collectionName": "product_options",
450 "info": {
451 "singularName": "product-option",
452 "pluralName": "product-options",
453 "displayName": "Product Option",
454 "description": "Product options from Medusa"
455 },
456 "options": {
457 "draftAndPublish": false
458 },
459 "pluginOptions": {},
460 "attributes": {
461 "medusaId": {
462 "type": "string",
463 "required": true,
464 "unique": true
465 },
466 "title": {
467 "type": "string",
468 "required": true
469 },
470 "locale": {
471 "type": "string",
472 "default": "en"
473 },
474 "products": {
475 "type": "relation",
476 "relation": "manyToMany",
477 "target": "api::product.product",
478 "inversedBy": "options"
479 },
480 "values": {
481 "type": "relation",
482 "relation": "oneToMany",
483 "target": "api::product-option-value.product-option-value",
484 "mappedBy": "option"
485 }
486 }
487 }
488 ```
489
490 You define the following fields for the Product Option content type:
491
492 1. `medusaId`: A unique identifier that maps to the Medusa product option ID.
493 2. `title`: The option's title.
494 3. `locale`: A string field to support localization.
495 4. `products`: A many-to-many relation to the Product content type.
496 5. `values`: A one-to-many relation to the Product Option Value content type, which you'll define later.
497
498 #### Product Option Lifecycle Hooks
499
500 Next, you'll handle option deletion by deleting associated option values.
501
502 Create the file `src/api/product-option/content-types/product-option/lifecycles.ts` with the following content:
503
504 ```ts title="src/api/product-option/content-types/product-option/lifecycles.ts" badgeLabel="Strapi" badgeColor="orange"
505 export default {
506 async beforeDelete(event) {
507 const { where } = event.params
508
509 // Find the option with its values
510 const option = await strapi.db.query("api::product-option.product-option").findOne({
511 where: {
512 id: where.id,
513 },
514 populate: {
515 values: true,
516 },
517 })
518
519 if (option && option.values && option.values.length > 0) {
520 // Delete all option values
521 for (const value of option.values) {
522 await strapi.documents("api::product-option-value.product-option-value").delete({
523 documentId: value.documentId,
524 })
525 }
526 }
527 },
528 }
529 ```
530
531 You define a `beforeDelete` lifecycle hook that deletes all associated option values when an option is deleted.
532
533 #### Product Option Controllers
534
535 Next, you'll create custom controllers to handle managing product options.
536
537 Create the file `src/api/product-option/controllers/product-option.ts` with the following content:
538
539 ```ts title="src/api/product-option/controllers/product-option.ts" badgeLabel="Strapi" badgeColor="orange"
540 import { factories } from "@strapi/strapi"
541
542 export default factories.createCoreController("api::product-option.product-option")
543 ```
544
545 This code creates a core controller for the Product Option content type using Strapi's factory method.
546
547 #### Product Option Services
548
549 Next, you'll create custom services to handle managing product options.
550
551 Create the file `src/api/product-option/services/product-option.ts` with the following content:
552
553 ```ts title="src/api/product-option/services/product-option.ts" badgeLabel="Strapi" badgeColor="orange"
554 import { factories } from "@strapi/strapi"
555
556 export default factories.createCoreService("api::product-option.product-option")
557 ```
558
559 This code creates a core service for the Product Option content type using Strapi's factory method.
560
561 #### Product Option Routes
562
563 Next, you'll create custom routes to handle managing product options.
564
565 Create the file `src/api/product-option/routes/product-option.ts` with the following content:
566
567 ```ts title="src/api/product-option/routes/product-option.ts" badgeLabel="Strapi" badgeColor="orange"
568 import { factories } from "@strapi/strapi"
569
570 export default factories.createCoreRouter("api::product-option.product-option")
571 ```
572
573 This code creates a core router for the Product Option content type using Strapi's factory method.
574
575 ### e. Define Product Option Value Content Type
576
577 The last content type you'll define is for product option values in Strapi.
578
579 #### Product Option Value schema.json
580
581 To create the schema for the Product Option Value content type, create the file `src/api/product-option-value/content-types/product-option-value/schema.json` with the following content:
582
583 ```json title="src/api/product-option-value/content-types/product-option-value/schema.json" badgeLabel="Strapi" badgeColor="orange"
584 {
585 "kind": "collectionType",
586 "collectionName": "product_option_values",
587 "info": {
588 "singularName": "product-option-value",
589 "pluralName": "product-option-values",
590 "displayName": "Product Option Value",
591 "description": "Product option values from Medusa"
592 },
593 "options": {
594 "draftAndPublish": false
595 },
596 "pluginOptions": {},
597 "attributes": {
598 "medusaId": {
599 "type": "string",
600 "required": true,
601 "unique": true
602 },
603 "value": {
604 "type": "string",
605 "required": true
606 },
607 "locale": {
608 "type": "string",
609 "default": "en"
610 },
611 "option": {
612 "type": "relation",
613 "relation": "manyToOne",
614 "target": "api::product-option.product-option",
615 "inversedBy": "values"
616 },
617 "variants": {
618 "type": "relation",
619 "relation": "manyToMany",
620 "target": "api::product-variant.product-variant",
621 "mappedBy": "option_values"
622 }
623 }
624 }
625 ```
626
627 You define the following fields for the Product Option Value content type:
628
629 1. `medusaId`: A unique identifier that maps to the Medusa product option value ID.
630 2. `value`: The option value's title.
631 3. `locale`: A string field to support localization.
632 4. `option`: A many-to-one relation to the Product Option content type.
633 5. `variants`: A many-to-many relation to the Product Variant content type.
634
635 #### Product Option Value Controllers
636
637 Next, you'll create custom controllers to handle managing product option values.
638
639 Create the file `src/api/product-option-value/controllers/product-option-value.ts` with the following content:
640
641 ```ts title="src/api/product-option-value/controllers/product-option-value.ts" badgeLabel="Strapi" badgeColor="orange"
642 import { factories } from "@strapi/strapi"
643
644 export default factories.createCoreController("api::product-option-value.product-option-value")
645 ```
646
647 This code creates a core controller for the Product Option Value content type using Strapi's factory method.
648
649 #### Product Option Value Services
650
651 Next, you'll create custom services to handle managing product option values.
652
653 Create the file `src/api/product-option-value/services/product-option-value.ts` with the following content:
654
655 ```ts title="src/api/product-option-value/services/product-option-value.ts" badgeLabel="Strapi" badgeColor="orange"
656 import { factories } from "@strapi/strapi"
657
658 export default factories.createCoreService("api::product-option-value.product-option-value")
659 ```
660
661 This code creates a core service for the Product Option Value content type using Strapi's factory method.
662
663 #### Product Option Value Routes
664
665 Next, you'll create custom routes to handle managing product option values.
666
667 Create the file `src/api/product-option-value/routes/product-option-value.ts` with the following content:
668
669 ```ts title="src/api/product-option-value/routes/product-option-value.ts" badgeLabel="Strapi" badgeColor="orange"
670 import { factories } from "@strapi/strapi"
671
672 export default factories.createCoreRouter("api::product-option-value.product-option-value")
673 ```
674
675 This code creates a core router for the Product Option Value content type using Strapi's factory method.
676
677 You now have all the customizations in Strapi ready. You'll return to Strapi later after you set up the integration with Medusa.
678
679 ---
680
681 ## Step 3: Integrate Strapi with Medusa
682
683 In this step, you'll integrate Strapi with Medusa by creating a Strapi Module.
684
685 A [module](!docs!/learn/fundamentals/modules) is a reusable package that provides functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
686
687 <Note>
688
689 Refer to the [Modules](!docs!/learn/fundamentals/modules) documentation to learn more about modules and their structure.
690
691 </Note>
692
693 ### a. Install Strapi Client
694
695 First, you'll install the Strapi client in your Medusa application to interact with Strapi's API.
696
697 In your `apps/backend` directory, run the following command to install the Strapi client:
698
699 ```bash badgeLabel="Medusa application" badgeColor="green"
700 npm install @strapi/client
701 ```
702
703 ### b. Create Module Directory
704
705 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/strapi`.
706
707 ### c. Create Strapi Client Loader
708
709 Next, you'll create the Strapi client when the Medusa server starts by creating a loader.
710
711 A [loader](!docs!/learn/fundamentals/modules/loaders) is an asynchronous function that runs when the Medusa server starts. Loaders are useful for setting up connections to third-party services and reusing those connections throughout your module.
712
713 To create the loader that initializes the Strapi client, create the file `src/modules/strapi/loaders/init-client.ts` with the following content:
714
715 ```ts title="src/modules/strapi/loaders/init-client.ts" badgeLabel="Medusa application" badgeColor="green"
716 import { LoaderOptions } from "@medusajs/framework/types"
717 import { asValue } from "@medusajs/framework/awilix"
718 import {
719 MedusaError,
720 ContainerRegistrationKeys,
721 } from "@medusajs/framework/utils"
722 import { strapi } from "@strapi/client"
723
724 export type ModuleOptions = {
725 apiUrl: string
726 apiToken: string
727 defaultLocale?: string
728 }
729
730 export default async function initStrapiClientLoader({
731 container,
732 options,
733 }: LoaderOptions<ModuleOptions>) {
734 if (!options?.apiUrl || !options?.apiToken) {
735 throw new MedusaError(
736 MedusaError.Types.INVALID_DATA,
737 "Strapi API URL and token are required"
738 )
739 }
740
741 const logger = container.resolve(
742 ContainerRegistrationKeys.LOGGER
743 )
744
745 try {
746 // Create Strapi client instance
747 const strapiClient = strapi({
748 baseURL: options.apiUrl,
749 auth: options.apiToken,
750 })
751
752 // Register the client in the container
753 container.register({
754 strapiClient: asValue(strapiClient),
755 })
756
757 logger.info("Strapi client initialized successfully")
758 } catch (error) {
759 logger.error(`Failed to initialize Strapi client: ${error}`)
760 throw error
761 }
762 }
763 ```
764
765 A loader file must export an asynchronous function that receives an object with the following properties:
766
767 1. `container`: The [module container](!docs!/learn/fundamentals/modules/container) that allows you to resolve and register module and Framework resources.
768 2. `options`: The options passed to the module during its registration. You define the following options for the Strapi Module:
769 - `apiUrl`: The URL of the Strapi API.
770 - `apiToken`: The API token to authenticate requests to Strapi.
771 - `defaultLocale`: An optional default locale for content.
772
773 In the loader function, you create a Strapi client instance using the provided API URL and token. Then, you register the client in the module container so that it can be resolved and used in the module's service.
774
775 ### d. Create Strapi Module Service
776
777 Next, you'll create the main service of the Strapi Module.
778
779 A module has a service that contains its logic. The Strapi Module's service will contain the logic to create, update, retrieve, and delete data in Strapi.
780
781 Create the file `src/modules/strapi/service.ts` with the following content:
782
783 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
784 import type { StrapiClient } from "@strapi/client"
785 import { Logger } from "@medusajs/framework/types"
786 import { ModuleOptions } from "./loaders/init-client"
787
788 type InjectedDependencies = {
789 logger: Logger
790 strapiClient: StrapiClient
791 }
792
793 export default class StrapiModuleService {
794 protected readonly options_: ModuleOptions
795 protected readonly logger_: any
796 protected readonly client_: StrapiClient
797
798 constructor(
799 { logger, strapiClient }: InjectedDependencies,
800 options: ModuleOptions
801 ) {
802 this.options_ = options
803 this.logger_ = logger
804 this.client_ = strapiClient
805 }
806
807 // TODO add methods
808 }
809 ```
810
811 The constructor of a module's service receives the following parameters:
812
813 1. The module's container.
814 2. The module's options.
815
816 You resolve the [Logger](!docs!/learn/debugging-and-testing/logging) and the Strapi client that you registered in the loader. You also store the module options for later use.
817
818 In the next sections, you'll add methods to this service to handle managing data in Strapi.
819
820 #### Format Errors Method
821
822 First, you'll add a helper method to format errors from Strapi.
823
824 In `src/modules/strapi/service.ts`, add the following method to the `StrapiModuleService` class:
825
826 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
827 export default class StrapiModuleService {
828 // ...
829 formatStrapiError(error: any, context: string): string {
830 // Handle Strapi client HTTP response errors
831 if (error?.response) {
832 const response = error.response
833 const parts = [context]
834
835 if (response.status) {
836 parts.push(`HTTP ${response.status}`)
837 }
838
839 if (response.statusText) {
840 parts.push(response.statusText)
841 }
842
843 // Add request URL if available
844 if (response.url) {
845 parts.push(`URL: ${response.url}`)
846 }
847
848 // Add request method if available
849 if (error.request?.method) {
850 parts.push(`Method: ${error.request.method}`)
851 }
852
853 return parts.join(" - ")
854 }
855
856 // If error has a response with Strapi error structure
857 if (error?.error) {
858 const strapiError = error.error
859 const parts = [context]
860
861 if (strapiError.status) {
862 parts.push(`Status ${strapiError.status}`)
863 }
864
865 if (strapiError.name) {
866 parts.push(`[${strapiError.name}]`)
867 }
868
869 if (strapiError.message) {
870 parts.push(strapiError.message)
871 }
872
873 if (strapiError.details && Object.keys(strapiError.details).length > 0) {
874 parts.push(`Details: ${JSON.stringify(strapiError.details)}`)
875 }
876
877 return parts.join(" - ")
878 }
879
880 // Fallback for non-Strapi errors
881 return `${context}: ${error.message || error}`
882 }
883 }
884 ```
885
886 This method takes an error object and a context string as parameters. It formats the error based on the structure of Strapi client errors, making it easier to log and debug issues related to Strapi API requests.
887
888 You'll use this method in other service methods to handle errors consistently.
889
890 #### Upload Images Method
891
892 Next, you'll add a method to upload images to Strapi.
893
894 In `src/modules/strapi/service.ts`, add the following method to the `StrapiModuleService` class:
895
896 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
897 export default class StrapiModuleService {
898 // ...
899 async uploadImages(imageUrls: string[]): Promise<number[]> {
900 const uploadedIds: number[] = []
901
902 for (const imageUrl of imageUrls) {
903 try {
904 // Fetch the image from the URL
905 const imageResponse = await fetch(imageUrl)
906 if (!imageResponse.ok) {
907 this.logger_.warn(`Failed to fetch image: ${imageUrl}`)
908 continue
909 }
910
911 const imageBuffer = await imageResponse.arrayBuffer()
912
913 // Extract filename from URL or generate one
914 const urlParts = imageUrl.split("/")
915 const filename = urlParts[urlParts.length - 1] || `image-${Date.now()}.jpg`
916
917 // Create a Blob from the buffer
918 const blob = new Blob([imageBuffer], {
919 type: imageResponse.headers.get("content-type") || "image/jpeg",
920 })
921
922 // Upload to Strapi using the files API
923 const result = await this.client_.files.upload(blob, {
924 fileInfo: {
925 name: filename,
926 },
927 })
928
929 if (result && result[0] && result[0].id) {
930 uploadedIds.push(result[0].id)
931 }
932 } catch (error) {
933 this.logger_.error(this.formatStrapiError(error, `Failed to upload image ${imageUrl}`))
934 }
935 }
936
937 return uploadedIds
938 }
939 }
940 ```
941
942 This method takes an array of image URLs, fetches each image, and uploads it to Strapi using the Strapi client's files API. It returns an array of uploaded image IDs.
943
944 You'll use this method later when creating or updating products and product variants in Strapi.
945
946 #### Delete Images Method
947
948 Next, you'll add a method to delete images from Strapi. This will be useful when reverting changes if a failure occurs.
949
950 In `src/modules/strapi/service.ts`, add the following import at the top of the file:
951
952 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
953 import { MedusaError } from "@medusajs/framework/utils"
954 ```
955
956 Then, add the following method to the `StrapiModuleService` class:
957
958 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
959 export default class StrapiModuleService {
960 // ...
961 async deleteImage(imageId: number): Promise<void> {
962 try {
963 await this.client_.files.delete(imageId)
964 } catch (error) {
965 throw new MedusaError(
966 MedusaError.Types.UNEXPECTED_STATE,
967 this.formatStrapiError(error, `Failed to delete image ${imageId} from Strapi`)
968 )
969 }
970 }
971 }
972 ```
973
974 This method takes an image ID as a parameter and deletes the corresponding image from Strapi using the Strapi client's files API. If the deletion fails, it throws a `MedusaError` with a formatted error message.
975
976 #### Create Document Type Method
977
978 Next, you'll add a method to create a document of a content type in Strapi, such as a product or product variant.
979
980 In `src/modules/strapi/service.ts`, add the following enum type before the `StrapiModuleService` class:
981
982 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
983 export enum Collection {
984 PRODUCTS = "products",
985 PRODUCT_VARIANTS = "product-variants",
986 PRODUCT_OPTIONS = "product-options",
987 PRODUCT_OPTION_VALUES = "product-option-values",
988 }
989 ```
990
991 Then, add the following method to the `StrapiModuleService` class:
992
993 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
994 export default class StrapiModuleService {
995 // ...
996 async create(collection: Collection, data: Record<string, unknown>) {
997 try {
998 return await this.client_.collection(collection).create(data)
999 } catch (error) {
1000 throw new MedusaError(
1001 MedusaError.Types.UNEXPECTED_STATE,
1002 this.formatStrapiError(error, `Failed to create ${collection} in Strapi`)
1003 )
1004 }
1005 }
1006 }
1007 ```
1008
1009 This method takes the following parameters:
1010
1011 1. `collection`: The collection (content type) in which to create the document. It uses the `Collection` enum.
1012 2. `data`: An object containing the data for the document to be created.
1013
1014 In the method, you create the document and return it.
1015
1016 #### Update Document Method
1017
1018 Next, you'll add a method to update a document of a content type in Strapi. This will be useful to implement two-way synching between Medusa and Strapi.
1019
1020 In `src/modules/strapi/service.ts`, add the following method to the `StrapiModuleService` class:
1021
1022 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
1023 export default class StrapiModuleService {
1024 // ...
1025 async update(collection: Collection, id: string, data: Record<string, unknown>) {
1026 try {
1027 return await this.client_.collection(collection).update(id, data)
1028 } catch (error) {
1029 throw new MedusaError(
1030 MedusaError.Types.UNEXPECTED_STATE,
1031 this.formatStrapiError(error, `Failed to update ${collection} in Strapi`)
1032 )
1033 }
1034 }
1035 }
1036 ```
1037
1038 This method takes the following parameters:
1039
1040 1. `collection`: The collection (content type) in which the document exists. It uses the `Collection` enum.
1041 2. `id`: The ID of the document to be updated.
1042 3. `data`: An object containing the data to update the document with.
1043
1044 In the method, you update the document and return it.
1045
1046 #### Delete Document Method
1047
1048 Next, you'll add a method to delete a document of a content type from Strapi. You'll use this method when a document is deleted in Medusa, or when reverting document creation in case of failures.
1049
1050 In `src/modules/strapi/service.ts`, add the following method to the `StrapiModuleService` class:
1051
1052 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
1053 export default class StrapiModuleService {
1054 // ...
1055 async delete(collection: Collection, id: string) {
1056 try {
1057 return await this.client_.collection(collection).delete(id)
1058 } catch (error) {
1059 throw new MedusaError(
1060 MedusaError.Types.UNEXPECTED_STATE,
1061 this.formatStrapiError(error, `Failed to delete ${collection} in Strapi`)
1062 )
1063 }
1064 }
1065 }
1066 ```
1067
1068 This method takes the following parameters:
1069
1070 1. `collection`: The collection (content type) in which the document exists. It uses the `Collection` enum.
1071 2. `id`: The ID of the document to be deleted.
1072
1073 In the method, you delete the document.
1074
1075 #### Retrieve Document by Medusa ID Method
1076
1077 Next, you'll add a method to retrieve a document of a content type from Strapi by its Medusa ID. This will be useful to retrieve a document in case you need to revert changes.
1078
1079 In `src/modules/strapi/service.ts`, add the following method to the `StrapiModuleService` class:
1080
1081 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
1082 export default class StrapiModuleService {
1083 // ...
1084 async findByMedusaId(
1085 collection: Collection,
1086 medusaId: string | string[],
1087 populate?: string[]
1088 ) {
1089 try {
1090 const result = await this.client_.collection(collection).find({
1091 filters: {
1092 medusaId: {
1093 $in: Array.isArray(medusaId) ? medusaId : [medusaId],
1094 },
1095 },
1096 populate,
1097 })
1098
1099 return result.data
1100 }
1101 catch (error) {
1102 throw new MedusaError(
1103 MedusaError.Types.UNEXPECTED_STATE,
1104 this.formatStrapiError(error, `Failed to find ${collection} in Strapi`)
1105 )
1106 }
1107 }
1108 }
1109 ```
1110
1111 This method takes the following parameters:
1112
1113 1. `collection`: The collection (content type) in which the document exists. It uses the `Collection` enum.
1114 2. `medusaId`: A single Medusa ID or an array of Medusa IDs of the documents to be retrieved.
1115 3. `populate`: An optional array of relations to populate in the retrieved document.
1116
1117 In the method, you retrieve the documents and return the results.
1118
1119 ### e. Export Module Definition
1120
1121 The final piece of a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the name of the module, its service, and optionally its loaders.
1122
1123 To create the module's definition, create the file `src/modules/strapi/index.ts` with the following content:
1124
1125 ```ts title="src/modules/strapi/index.ts" badgeLabel="Medusa application" badgeColor="green"
1126 import { Module } from "@medusajs/framework/utils"
1127 import StrapiModuleService from "./service"
1128 import initStrapiClientLoader from "./loaders/init-client"
1129
1130 export const STRAPI_MODULE = "strapi"
1131
1132 export default Module(STRAPI_MODULE, {
1133 service: StrapiModuleService,
1134 loaders: [initStrapiClientLoader],
1135 })
1136 ```
1137
1138 You use `Module` from the Modules SDK to create the module's definition. It accepts two parameters:
1139
1140 1. The module's name, which is `strapi`.
1141 2. An object with a required `service` property indicating the module's service. You also pass the loader you created to ensure it's executed when the application starts.
1142
1143 Aside from the module definition, you export the module's name as `STRAPI_MODULE` for later reference.
1144
1145 ### f. Add Module to Medusa's Configurations
1146
1147 Once you finish building the module, add it to Medusa's configurations to start using it.
1148
1149 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
1150
1151 ```ts title="medusa-config.ts" badgeLabel="Medusa application" badgeColor="green"
1152 module.exports = defineConfig({
1153 // ...
1154 modules: [
1155 {
1156 resolve: "./modules/strapi",
1157 options: {
1158 apiUrl: process.env.STRAPI_API_URL || "http://localhost:1337/api",
1159 apiToken: process.env.STRAPI_API_TOKEN || "",
1160 defaultLocale: process.env.STRAPI_DEFAULT_LOCALE || "en",
1161 },
1162 },
1163 ],
1164 })
1165 ```
1166
1167 Each object in the `modules` array has a `resolve` property, whose value is either a path to the module's directory or an npm package's name.
1168
1169 You also pass an `options` property with the module's options. You'll set the values of these options next.
1170
1171 ### g. Set Environment Variables
1172
1173 Before you can use the Strapi Module, you need to set the environment variables it requires.
1174
1175 One of these options is an API token that has permissions to manage the content types you created in Strapi.
1176
1177 To retrieve the API token from Strapi, run the following command in the Strapi project directory to start the Strapi server:
1178
1179 ```bash npm2yarn
1180 npm run dev
1181 ```
1182
1183 Then:
1184
1185 1. Log in to the Strapi admin panel at `http://localhost:1337/admin`.
1186 2. Go to Settings -> API Tokens.
1187 3. Click on "Create new API Token".
1188
1189 ![Strapi dashboard with the API Token settings opened](https://res.cloudinary.com/dza7lstvk/image/upload/v1763136134/Medusa%20Resources/CleanShot_2025-11-14_at_18.00.44_2x_ec8lds.png)
1190
1191 4. In the API token form:
1192 - Set a name for the token, such as "Medusa".
1193 - Set the type to "Custom", and:
1194 - For each content type you created (products, product variants, product options, and product option values), expand its permissions section and enable all the permissions (create, read, update, delete, find).
1195 - Also enable the permissions for "Upload" to allow image uploads.
1196 5. Click on "Save".
1197
1198 ![Strapi dashboard with the Create API Token form filled](https://res.cloudinary.com/dza7lstvk/image/upload/v1763136134/Medusa%20Resources/CleanShot_2025-11-14_at_18.01.25_2x_hdex6b.png)
1199
1200 Then, copy the generated API token.
1201
1202 Finally, set the following environment variables in your Medusa project's `.env` file:
1203
1204 ```env
1205 STRAPI_API_URL=http://localhost:1337/api
1206 STRAPI_API_TOKEN=your_generated_api_token
1207 ```
1208
1209 Make sure to replace `your_generated_api_token` with the actual API token you copied from Strapi.
1210
1211 ---
1212
1213 ## Step 4: Create Virtual Read-Only Link to Strapi Products
1214
1215 Medusa's [Module Links](!docs!/learn/fundamentals/module-links) feature allows you to virtually link data models from external services to modules in your Medusa application. Then, when you retrieve data from Medusa, you can also retrieve the linked data from the third-party service automatically.
1216
1217 In this step, you'll define a virtual read-only link between the product content type in Strapi and the `Product` model in Medusa. Later, you'll be able to retrieve products from Strapi when retrieving products in Medusa.
1218
1219 ### a. Define the Link
1220
1221 To define a virtual read-only link, create the file `src/links/product-strapi.ts` with the following content:
1222
1223 ```ts title="src/links/product-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
1224 import { defineLink } from "@medusajs/framework/utils"
1225 import ProductModule from "@medusajs/medusa/product"
1226 import { STRAPI_MODULE } from "../modules/strapi"
1227
1228 export default defineLink(
1229 {
1230 linkable: ProductModule.linkable.product,
1231 field: "id",
1232 },
1233 {
1234 linkable: {
1235 serviceName: STRAPI_MODULE,
1236 alias: "strapi_product",
1237 primaryKey: "product_id",
1238 },
1239 },
1240 {
1241 readOnly: true,
1242 }
1243 )
1244 ```
1245
1246 The `defineLink` function accepts three parameters:
1247
1248 - An object of the first data model that is part of the link. In this case, it's the `Product` model from Medusa's Product Module.
1249 - An object of the second data model that is part of the link. In this case, it's the product content type from the Strapi Module. You set the following properties:
1250 - `serviceName`: the name of the Strapi Module, which is `strapi`.
1251 - `alias`: an alias for the linked data model, which is `strapi_product`. You'll use this alias to reference the linked data model in queries.
1252 - `primaryKey`: the primary key of the linked data model, which is `product_id`. Medusa will look for this field in the retrieved `Products` from Strapi to match it with the `id` field of the `Product` model.
1253 - An object with the `readOnly` property set to `true`, indicating that this link is read-only. This means you can only retrieve the linked data, but you don't manage the link in the database.
1254
1255 ### b. Add list Method to the Strapi Module Service
1256
1257 When you retrieve products from Medusa with their `strapi_product` link, Medusa will call the `list` method of the Strapi Module's service to retrieve the linked products from Strapi.
1258
1259 So, in `src/modules/strapi/service.ts`, add a `list` method to the `StrapiModuleService` class:
1260
1261 ```ts title="src/modules/strapi/service.ts" badgeLabel="Medusa application" badgeColor="green"
1262 export default class StrapiModuleService {
1263 // ...
1264 async list(filter: { product_id: string | string[] }) {
1265 const ids = Array.isArray(filter.product_id)
1266 ? filter.product_id
1267 : [filter.product_id]
1268
1269 const results: any[] = []
1270
1271 for (const productId of ids) {
1272 try {
1273 // Fetch product with all relations populated
1274 const result = await this.client_.collection("products").find({
1275 filters: {
1276 medusaId: {
1277 $eq: productId,
1278 },
1279 },
1280 populate: {
1281 variants: {
1282 populate: ["option_values"],
1283 },
1284 options: {
1285 populate: ["values"],
1286 },
1287 },
1288 })
1289
1290 if (result.data && result.data.length > 0) {
1291 const product = result.data[0]
1292 results.push({
1293 ...product,
1294 id: `${product.id}`,
1295 product_id: productId,
1296 // Include populated relations
1297 variants: (product.variants || []).map((variant) => ({
1298 ...variant,
1299 id: `${variant.id}`,
1300 option_values: (variant.option_values || []).map((option_value) => ({
1301 ...option_value,
1302 id: `${option_value.id}`,
1303 })),
1304 })),
1305 options: (product.options || []).map((option) => ({
1306 ...option,
1307 id: `${option.id}`,
1308 values: (option.values || []).map((value) => ({
1309 ...value,
1310 id: `${value.id}`,
1311 })),
1312 })),
1313 })
1314 }
1315 } catch (error) {
1316 this.logger_.warn(this.formatStrapiError(error, `Failed to fetch product ${productId} from Strapi`))
1317 }
1318 }
1319
1320 return results
1321 }
1322 }
1323 ```
1324
1325 The `list` method receives a `filter` object with a `product_id` property, which contains the Medusa product ID(s) to retrieve their corresponding data from Strapi.
1326
1327 In the method, you fetch each product from Strapi using the Strapi client's collection API, populating its relations (variants and options). You then format the retrieved data to match the expected structure and return an array of products.
1328
1329 You can now retrieve product data from Strapi when retrieving products in Medusa. You'll learn how to do this in the upcoming steps.
1330
1331 ---
1332
1333 ## Step 5: Handle Product Creation
1334
1335 In this step, you'll implement the logic to listen to product creation events in Medusa and create the corresponding product data in Strapi.
1336
1337 To do this, you'll create:
1338
1339 1. [Workflows](!docs!/learn/fundamentals/workflows) that implement the logic to create product data in Strapi.
1340 2. A [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the product creation event in Medusa and triggers the workflow.
1341
1342 ### a. Create Product Options Workflow
1343
1344 Before creating the main workflow to handle product creation, you'll create a sub-workflow to handle the creation of product options and their values in Strapi. You'll use this sub-workflow in the main product creation workflow.
1345
1346 You create custom commerce features in [workflows](!docs!/learn/fundamentals/workflows). A workflow is a series of queries and actions, called steps, that complete a task. A workflow is similar to a function, but allows you to track execution progress, define rollback logic, and configure other advanced features.
1347
1348 <Note>
1349
1350 Refer to the [Workflows documentation](!docs!/learn/fundamentals/workflows) to learn more.
1351
1352 </Note>
1353
1354 The workflow to create product options in Strapi has the following steps:
1355
1356 <WorkflowDiagram
1357 workflow={{
1358 name: "createOptionsInStrapiWorkflow",
1359 steps: [
1360 {
1361 type: "step",
1362 name: "useQueryGraphStep",
1363 description: "Retrieve product option data.",
1364 link: "/references/helper-steps/useQueryGraphStep",
1365 depth: 1
1366 },
1367 {
1368 type: "step",
1369 name: "createOptionsInStrapiStep",
1370 description: "Create the product option in Strapi.",
1371 depth: 2
1372 },
1373 {
1374 type: "step",
1375 name: "createOptionValuesInStrapiStep",
1376 description: "Create the product option value in Strapi.",
1377 depth: 3
1378 },
1379 {
1380 type: "step",
1381 name: "updateProductOptionValuesMetadataStep",
1382 description: "Store the Strapi ID in the product option values metadata.",
1383 depth: 4
1384 }
1385 ]
1386 }}
1387 hideLegend
1388 />
1389
1390 The first step is available out-of-the-box in Medusa. You need to create the rest of the steps.
1391
1392 #### createOptionsInStrapiStep
1393
1394 The `createOptionsInStrapiStep` creates product options in Strapi.
1395
1396 To create the step, create the file `src/workflows/steps/create-options-in-strapi.ts` with the following content:
1397
1398 ```ts title="src/workflows/steps/create-options-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
1399 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1400 import { STRAPI_MODULE } from "../../modules/strapi"
1401 import StrapiModuleService, { Collection } from "../../modules/strapi/service"
1402
1403 export type CreateOptionsInStrapiInput = {
1404 options: {
1405 id: string
1406 title: string
1407 }[]
1408 }
1409
1410 export const createOptionsInStrapiStep = createStep(
1411 "create-options-in-strapi",
1412 async ({ options }: CreateOptionsInStrapiInput, { container }) => {
1413 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1414
1415 const results: Record<string, any>[] = []
1416
1417 try {
1418 for (const option of options) {
1419 const strapiOption = await strapiService.create(
1420 Collection.PRODUCT_OPTIONS,
1421 {
1422 medusaId: option.id,
1423 title: option.title,
1424 }
1425 )
1426
1427 results.push(strapiOption.data)
1428 }
1429 } catch (error) {
1430 // If error occurs during loop,
1431 // pass results created so far to compensation
1432 return StepResponse.permanentFailure(
1433 strapiService.formatStrapiError(
1434 error,
1435 "Failed to create options in Strapi"
1436 ),
1437 { results }
1438 )
1439 }
1440
1441 return new StepResponse(
1442 results,
1443 results
1444 )
1445 },
1446 async (compensationData, { container }) => {
1447 if (!compensationData) {
1448 return
1449 }
1450
1451 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1452
1453 // Delete all created options
1454 for (const result of compensationData) {
1455 await strapiService.delete(Collection.PRODUCT_OPTIONS, result.documentId)
1456 }
1457 }
1458 )
1459 ```
1460
1461 You create a step with the `createStep` function. It accepts three parameters:
1462
1463 1. The step's unique name.
1464 2. An async function that receives two parameters:
1465 - The step's input, which is an object holding the product options to create in Strapi.
1466 - An object that has properties including the [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools that you can access in the step.
1467 3. An async compensation function that undoes the actions performed by the step function. This function is only executed if an error occurs during the workflow's execution.
1468
1469 In the step function, you resolve the Strapi Module's service from the Medusa container. Then, you loop through the product options and create them in Strapi using the service's `create` method.
1470
1471 If an error occurs during the creation loop, you return a permanent failure response with the results created so far. This allows the compensation function to delete any options that were successfully created before the error occurred.
1472
1473 Finally, a step must return a `StepResponse` instance, which accepts two parameters:
1474
1475 1. The step's output, which is an array of created Strapi product options.
1476 2. The data to pass to the compensation function, which is also the array of created Strapi product options.
1477
1478 In the compensation function, you delete all the created product options in Strapi if an error occurs during the workflow's execution.
1479
1480 #### createOptionValuesInStrapiStep
1481
1482 The `createOptionValuesInStrapiStep` creates product option values in Strapi.
1483
1484 To create the step, create the file `src/workflows/steps/create-option-values-in-strapi.ts` with the following content:
1485
1486 ```ts title="src/workflows/steps/create-option-values-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
1487 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1488 import { STRAPI_MODULE } from "../../modules/strapi"
1489 import StrapiModuleService, { Collection } from "../../modules/strapi/service"
1490
1491 export type CreateOptionValuesInStrapiInput = {
1492 optionValues: {
1493 id: string
1494 value: string
1495 strapiOptionId: number
1496 }[]
1497 }
1498
1499 export const createOptionValuesInStrapiStep = createStep(
1500 "create-option-values-in-strapi",
1501 async ({ optionValues }: CreateOptionValuesInStrapiInput, { container }) => {
1502 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1503
1504 const results: Record<string, any>[] = []
1505
1506 try {
1507 for (const optionValue of optionValues) {
1508 // Create option value in Strapi
1509 const strapiOptionValue = await strapiService.create(
1510 Collection.PRODUCT_OPTION_VALUES,
1511 {
1512 medusaId: optionValue.id,
1513 value: optionValue.value,
1514 option: optionValue.strapiOptionId,
1515 }
1516 )
1517
1518 results.push(strapiOptionValue.data)
1519 }
1520 } catch (error) {
1521 // If error occurs during loop,
1522 // pass results created so far to compensation
1523 return StepResponse.permanentFailure(
1524 strapiService.formatStrapiError(
1525 error,
1526 "Failed to create option values in Strapi"
1527 ),
1528 { results }
1529 )
1530 }
1531
1532 return new StepResponse(
1533 results,
1534 results
1535 )
1536 },
1537 async (compensationData, { container }) => {
1538 if (!compensationData) {
1539 return
1540 }
1541
1542 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1543
1544 // Delete all created option values
1545 for (const result of compensationData) {
1546 await strapiService.delete(
1547 Collection.PRODUCT_OPTION_VALUES,
1548 result.documentId
1549 )
1550 }
1551 }
1552 )
1553 ```
1554
1555 This step receives the option values to create in Strapi. In the step, you create each option value in Strapi using the Strapi Module's service.
1556
1557 In the compensation function, you delete all the created option values in Strapi if an error occurs during the workflow's execution.
1558
1559 #### updateProductOptionValuesMetadataStep
1560
1561 The `updateProductOptionValuesMetadataStep` stores the Strapi IDs of the created product option values in the `metadata` property of the corresponding product option values in Medusa. This allows you to reference the Strapi option values later, such as when updating or deleting them.
1562
1563 To create the step, create the file `src/workflows/steps/update-product-option-values-metadata.ts` with the following content:
1564
1565 ```ts title="src/workflows/steps/update-product-option-values-metadata.ts" badgeLabel="Medusa application" badgeColor="green"
1566 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1567 import { Modules } from "@medusajs/framework/utils"
1568 import { ProductOptionValueDTO } from "@medusajs/framework/types"
1569
1570 export type UpdateProductOptionValuesMetadataInput = {
1571 updates: {
1572 id: string
1573 strapiId: number
1574 strapiDocumentId: string
1575 }[]
1576 }
1577
1578 export const updateProductOptionValuesMetadataStep = createStep(
1579 "update-product-option-values-metadata",
1580 async ({ updates }: UpdateProductOptionValuesMetadataInput, { container }) => {
1581 const productModuleService = container.resolve(Modules.PRODUCT)
1582
1583 const updatedOptionValues: ProductOptionValueDTO[] = []
1584
1585 // Fetch original metadata for compensation
1586 const originalOptionValues = await productModuleService.listProductOptionValues({
1587 id: updates.map((u) => u.id),
1588 })
1589
1590 // Update each option value's metadata
1591 for (const update of updates) {
1592 const optionValue = originalOptionValues.find((ov) => ov.id === update.id)
1593 if (optionValue) {
1594
1595 const updated = await productModuleService.updateProductOptionValues(
1596 update.id,
1597 {
1598 metadata: {
1599 ...optionValue.metadata,
1600 strapi_id: update.strapiId,
1601 strapi_document_id: update.strapiDocumentId,
1602 },
1603 }
1604 )
1605
1606 updatedOptionValues.push(updated)
1607
1608 }
1609 }
1610
1611 return new StepResponse(updatedOptionValues, originalOptionValues)
1612 },
1613 async (compensationData, { container }) => {
1614 if (!compensationData) {
1615 return
1616 }
1617
1618 const productModuleService = container.resolve(Modules.PRODUCT)
1619
1620 // Restore original metadata
1621 for (const original of compensationData) {
1622 await productModuleService.updateProductOptionValues(original.id, {
1623 metadata: original.metadata,
1624 })
1625 }
1626 }
1627 )
1628 ```
1629
1630 This step receives an array of option values to update with their corresponding Strapi IDs.
1631
1632 In the step, you resolve the Product Module's service and update each option value's `metadata` property with the Strapi ID and document ID.
1633
1634 In the compensation function, you restore the original metadata of the option values if an error occurs during the workflow's execution.
1635
1636 #### Create Product Options Workflow
1637
1638 Now that you have created the necessary steps, you can create the workflow.
1639
1640 To create the workflow, create the file `src/workflows/create-options-in-strapi.ts` with the following content:
1641
1642 ```ts title="src/workflows/create-options-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green" collapsibleLines="1-15" expandButtonLabel="Show Imports"
1643 import {
1644 createWorkflow,
1645 WorkflowResponse,
1646 transform,
1647 } from "@medusajs/framework/workflows-sdk"
1648 import { createOptionsInStrapiStep } from "./steps/create-options-in-strapi"
1649 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1650 import {
1651 CreateOptionValuesInStrapiInput,
1652 createOptionValuesInStrapiStep,
1653 } from "./steps/create-option-values-in-strapi"
1654 import {
1655 updateProductOptionValuesMetadataStep,
1656 } from "./steps/update-product-option-values-metadata"
1657
1658 export type CreateOptionsInStrapiWorkflowInput = {
1659 ids: string[]
1660 }
1661
1662 export const createOptionsInStrapiWorkflow = createWorkflow(
1663 "create-options-in-strapi",
1664 (input: CreateOptionsInStrapiWorkflowInput) => {
1665 // Fetch the option with all necessary fields
1666 // including metadata
1667 const { data: options } = useQueryGraphStep({
1668 entity: "product_option",
1669 fields: [
1670 "id",
1671 "title",
1672 "metadata",
1673 "values.id",
1674 "values.value",
1675 "values.metadata",
1676 ],
1677 filters: {
1678 id: input.ids,
1679 },
1680 options: {
1681 throwIfKeyNotFound: true,
1682 },
1683 })
1684
1685 // @ts-ignore
1686 const preparedOptions = transform({ options }, (data) => {
1687 return data.options.map((option) => ({
1688 id: option.id,
1689 title: option.title,
1690 }))
1691 })
1692
1693 // Pass the prepared option data to the step
1694 const strapiOptions = createOptionsInStrapiStep({
1695 options: preparedOptions,
1696 })
1697
1698 // Extract option values
1699 const optionValuesData = transform({ options, strapiOptions }, (data) => {
1700 return data.options.flatMap((option) => {
1701 return option.values.map((value) => {
1702 const strapiOption = data.strapiOptions.find(
1703 (strapiOption) => strapiOption.medusaId === option.id
1704 )
1705 if (!strapiOption) {
1706 return null
1707 }
1708 return {
1709 id: value.id,
1710 value: value.value,
1711 strapiOptionId: strapiOption.id,
1712 }
1713 })
1714 })
1715 })
1716
1717 const strapiOptionValues = createOptionValuesInStrapiStep({
1718 optionValues: optionValuesData,
1719 } as CreateOptionValuesInStrapiInput)
1720
1721 const optionValuesMetadataUpdate = transform({ strapiOptionValues }, (data) => {
1722 return {
1723 updates: [
1724 ...data.strapiOptionValues.map((optionValue) => ({
1725 id: optionValue.medusaId,
1726 strapiId: optionValue.id,
1727 strapiDocumentId: optionValue.documentId,
1728 })),
1729 ],
1730 }
1731 })
1732
1733 updateProductOptionValuesMetadataStep(optionValuesMetadataUpdate)
1734
1735 return new WorkflowResponse({
1736 strapi_options: strapiOptions,
1737 })
1738 }
1739 )
1740 ```
1741
1742 You create a workflow using the `createWorkflow` function. It accepts the workflow's unique name as a first parameter.
1743
1744 It accepts a second parameter: a constructor function that holds the workflow's implementation. The function accepts an input object holding the IDs of the product options to create in Strapi.
1745
1746 In the workflow, you:
1747
1748 1. Retrieve the product options in Medusa using the `useQueryGraphStep`.
1749 - This step uses [Query](!docs!/learn/fundamentals/query) to retrieve data in Medusa across modules.
1750 2. Prepare the option data to create using [transform](!docs!/learn/fundamentals/workflows/variable-manipulation).
1751 - This function allows you to manipulate data in workflows.
1752 3. Create the product options in Strapi using the `createOptionsInStrapiStep`.
1753 4. Prepare the option values to create using `transform`.
1754 5. Create the product option values in Strapi using the `createOptionValuesInStrapiStep`.
1755 6. Prepare the data to update the option values' metadata using `transform`.
1756 7. Update the option values' metadata using the `updateProductOptionValuesMetadataStep`.
1757
1758 A workflow must return an instance of `WorkflowResponse` that accepts the data to return to the workflow's executor.
1759
1760 You'll use this workflow when you implement the create products in Strapi workflow.
1761
1762 <Note>
1763
1764 In a workflow, you can't manipulate data because Medusa stores an internal representation of the workflow on application startup. Learn more in the [Data Manipulation](!docs!/learn/fundamentals/workflows/variable-manipulation) documentation.
1765
1766 </Note>
1767
1768 ### b. Create Product Variants Workflow
1769
1770 Next, you'll create another sub-workflow to handle the creation of product variants in Strapi. You'll use this sub-workflow in the main product creation workflow.
1771
1772 The workflow to create product variants in Strapi has the following steps:
1773
1774 <WorkflowDiagram
1775 workflow={{
1776 workflow: "createVariantsInStrapiWorkflow",
1777 steps: [
1778 {
1779 type: "step",
1780 name: "acquireLockStep",
1781 description: "Acquire a lock to prevent concurrent creation",
1782 link: "/references/medusa-workflows/steps/acquireLockStep",
1783 depth: 1
1784 },
1785 {
1786 type: "step",
1787 name: "useQueryGraphStep",
1788 description: "Retrieve product variant data.",
1789 link: "/references/helper-steps/useQueryGraphStep",
1790 depth: 2
1791 },
1792 {
1793 type: "when",
1794 steps: [
1795 {
1796 type: "step",
1797 name: "uploadImagesToStrapiStep",
1798 description: "Upload variant images to Strapi.",
1799 depth: 1
1800 },
1801 {
1802 type: "step",
1803 name: "uploadImagesToStrapiStep",
1804 description: "Upload variant thumbnail to Strapi.",
1805 depth: 2
1806 },
1807 {
1808 type: "step",
1809 name: "createVariantsInStrapiStep",
1810 description: "Create the product variant in Strapi.",
1811 depth: 3
1812 },
1813 {
1814 type: "step",
1815 name: "updateProductVariantsMetadataStep",
1816 description: "Store the Strapi ID in the product variants metadata.",
1817 depth: 4
1818 }
1819 ],
1820 depth: 3
1821 },
1822 {
1823 type: "step",
1824 name: "releaseLockStep",
1825 description: "Release the acquired lock",
1826 link: "/references/medusa-workflows/steps/releaseLockStep",
1827 depth: 4
1828 }
1829 ]
1830 }}
1831 hideLegend
1832 />
1833
1834 The first, second, and last steps are available out-of-the-box in Medusa. You need to create the rest of the steps.
1835
1836 #### uploadImagesToStrapiStep
1837
1838 The `uploadImagesToStrapiStep` uploads images to Strapi. You'll use it to upload product and variant images.
1839
1840 To create the step, create the file `src/workflows/steps/upload-images-to-strapi.ts` with the following content:
1841
1842 ```ts title="src/workflows/steps/upload-images-to-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
1843 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1844 import { STRAPI_MODULE } from "../../modules/strapi"
1845 import StrapiModuleService from "../../modules/strapi/service"
1846 import { promiseAll } from "@medusajs/framework/utils"
1847
1848 export type UploadImagesToStrapiInput = {
1849 items: {
1850 entity_id: string
1851 url: string
1852 }[]
1853 }
1854
1855 export const uploadImagesToStrapiStep = createStep(
1856 "upload-images-to-strapi",
1857 async ({ items }: UploadImagesToStrapiInput, { container }) => {
1858 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1859
1860 const uploadedImages: {
1861 entity_id: string
1862 image_id: number
1863 }[] = []
1864
1865 try {
1866 for (const item of items) {
1867 // Upload image to Strapi
1868 const uploadedImageId = await strapiService.uploadImages([item.url])
1869 uploadedImages.push({
1870 entity_id: item.entity_id,
1871 image_id: uploadedImageId[0],
1872 })
1873 }
1874 } catch (error) {
1875 // If error occurs, pass all uploaded files to compensation
1876 return StepResponse.permanentFailure(
1877 strapiService.formatStrapiError(
1878 error,
1879 "Failed to upload images to Strapi"
1880 ),
1881 { uploadedImages }
1882 )
1883 }
1884
1885 return new StepResponse(
1886 uploadedImages,
1887 uploadedImages
1888 )
1889 },
1890 async (compensationData, { container }) => {
1891 if (!compensationData) {
1892 return
1893 }
1894
1895 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1896
1897 await promiseAll(
1898 compensationData.map(
1899 (uploadedImage) => strapiService.deleteImage(uploadedImage.image_id)
1900 )
1901 )
1902 }
1903 )
1904 ```
1905
1906 The step accepts an array of items, each having the ID of the item that the image is associated with, and the URL of the image to upload.
1907
1908 In the step, you upload each image to Strapi using the Strapi Module's service.
1909
1910 In the compensation function, you delete all the uploaded images in Strapi if an error occurs during the workflow's execution.
1911
1912 #### createVariantsInStrapiStep
1913
1914 The `createVariantsInStrapiStep` creates product variants in Strapi.
1915
1916 To create the step, create the file `src/workflows/steps/create-variants-in-strapi.ts` with the following content:
1917
1918 ```ts title="src/workflows/steps/create-variants-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
1919 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1920 import { STRAPI_MODULE } from "../../modules/strapi"
1921 import StrapiModuleService, { Collection } from "../../modules/strapi/service"
1922
1923 export type CreateVariantsInStrapiInput = {
1924 variants: {
1925 id: string
1926 title: string
1927 sku?: string
1928 strapiProductId: number
1929 optionValueIds?: number[]
1930 imageIds?: number[]
1931 thumbnailId?: number
1932 }[]
1933 }
1934
1935 export const createVariantsInStrapiStep = createStep(
1936 "create-variants-in-strapi",
1937 async ({ variants }: CreateVariantsInStrapiInput, { container }) => {
1938 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1939
1940 const results: Record<string, any>[] = []
1941
1942 try {
1943 // Process all variants
1944 for (const variant of variants) {
1945 // Create variant in Strapi
1946 const strapiVariant = await strapiService.create(
1947 Collection.PRODUCT_VARIANTS,
1948 {
1949 medusaId: variant.id,
1950 title: variant.title,
1951 sku: variant.sku,
1952 product: variant.strapiProductId,
1953 option_values: variant.optionValueIds || [],
1954 images: variant.imageIds || [],
1955 thumbnail: variant.thumbnailId,
1956 }
1957 )
1958
1959 results.push(strapiVariant.data)
1960 }
1961 } catch (error) {
1962 // If error occurs during loop,
1963 // pass results created so far to compensation
1964 return StepResponse.permanentFailure(
1965 strapiService.formatStrapiError(
1966 error,
1967 "Failed to create variants in Strapi"
1968 ),
1969 { results }
1970 )
1971 }
1972
1973 return new StepResponse(
1974 results,
1975 results
1976 )
1977 },
1978 async (compensationData, { container }) => {
1979 if (!compensationData) {
1980 return
1981 }
1982
1983 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
1984
1985 // Delete all created variants
1986 for (const result of compensationData) {
1987 await strapiService.delete(Collection.PRODUCT_VARIANTS, result.documentId)
1988 }
1989 }
1990 )
1991 ```
1992
1993 The step receives the product variants to create in Strapi. In the step, you create each variant in Strapi using the Strapi Module's service.
1994
1995 In the compensation function, you delete all the created variants in Strapi if an error occurs during the workflow's execution.
1996
1997 #### updateProductVariantsMetadataStep
1998
1999 The `updateProductVariantsMetadataStep` stores the Strapi IDs of the created product variants in the `metadata` property of the corresponding product variants in Medusa. This allows you to reference the Strapi variants later, such as when updating or deleting them.
2000
2001 To create the step, create the file `src/workflows/steps/update-product-variants-metadata.ts` with the following content:
2002
2003 ```ts title="src/workflows/steps/update-product-variants-metadata.ts" badgeLabel="Medusa application" badgeColor="green"
2004 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2005 import { Modules } from "@medusajs/framework/utils"
2006 import { ProductVariantDTO } from "@medusajs/framework/types"
2007
2008 export type UpdateProductVariantsMetadataInput = {
2009 updates: {
2010 variantId: string
2011 strapiId: number
2012 strapiDocumentId: string
2013 }[]
2014 }
2015
2016 export const updateProductVariantsMetadataStep = createStep(
2017 "update-product-variants-metadata",
2018 async ({ updates }: UpdateProductVariantsMetadataInput, { container }) => {
2019 const productModuleService = container.resolve(Modules.PRODUCT)
2020
2021 const updatedVariants: ProductVariantDTO[] = []
2022
2023 // Fetch original metadata for compensation
2024 const originalVariants = await productModuleService.listProductVariants({
2025 id: updates.map((u) => u.variantId),
2026 })
2027
2028 // Update each variant's metadata
2029 for (const update of updates) {
2030 const variant = originalVariants.find((v) => v.id === update.variantId)
2031 if (variant) {
2032
2033 const updated = await productModuleService.updateProductVariants(
2034 update.variantId,
2035 {
2036 metadata: {
2037 ...variant.metadata,
2038 strapi_id: update.strapiId,
2039 strapi_document_id: update.strapiDocumentId,
2040 },
2041 }
2042 )
2043
2044 updatedVariants.push(updated)
2045
2046 }
2047 }
2048
2049 return new StepResponse(updatedVariants, originalVariants)
2050 },
2051 async (compensationData, { container }) => {
2052 if (!compensationData) {
2053 return
2054 }
2055
2056 const productModuleService = container.resolve(Modules.PRODUCT)
2057
2058 // Restore original metadata
2059 for (const original of compensationData) {
2060 await productModuleService.updateProductVariants(original.id, {
2061 metadata: original.metadata,
2062 })
2063 }
2064 }
2065 )
2066 ```
2067
2068 This step receives an array of variants to update with their corresponding Strapi IDs.
2069
2070 In the step, you resolve the Product Module's service and update each variant's `metadata` property with the Strapi ID and document ID.
2071
2072 In the compensation function, you restore the original metadata of the variants if an error occurs during the workflow's execution.
2073
2074 #### Create Product Variants Workflow
2075
2076 Now that you have created the necessary steps, you can create the workflow.
2077
2078 To create the workflow, create the file `src/workflows/create-variants-in-strapi.ts` with the following content:
2079
2080 ```ts title="src/workflows/create-variants-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green" collapsibleLines="1-12" expandButtonLabel="Show Imports"
2081 import {
2082 createWorkflow,
2083 WorkflowResponse,
2084 transform,
2085 when,
2086 } from "@medusajs/framework/workflows-sdk"
2087 import { acquireLockStep, releaseLockStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
2088 import { CreateVariantsInStrapiInput } from "./steps/create-variants-in-strapi"
2089 import { createVariantsInStrapiStep } from "./steps/create-variants-in-strapi"
2090 import { uploadImagesToStrapiStep } from "./steps/upload-images-to-strapi"
2091 import { updateProductVariantsMetadataStep } from "./steps/update-product-variants-metadata"
2092
2093 export type CreateVariantsInStrapiWorkflowInput = {
2094 ids: string[]
2095 productId: string
2096 }
2097
2098 export const createVariantsInStrapiWorkflow = createWorkflow(
2099 "create-variants-in-strapi",
2100 (input: CreateVariantsInStrapiWorkflowInput) => {
2101 acquireLockStep({
2102 key: ["strapi-product-create", input.productId],
2103 })
2104 // Fetch the variant with all necessary fields including option values
2105 const { data: variants } = useQueryGraphStep({
2106 entity: "product_variant",
2107 fields: [
2108 "id",
2109 "title",
2110 "sku",
2111 "product_id",
2112 "product.metadata",
2113 "product.options.id",
2114 "product.options.values.id",
2115 "product.options.values.value",
2116 "product.options.values.metadata",
2117 "product.strapi_product.*",
2118 "images.*",
2119 "thumbnail",
2120 "options.*",
2121 ],
2122 filters: {
2123 id: input.ids,
2124 },
2125 options: {
2126 throwIfKeyNotFound: true,
2127 },
2128 })
2129
2130 const strapiVariants = when(
2131 "sync-strapi-variants",
2132 { variants },
2133 (data) => !!(data.variants[0].product as any)?.strapi_product
2134 ).then(() => {
2135 const variantImages = transform({
2136 variants,
2137 }, (data) => {
2138 return data.variants.flatMap((variant) => variant.images?.map(
2139 (image) => ({
2140 entity_id: variant.id,
2141 url: image.url,
2142 })
2143 ) || [])
2144 })
2145 const variantThumbnail = transform({
2146 variants,
2147 }, (data) => {
2148 return data.variants
2149 // @ts-ignore
2150 .filter((variant) => !!variant.thumbnail)
2151 .flatMap((variant) => ({
2152 entity_id: variant.id,
2153 // @ts-ignore
2154 url: variant.thumbnail!,
2155 }))
2156 })
2157
2158 const strapiVariantImages = uploadImagesToStrapiStep({
2159 items: variantImages,
2160 })
2161
2162 const strapiVariantThumbnail = uploadImagesToStrapiStep({
2163 items: variantThumbnail,
2164 }).config({ name: "upload-variant-thumbnail" })
2165
2166 const variantsData = transform({
2167 variants,
2168 strapiVariantImages,
2169 strapiVariantThumbnail,
2170 }, (data) => {
2171 const varData = data.variants.map((variant) => ({
2172 id: variant.id,
2173 title: variant.title,
2174 sku: variant.sku,
2175 strapiProductId: Number(variant.product?.metadata?.strapi_id),
2176 strapiVariantImages: data.strapiVariantImages
2177 .filter((image) => image.entity_id === variant.id)
2178 .map((image) => image.image_id),
2179 strapiVariantThumbnail: data.strapiVariantThumbnail
2180 .find((image) => image.entity_id === variant.id)?.image_id,
2181 optionValueIds: variant.options.flatMap((option) => {
2182 // find the strapi option value id for the option value
2183 return variant.product?.options.flatMap(
2184 (productOption) => productOption.values.find(
2185 (value) => value.value === option.value
2186 )?.metadata?.strapi_id).filter((value) => value !== undefined)
2187 }),
2188 }))
2189
2190 return varData
2191 })
2192
2193 const strapiVariants = createVariantsInStrapiStep({
2194 variants: variantsData,
2195 } as CreateVariantsInStrapiInput)
2196
2197 const variantsMetadataUpdate = transform({ strapiVariants }, (data) => {
2198 return {
2199 updates: data.strapiVariants.map((strapiVariant) => ({
2200 variantId: strapiVariant.medusaId,
2201 strapiId: strapiVariant.id,
2202 strapiDocumentId: strapiVariant.documentId,
2203 })),
2204 }
2205 })
2206
2207 updateProductVariantsMetadataStep(variantsMetadataUpdate)
2208
2209 return strapiVariants
2210 })
2211
2212 releaseLockStep({
2213 key: ["strapi-product-create", input.productId],
2214 })
2215
2216 return new WorkflowResponse({
2217 variants: strapiVariants,
2218 })
2219 }
2220 )
2221 ```
2222
2223 The workflow receives the IDs of the product variants to create in Strapi and the Medusa product ID they belong to.
2224
2225 In the workflow, you:
2226
2227 1. Acquire a [lock](../../../infrastructure-modules/locking/page.mdx) to prevent concurrent creation of variants for the same product. This is necessary to handle both the product and variant creation events without duplications.
2228 2. Retrieve the product variants in Medusa using the `useQueryGraphStep`.
2229 3. Check if the product has been created in Strapi using [when](!docs!/learn/fundamentals/workflows/conditions). If so, you:
2230 - Prepare the variant images to upload using `transform`.
2231 - Prepare the variant thumbnail to upload using `transform`.
2232 - Upload the variant images to Strapi using the `uploadImagesToStrapiStep`.
2233 - Upload the variant thumbnail to Strapi using the `uploadImagesToStrapiStep`.
2234 - Prepare the variant data to create using `transform`.
2235 - Create the product variants in Strapi using the `createVariantsInStrapiStep`.
2236 - Prepare the data to update the variants' metadata using `transform`.
2237 - Update the variants' metadata using the `updateProductVariantsMetadataStep`.
2238 4. Release the acquired lock.
2239
2240 <Note>
2241
2242 In a workflow, you can't perform steps based on conditions because Medusa stores an internal representation of the workflow on application startup. Learn more in the [Conditions in Workflows](!docs!/learn/fundamentals/workflows/conditions) documentation.
2243
2244 </Note>
2245
2246 ### c. Create Product Creation Workflow
2247
2248 Now that you have created the necessary sub-workflows, you can create the main workflow to handle product creation in Strapi.
2249
2250 The workflow to create products in Strapi has the following steps:
2251
2252 <WorkflowDiagram
2253 workflow={{
2254 name: "createProductInStrapiWorkflow",
2255 steps: [
2256 {
2257 type: "step",
2258 name: "acquireLockStep",
2259 description: "Acquire a lock to prevent concurrent creation of product variants",
2260 link: "/references/medusa-workflows/steps/acquireLockStep",
2261 depth: 1
2262 },
2263 {
2264 type: "step",
2265 name: "useQueryGraphStep",
2266 description: "Retrieve product data.",
2267 link: "/references/helper-steps/useQueryGraphStep",
2268 depth: 2
2269 },
2270 {
2271 type: "step",
2272 name: "uploadImagesToStrapiStep",
2273 description: "Upload product images to Strapi.",
2274 depth: 3
2275 },
2276 {
2277 type: "when",
2278 steps: [
2279 {
2280 type: "step",
2281 name: "uploadImagesToStrapiStep",
2282 description: "Upload product thumbnail to Strapi if it exists.",
2283 depth: 1
2284 }
2285 ],
2286 depth: 4
2287 },
2288 {
2289 type: "step",
2290 name: "createProductInStrapiStep",
2291 description: "Create the product in Strapi.",
2292 depth: 5
2293 },
2294 {
2295 type: "workflow",
2296 name: "updateProductsWorkflow",
2297 description: "Update the product's `metadata` with the Strapi ID.",
2298 link: "/references/medusa-workflows/updateProductsWorkflow",
2299 depth: 6
2300 },
2301 {
2302 type: "step",
2303 name: "retrieveFromStrapiStep",
2304 description: "Retrieve existing product options from Strapi.",
2305 depth: 7
2306 },
2307 {
2308 type: "when",
2309 steps: [
2310 {
2311 type: "workflow",
2312 name: "createOptionsInStrapiWorkflow",
2313 description: "Create the product options in Strapi.",
2314 depth: 1
2315 }
2316 ],
2317 depth: 8,
2318 },
2319 {
2320 type: "when",
2321 steps: [
2322 {
2323 type: "step",
2324 name: "updateProductInStrapiStep",
2325 description: "Update the product in Strapi with the option IDs.",
2326 depth: 1
2327 }
2328 ],
2329 depth: 9
2330 },
2331 {
2332 type: "step",
2333 name: "releaseLockStep",
2334 description: "Release the acquired lock",
2335 link: "/references/medusa-workflows/steps/releaseLockStep",
2336 depth: 10
2337 },
2338 {
2339 type: "workflow",
2340 name: "createVariantsInStrapiWorkflow",
2341 description: "Create the product variants in Strapi.",
2342 depth: 11
2343 }
2344 ]
2345 }}
2346 hideLegend
2347 />
2348
2349 You need to create the `createProductInStrapiStep`, `retrieveFromStrapiStep`, and `updateProductInStrapiStep` steps. The rest of the steps and workflows are either available out-of-the-box in Medusa or you have already created them.
2350
2351 #### retrieveFromStrapiStep
2352
2353 The `retrieveFromStrapiStep` retrieves items from Strapi by their Medusa IDs.
2354
2355 To create the step, create the file `src/workflows/steps/retrieve-from-strapi.ts` with the following content:
2356
2357 ```ts title="src/workflows/steps/retrieve-from-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
2358 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2359 import { STRAPI_MODULE } from "../../modules/strapi"
2360 import StrapiModuleService, { Collection } from "../../modules/strapi/service"
2361
2362 export type RetrieveFromStrapiInput = {
2363 collection: Collection
2364 ids: string[]
2365 populate?: string[]
2366 }
2367
2368 export const retrieveFromStrapiStep = createStep(
2369 "retrieve-from-strapi",
2370 async ({ collection, ids, populate }: RetrieveFromStrapiInput, { container }) => {
2371 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
2372
2373 const items = await strapiService.findByMedusaId(collection, ids, populate)
2374
2375 return new StepResponse(items)
2376 }
2377 )
2378 ```
2379
2380 The step receives a collection name, an array of Medusa IDs, and an optional array of fields to populate.
2381
2382 In the step, you use the Strapi Module's service `findByMedusaId` method to retrieve items from Strapi.
2383
2384 #### updateProductInStrapiStep
2385
2386 The `updateProductInStrapiStep` updates a product in Strapi.
2387
2388 To create the step, create the file `src/workflows/steps/update-product-in-strapi.ts` with the following content:
2389
2390 ```ts title="src/workflows/steps/update-product-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
2391 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2392 import { STRAPI_MODULE } from "../../modules/strapi"
2393 import StrapiModuleService, { Collection } from "../../modules/strapi/service"
2394
2395 export type UpdateProductInStrapiInput = {
2396 product: {
2397 id: string
2398 title?: string
2399 subtitle?: string
2400 description?: string
2401 handle?: string
2402 optionIds?: number[]
2403 }
2404 }
2405
2406 export const updateProductInStrapiStep = createStep(
2407 "update-product-in-strapi",
2408 async ({ product }: UpdateProductInStrapiInput, { container }) => {
2409 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
2410
2411 // Fetch current Strapi product data for compensation
2412 const [originalProduct] = await strapiService.findByMedusaId(Collection.PRODUCTS, product.id, ["options"])
2413
2414 // Update product in Strapi
2415 const updateData: Record<string, any> = {}
2416 if (product.title !== undefined) {updateData.title = product.title}
2417 if (product.subtitle !== undefined) {updateData.subtitle = product.subtitle}
2418 if (product.description !== undefined) {updateData.description = product.description}
2419 if (product.handle !== undefined) {updateData.handle = product.handle}
2420 if (product.optionIds !== undefined) {updateData.options = product.optionIds}
2421
2422 const updated = await strapiService.update(Collection.PRODUCTS, originalProduct.documentId, updateData)
2423
2424 return new StepResponse(
2425 updated.data,
2426 originalProduct
2427 )
2428 },
2429 async (compensationData, { container }) => {
2430 if (!compensationData) {
2431 return
2432 }
2433
2434 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
2435
2436 await strapiService.update(Collection.PRODUCTS, compensationData.documentId, {
2437 title: compensationData.title,
2438 subtitle: compensationData.subtitle,
2439 description: compensationData.description,
2440 handle: compensationData.handle,
2441 options: compensationData.options?.map((opt) => opt.id) || [],
2442 })
2443 }
2444 )
2445 ```
2446
2447 The step receives a product object with an ID and optional fields to update (title, subtitle, description, handle, and optionIds). It finds the Strapi product by its Medusa ID and updates it with the provided details.
2448
2449 In the compensation function, you restore the original product data if an error occurs during the workflow's execution.
2450
2451 #### createProductInStrapiStep
2452
2453 The `createProductInStrapiStep` creates a product in Strapi.
2454
2455 To create the step, create the file `src/workflows/steps/create-product-in-strapi.ts` with the following content:
2456
2457 ```ts title="src/workflows/steps/create-product-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
2458 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2459 import { STRAPI_MODULE } from "../../modules/strapi"
2460 import StrapiModuleService, { Collection } from "../../modules/strapi/service"
2461
2462 export type CreateProductInStrapiInput = {
2463 product: {
2464 id: string
2465 title: string
2466 subtitle?: string
2467 description?: string
2468 handle: string
2469 imageIds?: number[]
2470 thumbnailId?: number
2471 }
2472 }
2473
2474 export const createProductInStrapiStep = createStep(
2475 "create-product-in-strapi",
2476 async ({ product }: CreateProductInStrapiInput, { container }) => {
2477 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
2478
2479 // Create product in Strapi
2480 const strapiProduct = await strapiService.create(Collection.PRODUCTS, {
2481 medusaId: product.id,
2482 title: product.title,
2483 subtitle: product.subtitle,
2484 description: product.description,
2485 handle: product.handle,
2486 images: product.imageIds || [],
2487 thumbnail: product.thumbnailId,
2488 })
2489
2490 return new StepResponse(
2491 strapiProduct.data,
2492 strapiProduct.data
2493 )
2494 },
2495 async (compensationData, { container }) => {
2496 if (!compensationData) {
2497 return
2498 }
2499
2500 const strapiService: StrapiModuleService = container.resolve(STRAPI_MODULE)
2501
2502 // Delete the product
2503 await strapiService.delete(Collection.PRODUCTS, compensationData.documentId)
2504 }
2505 )
2506 ```
2507
2508 The step receives the product to create in Strapi. In the step, you create the product in Strapi using the Strapi Module's service.
2509
2510 In the compensation function, you delete the created product in Strapi if an error occurs during the workflow's execution.
2511
2512 #### Create Product Workflow
2513
2514 Now that you have created the necessary steps, you can create the main workflow to handle product creation in Strapi.
2515
2516 To create the workflow, create the file `src/workflows/create-product-in-strapi.ts` with the following content:
2517
2518 ```ts title="src/workflows/create-product-in-strapi.ts" badgeLabel="Medusa application" badgeColor="green"
2519 import {
2520 createWorkflow,
2521 WorkflowResponse,
2522 transform,
2523 when,
2524 } from "@medusajs/framework/workflows-sdk"
2525 import {
2526 CreateProductInStrapiInput,
2527 createProductInStrapiStep,
2528 } from "./steps/create-product-in-strapi"
2529 import { uploadImagesToStrapiStep } from "./steps/upload-images-to-strapi"
2530 import {
2531 useQueryGraphStep,
2532 updateProductsWorkflow,
2533 acquireLockStep,
2534 releaseLockStep,
2535 } from "@medusajs/medusa/core-flows"
2536 import { createOptionsInStrapiWorkflow } from "./create-options-in-strapi"
2537 import { createVariantsInStrapiWorkflow } from "./create-variants-in-strapi"
2538 import { updateProductInStrapiStep } from "./steps/update-product-in-strapi"
2539 import { retrieveFromStrapiStep } from "./steps/retrieve-from-strapi"
2540 import { Collection } from "../modules/strapi/service"
2541
2542 export type CreateProductInStrapiWorkflowInput = {
2543 id: string
2544 }
2545
2546 export const createProductInStrapiWorkflow = createWorkflow(
2547 "create-product-in-strapi",
2548 (input: CreateProductInStrapiWorkflowInput) => {
2549 acquireLockStep({
2550 key: ["strapi-product-create", input.id],
2551 timeout: 60,
2552 })
2553 const { data: products } = useQueryGraphStep({
2554 entity: "product",
2555 fields: [
2556 "id",
2557 "title",
2558 "subtitle",
2559 "description",
2560 "handle",
2561 "images.url",
2562 "thumbnail",
2563 "variants.id",
2564 "options.id",
2565 ],
2566 filters: {
2567 id: input.id,
2568 },
2569 options: {
2570 throwIfKeyNotFound: true,
2571 },
2572 })
2573
2574 const productImages = transform({ products }, (data) => {
2575 return data.products[0].images.map((image) => {
2576 return {
2577 entity_id: data.products[0].id,
2578 url: image.url,
2579 }
2580 })
2581 })
2582
2583 const strapiProductImages = uploadImagesToStrapiStep({
2584 items: productImages,
2585 })
2586
2587 const strapiProductThumbnail = when(
2588 ({ products }),
2589 // @ts-ignore
2590 (data) => !!data.products[0].thumbnail
2591 ).then(() => {
2592 return uploadImagesToStrapiStep({
2593 items: [{
2594 entity_id: products[0].id,
2595 url: products[0].thumbnail!,
2596 }],
2597 }).config({ name: "upload-product-thumbnail" })
2598 })
2599
2600 const productWithImages = transform(
2601 { strapiProductImages, strapiProductThumbnail, products },
2602 (data) => {
2603 return {
2604 id: data.products[0].id,
2605 title: data.products[0].title,
2606 subtitle: data.products[0].subtitle,
2607 description: data.products[0].description,
2608 handle: data.products[0].handle,
2609 imageIds: data.strapiProductImages.map((image) => image.image_id),
2610 thumbnailId: data.strapiProductThumbnail?.[0]?.image_id,
2611 }
2612 }
2613 )
2614
2615 const strapiProduct = createProductInStrapiStep({
2616 product: productWithImages,
2617 } as CreateProductInStrapiInput)
2618
2619 const productMetadataUpdate = transform({ strapiProduct }, (data) => {
2620 return {
2621 selector: { id: data.strapiProduct.medusaId },
2622 update: {
2623 metadata: {
2624 strapi_id: data.strapiProduct.id,
2625 strapi_document_id: data.strapiProduct.documentId,
2626 },
2627 },
2628 }
2629 })
2630
2631 updateProductsWorkflow.runAsStep({
2632 input: productMetadataUpdate,
2633 })
2634
2635 const variantIds = transform({
2636 products,
2637 }, (data) => data.products[0].variants.map((variant) => variant.id))
2638 const optionIds = transform({
2639 products,
2640 }, (data) => data.products[0].options.map((option) => option.id))
2641
2642 const existingStrapiOptions = retrieveFromStrapiStep({
2643 collection: Collection.PRODUCT_OPTIONS,
2644 ids: optionIds,
2645 })
2646
2647 const optionsToCreate = transform({ existingStrapiOptions, optionIds }, (data) => {
2648 const existingMedusaIds = new Set(data.existingStrapiOptions.map((option) => option.medusaId))
2649 return data.optionIds.filter((id: string) => !existingMedusaIds.has(id))
2650 })
2651
2652 const newStrapiOptions = when({ optionsToCreate }, (data) => data.optionsToCreate.length > 0).then(() => {
2653 return createOptionsInStrapiWorkflow.runAsStep({
2654 input: {
2655 ids: optionsToCreate,
2656 },
2657 })
2658 })
2659
2660 const strapiOptionIds = transform({ existingStrapiOptions, newStrapiOptions }, (data): number[] => {
2661 const existingIds = (data.existingStrapiOptions || []).map((option) => option.id).filter(Boolean) as number[]
2662 const newIds = data.newStrapiOptions ? (data.newStrapiOptions.strapi_options || []).map((option) => option.id).filter(Boolean) as number[] : []
2663 return [...existingIds, ...newIds]
2664 })
2665
2666 when({ strapiOptionIds }, (data) => data.strapiOptionIds.length > 0).then(() => {
2667 return updateProductInStrapiStep({
2668 product: {
2669 id: input.id,
2670 optionIds: strapiOptionIds,
2671 },
2672 })
2673 })
2674
2675 releaseLockStep({
2676 key: ["strapi-product-create", input.id],
2677 })
2678
2679 createVariantsInStrapiWorkflow.runAsStep({
2680 input: {
2681 ids: variantIds,
2682 productId: input.id,
2683 },
2684 })
2685
2686 return new WorkflowResponse(strapiProduct)
2687 }
2688 )
2689 ```
2690
2691 The workflow receives the ID of the product to create in Strapi.
2692
2693 In the workflow, you:
2694
2695 1. Acquire a [lock](../../../infrastructure-modules/locking/page.mdx) to prevent concurrent creation of variants for the same product. This is necessary to handle both the product and variant creation events. Otherwise, variants might be created multiple times.
2696 2. Retrieve the product in Medusa using the `useQueryGraphStep`.
2697 3. Prepare the product images to upload using `transform`.
2698 4. Upload the product images to Strapi using the `uploadImagesToStrapiStep`.
2699 5. Check if the product has a thumbnail using `when`. If so, you upload the thumbnail to Strapi using the `uploadImagesToStrapiStep`.
2700 6. Prepare the product data to create using `transform`.
2701 7. Create the product in Strapi using the `createProductInStrapiStep`.
2702 8. Prepare the data to update the product's metadata using `transform`.
2703 9. Update the product's metadata using the `updateProductsWorkflow`.
2704 10. Prepare the IDs of the product options and variants using `transform`.
2705 11. Check for existing product options in Strapi using `retrieveFromStrapiStep`.
2706 12. Identify which options need to be created using `transform`.
2707 13. Create only the product options that don't exist yet using the `createOptionsInStrapiWorkflow` (conditionally with `when`).
2708 14. Combine existing and newly created option IDs using `transform`.
2709 15. Link existing and newly created options to the product using `updateProductInStrapiStep` (conditionally with `when`).
2710 16. Release the acquired lock.
2711 17. Create the product variants in Strapi using the `createVariantsInStrapiWorkflow`.
2712
2713 The workflow returns the created Strapi product as a response.
2714
2715 ### d. Create Product Created Subscriber
2716
2717 Finally, you need to create a subscriber that listens to the product creation event in Medusa and triggers the `createProductInStrapiWorkflow`.
2718
2719 A subscriber is an asynchronous function that is executed whenever its associated event is emitted.
2720
2721 <Note>
2722
2723 Refer to the [Subscribers documentation](!docs!/learn/fundamentals/events-and-subscribers) to learn more about subscribers.
2724
2725 </Note>
2726
2727 To create the subscriber, create the file `src/subscribers/product-created-strapi-sync.ts` with the following content:
2728
2729 ```ts title="src/subscribers/product-created-strapi-sync.ts" badgeLabel="Medusa application" badgeColor="green"
2730 import {
2731 type SubscriberConfig,
2732 type SubscriberArgs,
2733 } from "@medusajs/framework"
2734 import { createProductInStrapiWorkflow } from "../workflows/create-product-in-strapi"
2735
2736 export default async function productCreatedStrapiSyncHandler({
2737 event: { data },
2738 container,
2739 }: SubscriberArgs<{ id: string }>) {
2740 await createProductInStrapiWorkflow(container).run({
2741 input: {
2742 id: data.id,
2743 },
2744 })
2745 }
2746
2747 export const config: SubscriberConfig = {
2748 event: "product.created",
2749 }
2750 ```
2751
2752 A subscriber file must export:
2753
2754 - An asynchronous function, which is the subscriber function that is executed when the event is emitted.
2755 - A configuration object that defines the event the subscriber listens to, which is `product.created` in this case.
2756
2757 In the subscriber function, you run the `createProductInStrapiWorkflow`, passing the ID of the created product as input.
2758
2759 ### Test Product Creation
2760
2761 Now that you have implemented the product creation workflow and subscriber, you can test the integration.
2762
2763 First, run the following command in the Strapi application's directory to start the Strapi server:
2764
2765 ```bash npm2yarn badgeLabel="Strapi" badgeColor="orange"
2766 npm run develop
2767 ```
2768
2769 Then, run the following command in the `apps/backend` directory to start the Medusa server:
2770
2771 ```bash npm2yarn
2772 npm run dev
2773 ```
2774
2775 Next, open the Medusa Admin dashboard and [create a new product](!user-guide!/products/create). Once you create the product, you'll see the following in the Medusa server logs:
2776
2777 ```bash
2778 info: Processing product.created which has 1 subscribers
2779 ```
2780
2781 This indicates that the subscriber has been triggered.
2782
2783 Then, open the Strapi Admin dashboard and navigate to the Products collection. You should see the newly created product in the list.
2784
2785 ---
2786
2787 ## Step 6: Handle Strapi Product Updates
2788
2789 Next, you'll handle product updates in Strapi and synchronize the changes back to Medusa. You'll create a workflow to update the relevant product data in Medusa based on the data received from Strapi.
2790
2791 Then, you'll create an API route webhook that Strapi can call whenever product data is updated. With this setup, you'll have two-way synchronization between Medusa and Strapi for product data.
2792
2793 ### a. Handle Strapi Webhook Workflow
2794
2795 The workflow to handle Strapi webhooks has the following steps:
2796
2797 <WorkflowDiagram
2798 workflow={{
2799 name: "handleStrapiWebhookWorkflow",
2800 steps: [
2801 {
2802 type: "step",
2803 name: "prepareStrapiUpdateDataStep",
2804 description: "Prepare the product update data from the Strapi webhook payload.",
2805 depth: 1
2806 },
2807 {
2808 type: "when",
2809 steps: [
2810 {
2811 type: "workflow",
2812 name: "updateProductsWorkflow",
2813 description: "If the data updated in Strapi is product data, update the product in Medusa.",
2814 link: "/references/medusa-workflows/updateProductsWorkflow",
2815 depth: 1
2816 },
2817 {
2818 type: "step",
2819 name: "clearProductCacheStep",
2820 description: "Clear the product cache to ensure updated data is served to clients.",
2821 depth: 2
2822 },
2823 ],
2824 depth: 2
2825 },
2826 {
2827 type: "when",
2828 steps: [
2829 {
2830 type: "workflow",
2831 name: "updateProductVariantsWorkflow",
2832 description: "If the data updated in Strapi is product variant data, update the product variant in Medusa.",
2833 link: "/references/medusa-workflows/updateProductVariantsWorkflow",
2834 depth: 1
2835 },
2836 {
2837 type: "step",
2838 name: "clearProductCacheStep",
2839 description: "Clear the product cache to ensure updated data is served to clients.",
2840 depth: 2
2841 }
2842 ],
2843 depth: 3
2844 },
2845 {
2846 type: "when",
2847 steps: [
2848 {
2849 type: "workflow",
2850 name: "updateProductOptionsWorkflow",
2851 description: "If the data updated in Strapi is product option data, update the product option in Medusa.",
2852 link: "/references/medusa-workflows/updateProductOptionsWorkflow",
2853 depth: 1
2854 },
2855 {
2856 type: "step",
2857 name: "clearProductCacheStep",
2858 description: "Clear the product cache to ensure updated data is served to clients.",
2859 depth: 2
2860 }
2861 ],
2862 depth: 4
2863 },
2864 {
2865 type: "when",
2866 steps: [
2867 {
2868 type: "step",
2869 name: "updateProductOptionValueStep",
2870 description: "If the data updated in Strapi is product option value data, update the product option value in Medusa.",
2871 depth: 1
2872 },
2873 {
2874 type: "step",
2875 name: "clearProductCacheStep",
2876 description: "Clear the product cache to ensure updated data is served to clients.",
2877 depth: 2
2878 }
2879 ]
2880 }
2881 ]
2882 }}
2883 hideLegend
2884 />
2885
2886 You only need to create the `prepareStrapiUpdateDataStep`, `clearProductCacheStep`, and `updateProductOptionValueStep` steps. The rest of the steps and workflows are available out-of-the-box in Medusa.
2887
2888 #### prepareStrapiUpdateDataStep
2889
2890 The `prepareStrapiUpdateDataStep` extracts the data to update from the Strapi webhook payload.
2891
2892 To create the step, create the file `src/workflows/steps/prepare-strapi-update-data.ts` with the following content:
2893
2894 ```ts title="src/workflows/steps/prepare-strapi-update-data.ts" badgeLabel="Medusa application" badgeColor="green"
2895 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2896
2897 export const prepareStrapiUpdateDataStep = createStep(
2898 "prepare-strapi-update-data",
2899 async ({ entry }: { entry: any }) => {
2900 let data: Record<string, unknown> = {}
2901 const model = entry.model
2902
2903 switch (model) {
2904 case "product":
2905 data = {
2906 id: entry.entry.medusaId,
2907 title: entry.entry.title,
2908 subtitle: entry.entry.subtitle,
2909 description: entry.entry.description,
2910 handle: entry.entry.handle,
2911 }
2912 break
2913 case "product-variant":
2914 data = {
2915 id: entry.entry.medusaId,
2916 title: entry.entry.title,
2917 sku: entry.entry.sku,
2918 }
2919 break
2920 case "product-option":
2921 data = {
2922 selector: {
2923 id: entry.entry.medusaId,
2924 },
2925 update: {
2926 title: entry.entry.title,
2927 },
2928 }
2929 break
2930 case "product-option-value":
2931 data = {
2932 optionValueId: entry.entry.medusaId,
2933 value: entry.entry.value,
2934 }
2935 break
2936 }
2937
2938 return new StepResponse({ data, model })
2939 }
2940 )
2941 ```
2942
2943 The step receives the Strapi webhook payload containing the updated entry.
2944
2945 In the step, you extract the relevant data based on the model type (product, product variant, product option, or product option value) and return it.
2946
2947 #### clearProductCacheStep
2948
2949 The `clearProductCacheStep` clears the product cache in Medusa to ensure that updated data is served to clients. This is necessary as you'll enable [caching](../../../infrastructure-modules/caching/page.mdx) later, which may cause stale data to be served to the storefront.
2950
2951 To create the step, create the file `src/workflows/steps/clear-product-cache.ts` with the following content:
2952
2953 ```ts title="src/workflows/steps/clear-product-cache.ts" badgeLabel="Medusa application" badgeColor="green"
2954 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2955 import { Modules } from "@medusajs/framework/utils"
2956
2957 type ClearProductCacheInput = {
2958 productId: string | string[]
2959 }
2960
2961 export const clearProductCacheStep = createStep(
2962 "clear-product-cache",
2963 async ({ productId }: ClearProductCacheInput, { container }) => {
2964 const cachingModuleService = container.resolve(Modules.CACHING)
2965
2966 const productIds = Array.isArray(productId) ? productId : [productId]
2967
2968 // Clear cache for all specified products
2969 for (const id of productIds) {
2970 if (id) {
2971 await cachingModuleService.clear({
2972 tags: [`Product:${id}`],
2973 })
2974 }
2975 }
2976
2977 return new StepResponse({})
2978 }
2979 )
2980 ```
2981
2982 The step receives the ID or IDs of the products to clear the cache for.
2983
2984 In the step, you clear the cache for each specified product using the Caching Module's service.
2985
2986 #### updateProductOptionValueStep
2987
2988 The `updateProductOptionValueStep` updates product option values in Medusa based on the data received from Strapi.
2989
2990 To create the step, create the file `src/workflows/steps/update-product-option-value.ts` with the following content:
2991
2992 ```ts title="src/workflows/steps/update-product-option-value.ts" badgeLabel="Medusa application" badgeColor="green"
2993 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2994 import { Modules } from "@medusajs/framework/utils"
2995 import { IProductModuleService } from "@medusajs/framework/types"
2996
2997 type UpdateProductOptionValueInput = {
2998 id: string
2999 value: string
3000 }
3001
3002 export const updateProductOptionValueStep = createStep(
3003 "update-product-option-value",
3004 async ({ id, value }: UpdateProductOptionValueInput, { container }) => {
3005 const productModuleService: IProductModuleService = container.resolve(
3006 Modules.PRODUCT
3007 )
3008
3009 // Store the old value for compensation
3010 const oldOptionValue = await productModuleService
3011 .retrieveProductOptionValue(id)
3012
3013 // Update the option value
3014 const updatedOptionValue = await productModuleService
3015 .updateProductOptionValues(
3016 id,
3017 {
3018 value,
3019 }
3020 )
3021
3022 return new StepResponse(updatedOptionValue, oldOptionValue)
3023 },
3024 async (compensateData, { container }) => {
3025 if (!compensateData) {
3026 return
3027 }
3028
3029 const productModuleService: IProductModuleService = container.resolve(
3030 Modules.PRODUCT
3031 )
3032
3033 // Revert the option value to its old value
3034 await productModuleService.updateProductOptionValues(
3035 compensateData.id,
3036 {
3037 value: compensateData.value,
3038 }
3039 )
3040 }
3041 )
3042 ```
3043
3044 The step receives the ID of the option value to update and the new value.
3045
3046 In the step, you resolve the Product Module's service and update the option value in Medusa.
3047
3048 In the compensation function, you revert the option value to its old value if an error occurs during the workflow's execution.
3049
3050 #### Handle Strapi Webhook Workflow
3051
3052 Now that you have created the necessary steps, you can create the workflow to handle Strapi webhooks.
3053
3054 To create the workflow, create the file `src/workflows/handle-strapi-webhook.ts` with the following content:
3055
3056 ```ts title="src/workflows/handle-strapi-webhook.ts" badgeLabel="Medusa application" badgeColor="green" collapsibleLines="1-19" expandButtonLabel="Show Imports"
3057 import {
3058 createWorkflow,
3059 when,
3060 transform,
3061 } from "@medusajs/framework/workflows-sdk"
3062 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
3063 import { prepareStrapiUpdateDataStep } from "./steps/prepare-strapi-update-data"
3064 import { clearProductCacheStep } from "./steps/clear-product-cache"
3065 import { updateProductOptionValueStep } from "./steps/update-product-option-value"
3066 import {
3067 updateProductsWorkflow,
3068 updateProductVariantsWorkflow,
3069 updateProductOptionsWorkflow,
3070 } from "@medusajs/medusa/core-flows"
3071 import {
3072 UpsertProductDTO,
3073 UpsertProductVariantDTO,
3074 } from "@medusajs/framework/types"
3075
3076 export type WorkflowInput = {
3077 entry: any
3078 }
3079
3080 export const handleStrapiWebhookWorkflow = createWorkflow(
3081 "handle-strapi-webhook-workflow",
3082 (input: WorkflowInput) => {
3083 const preparedData = prepareStrapiUpdateDataStep({
3084 entry: input.entry,
3085 })
3086
3087 when(input, (input) => input.entry.model === "product")
3088 .then(() => {
3089 updateProductsWorkflow.runAsStep({
3090 input: {
3091 products: [preparedData.data as unknown as UpsertProductDTO],
3092 },
3093 })
3094
3095 // Clear the product cache after update
3096 const productId = transform({ preparedData }, (data) => {
3097 return (data.preparedData.data as any).id
3098 })
3099
3100 clearProductCacheStep({ productId })
3101 })
3102
3103 when(input, (input) => input.entry.model === "product-variant")
3104 .then(() => {
3105 const variants = updateProductVariantsWorkflow.runAsStep({
3106 input: {
3107 product_variants: [
3108 preparedData.data as unknown as UpsertProductVariantDTO,
3109 ],
3110 },
3111 })
3112
3113 clearProductCacheStep({
3114 productId: variants[0].product_id!,
3115 }).config({ name: "clear-product-cache-variant" })
3116 })
3117
3118 when(input, (input) => input.entry.model === "product-option")
3119 .then(() => {
3120 updateProductOptionsWorkflow.runAsStep({
3121 input: preparedData.data as any,
3122 })
3123
3124 // Since options can belong to multiple products (manyToMany),
3125 // we need to find all products that use this option
3126 const { data: products } = useQueryGraphStep({
3127 entity: "product",
3128 fields: ["id"],
3129 filters: {
3130 options: {
3131 id: (preparedData.data.selector as Record<string, string>).id,
3132 },
3133 },
3134 }).config({ name: "get-products-from-option" })
3135
3136 // Clear cache for all products that use this option
3137 const productIds = transform({ products }, (data) => {
3138 return data.products.map((p) => p.id) as string[]
3139 })
3140
3141 clearProductCacheStep({
3142 productId: productIds,
3143 }).config({ name: "clear-product-cache-option" })
3144 })
3145
3146 when(input, (input) => input.entry.model === "product-option-value")
3147 .then(() => {
3148 // Update the option value using the Product Module
3149 const optionValueData = transform({ preparedData }, (data) => ({
3150 id: data.preparedData.data.optionValueId as string,
3151 value: data.preparedData.data.value as string,
3152 }))
3153
3154 updateProductOptionValueStep(optionValueData)
3155
3156 // Find all variants that use this option value to
3157 // clear their product cache
3158 const { data: variants } = useQueryGraphStep({
3159 entity: "product_variant",
3160 fields: [
3161 "id",
3162 "product_id",
3163 ],
3164 filters: {
3165 options: {
3166 id: preparedData.data.optionValueId as string,
3167 },
3168 },
3169 }).config({ name: "get-variants-from-option-value" })
3170
3171 // Clear the product cache for all affected products
3172 const productIds = transform({ variants }, (data) => {
3173 const uniqueProductIds = [
3174 ...new Set(data.variants.map((v) => v.product_id)),
3175 ]
3176 return uniqueProductIds as string[]
3177 })
3178
3179 clearProductCacheStep({
3180 productId: productIds,
3181 }).config({ name: "clear-product-cache-option-value" })
3182 })
3183 }
3184 )
3185 ```
3186
3187 The workflow receives the Strapi webhook payload containing the updated entry.
3188
3189 In the workflow, you:
3190
3191 1. Prepare the update data using the `prepareStrapiUpdateDataStep`.
3192 2. Check if the updated model is a product using `when`. If so, you:
3193 - Update the product in Medusa using the `updateProductsWorkflow`.
3194 - Clear the product cache using the `clearProductCacheStep`.
3195 3. Check if the updated model is a product variant using `when`. If so, you
3196 - Update the product variant in Medusa using the `updateProductVariantsWorkflow`.
3197 - Clear the product cache using the `clearProductCacheStep`.
3198 4. Check if the updated model is a product option using `when`. If so, you:
3199 - Update the product option in Medusa using the `updateProductOptionsWorkflow`.
3200 - Clear the product cache using the `clearProductCacheStep`.
3201 5. Check if the updated model is a product option value using `when`. If so, you:
3202 - Update the product option value in Medusa using the `updateProductOptionValueStep`.
3203 - Retrieve all product variants that use the updated option value using the `useQueryGraphStep`.
3204 - Clear the product cache for all affected products using the `clearProductCacheStep`.
3205
3206 ### b. Create Strapi Webhook API Route
3207
3208 Next, you need to create an API route webhook that Strapi can call whenever product data is updated.
3209
3210 An [API route](!docs!/learn/fundamentals/api-routes) is an endpoint that exposes business logic and commerce features to clients.
3211
3212 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory. The path of the API route is the file's path relative to `src/api`.
3213
3214 <Note>
3215
3216 Refer to the [API routes](!docs!/learn/fundamentals/api-routes) to learn more about them.
3217
3218 </Note>
3219
3220 To create the API route, create the file `src/api/webhooks/strapi/route.ts` with the following content:
3221
3222 {/* eslint-disable @medusajs/no-service-mutations-in-api-route */}
3223
3224 ```ts title="src/api/webhooks/strapi/route.ts" badgeLabel="Medusa application" badgeColor="green"
3225 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
3226 import {
3227 simpleHash,
3228 Modules,
3229 ContainerRegistrationKeys,
3230 } from "@medusajs/framework/utils"
3231 import {
3232 handleStrapiWebhookWorkflow,
3233 WorkflowInput,
3234 } from "../../../workflows/handle-strapi-webhook"
3235
3236 export const POST = async (
3237 req: MedusaRequest,
3238 res: MedusaResponse
3239 ) => {
3240 const body = req.body as Record<string, unknown>
3241 const logger = req.scope.resolve(
3242 ContainerRegistrationKeys.LOGGER
3243 )
3244 const cachingService = req.scope.resolve(Modules.CACHING)
3245
3246 // Generate a hash of the webhook payload to detect duplicates
3247 const payloadHash = simpleHash(JSON.stringify(body))
3248 const cacheKey = `strapi-webhook:${payloadHash}`
3249
3250 // Check if we've already processed this webhook
3251 const alreadyProcessed = await cachingService.get({ key: cacheKey })
3252
3253 if (alreadyProcessed) {
3254 logger.debug(`Webhook already processed (hash: ${payloadHash}), skipping to prevent infinite loop`)
3255 res.status(200).send("OK - Already processed")
3256 return
3257 }
3258
3259 if (body.event === "entry.update") {
3260 const entry = body.entry as Record<string, unknown>
3261 const entityCacheKey = `strapi-update:${body.model}:${entry.medusaId}`
3262 await cachingService.set({
3263 key: entityCacheKey,
3264 data: { status: "processing", timestamp: Date.now() },
3265 ttl: 10,
3266 })
3267
3268 await handleStrapiWebhookWorkflow(req.scope).run({
3269 input: {
3270 entry: body,
3271 } as WorkflowInput,
3272 })
3273
3274 // Cache the hash to prevent reprocessing (TTL: 60 seconds)
3275 await cachingService.set({
3276 key: cacheKey,
3277 data: { status: "processed", timestamp: Date.now() },
3278 ttl: 60,
3279 })
3280 logger.debug(`Webhook processed and cached (hash: ${payloadHash})`)
3281 }
3282
3283 res.status(200).send("OK")
3284 }
3285 ```
3286
3287 Since you export `POST` function, you expose a `POST` API route at `/webhooks/strapi`.
3288
3289 In the API route, you:
3290
3291 1. Retrieve the webhook payload from the request body.
3292 2. Resolve the Caching Module's service.
3293 3. Generate a hash of the webhook payload to detect duplicate webhook calls. This is necessary since you've implemented two-way synchronization between Medusa and Strapi, which may lead to infinite loops of updates.
3294 4. If the hash exists in the cache, the webhook has already been processed, so you skip further processing and return a `200` response.
3295 5. If the webhook event is `entry.update`, you:
3296 - Cache the entity being updated to prevent concurrent updates.
3297 - Run the `handleStrapiWebhookWorkflow`, passing the webhook payload as input.
3298 - Cache the hash of the webhook payload to prevent reprocessing for 60 seconds.
3299
3300 ### c. Add Webhook Validation Middleware
3301
3302 To ensure that webhook requests are coming from your Strapi application, you'll add a [middleware](!docs!/learn/fundamentals/api-routes/middlewares) that validates the webhook requests.
3303
3304 To add the middleware, create the file `src/api/middlewares.ts` with the following content:
3305
3306 ```ts title="src/api/middlewares.ts" badgeLabel="Medusa application" badgeColor="green"
3307 import {
3308 defineMiddlewares,
3309 MedusaNextFunction,
3310 MedusaRequest,
3311 MedusaResponse,
3312 } from "@medusajs/framework/http"
3313 import { Modules } from "@medusajs/framework/utils"
3314
3315 export default defineMiddlewares({
3316 routes: [
3317 {
3318 matcher: "/webhooks/strapi",
3319 middlewares: [
3320 async (
3321 req: MedusaRequest,
3322 res: MedusaResponse,
3323 next: MedusaNextFunction
3324 ) => {
3325 const apiKeyModuleService = req.scope.resolve(
3326 Modules.API_KEY
3327 )
3328
3329 // Extract Bearer token from Authorization header
3330 const authHeader = req.headers["authorization"]
3331 const apiKey = authHeader?.replace("Bearer ", "")
3332
3333 if (!apiKey) {
3334 return res.status(401).json({
3335 message: "Unauthorized: Missing API key",
3336 })
3337 }
3338
3339 try {
3340 // Validate the API key using Medusa's API Key Module
3341 const isValid = await apiKeyModuleService.authenticate(apiKey)
3342
3343 if (!isValid) {
3344 return res.status(401).json({
3345 message: "Unauthorized: Invalid API key",
3346 })
3347 }
3348
3349 // API key is valid, proceed to route handler
3350 next()
3351 } catch (error) {
3352 return res.status(401).json({
3353 message: "Unauthorized: API key authentication failed",
3354 })
3355 }
3356 },
3357 ],
3358 },
3359 ],
3360 })
3361 ```
3362
3363 The middleware file must create middlewares with the `defineMiddlewares` function.
3364
3365 You define a middleware for the `/webhooks/strapi` route that:
3366
3367 1. Resolves the [API Key Module](../../../commerce-modules/api-key/page.mdx)'s service.
3368 2. Extracts the API key from the `Authorization` header.
3369 3. If the API key is missing, returns a `401 Unauthorized` response.
3370 4. Validates the API key using the API Key Module's service.
3371 5. If the API key is invalid, returns a `401 Unauthorized` response.
3372 6. Otherwise, calls the `next` function to proceed to the route handler.
3373
3374 ### d. Enable Caching in Medusa
3375
3376 <Prerequisites
3377 items={[
3378 {
3379 text: "Redis installed and Redis server running",
3380 link: "https://redis.io/docs/getting-started/installation/"
3381 }
3382 ]}
3383 />
3384
3385 The [Caching Module](../../../infrastructure-modules/caching/page.mdx) is currently guarded by a feature flag. To enable it, add the feature flag and module in your `medusa-config.ts` file:
3386
3387 ```ts title="medusa-config.ts" badgeLabel="Medusa application" badgeColor="green"
3388 module.exports = defineConfig({
3389 // ...
3390 modules: [
3391 // ...
3392 {
3393 resolve: "@medusajs/medusa/caching",
3394 options: {
3395 providers: [
3396 {
3397 resolve: "@medusajs/caching-redis",
3398 id: "caching-redis",
3399 options: {
3400 redisUrl: process.env.REDIS_URL,
3401 },
3402 },
3403 ],
3404 },
3405 },
3406 ],
3407 featureFlags: {
3408 caching: true,
3409 },
3410 })
3411 ```
3412
3413 This configuration enables the Caching Module with Redis as the caching provider. Make sure to set the `REDIS_URL` environment variable to point to your Redis server:
3414
3415 ```bash
3416 REDIS_URL=redis://localhost:6379
3417 ```
3418
3419 You can now use the Caching Module's service in your workflows and API routes. Medusa will also cache product and cart data automatically to improve performance.
3420
3421 ### e. Webhook Handling Preparation
3422
3423 Before you test the webhook handling, you need to create a secret API key in Medusa, then configure webhooks in Strapi.
3424
3425 Make sure to start both the Medusa and Strapi servers if they are not already running.
3426
3427 #### Create Secret API Key in Medusa
3428
3429 To create the secret API key in Medusa:
3430
3431 1. Open the Medusa Admin dashboard.
3432 2. Go to Settings -> Secret API Keys.
3433 3. Click on the "Create" button at the top right.
3434 4. Enter a name for the API key. For example, "Strapi".
3435 5. Click on the "Save" button.
3436 6. Copy the generated API key. You'll need it to configure the webhook in Strapi.
3437
3438 ![Medusa Admin dashboard with the Secret API Keys page showing the Strapi API key](https://res.cloudinary.com/dza7lstvk/image/upload/v1763368257/Medusa%20Resources/CleanShot_2025-11-17_at_10.20.28_2x_b6cilm.png)
3439
3440 #### Configure Webhook in Strapi
3441
3442 Next, you need to configure a webhook in Strapi to call the Medusa webhook API route whenever product data is updated.
3443
3444 To configure the webhook in Strapi:
3445
3446 1. Open the Strapi Admin dashboard.
3447 2. Go to Settings -> Webhooks.
3448 3. Click on the "Create new webhook" button at the top right.
3449 4. In the webhook creation form:
3450 - **Name**: Enter a name for the webhook. For example, "Medusa".
3451 - **URL**: Enter the URL of the Medusa webhook API route. It should be `http://localhost:9000/webhooks/strapi` if you're running Medusa locally.
3452 - **Headers**: Add a new header with the key `Authorization` and the value `Bearer YOUR_SECRET_API_KEY`. Replace `YOUR_SECRET_API_KEY` with the API key you created in Medusa.
3453 - **Events**: Select the "Update" event for "Entry". This ensures that the webhook is triggered whenever an entry is updated in Strapi.
3454 5. Click on the "Save" button to create the webhook.
3455
3456 ![Strapi Webhook Creation form](https://res.cloudinary.com/dza7lstvk/image/upload/v1763368257/Medusa%20Resources/CleanShot_2025-11-17_at_10.30.22_2x_zohl1q.png)
3457
3458 ### Test Strapi Webhook Handling
3459
3460 To test out the webhook handling:
3461
3462 1. Make sure both the Medusa and Strapi servers are running.
3463 2. On the Strapi Admin dashboard, go to Content Manager -> Products.
3464 3. Select an existing product to edit.
3465 4. Update the product's title or description.
3466 5. Click on the "Save" button to save the changes.
3467
3468 Once you save the changes, Strapi will send a webhook to Medusa. You should see the following in the Medusa server logs:
3469
3470 ```bash
3471 http: POST /webhooks/strapi ← - (200) - 153.264 ms
3472 ```
3473
3474 This indicates that the webhook was received and processed successfully.
3475
3476 You can also check the product in the Medusa Admin dashboard to verify that the changes made in Strapi are reflected in Medusa.
3477
3478 ---
3479
3480 ## Step 7: Show Strapi Data in Storefront
3481
3482 Now that you've integrated Strapi with Medusa, you can customize the Next.js Starter Storefront to display product content from Strapi, allowing you to show product content and assets optimized for the storefront.
3483
3484 In this step, you'll customize the Next.js Starter Storefront to show the Strapi product data.
3485
3486 <Note title="Reminder" forceMultiline>
3487
3488 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
3489
3490 ```bash
3491 cd apps/storefront
3492 ```
3493
3494 </Note>
3495
3496 ### a. Allow Retrieving Strapi Data in Store Products
3497
3498 The Store API routes only return the fields that they allow in the `fields` query parameter. Any other field, including a field added by a custom link like `strapi_product`, is removed from the response without an error.
3499
3500 So, before you can retrieve Strapi data in the storefront, you must add `strapi_product` to the allowed fields of the Products API route.
3501
3502 In your Medusa application, add a route object to the `src/api/middlewares.ts` file that you created earlier:
3503
3504 ```ts title="src/api/middlewares.ts" badgeLabel="Medusa application" badgeColor="green"
3505 import { allowFields } from "@medusajs/framework/http"
3506
3507 export default defineMiddlewares({
3508 routes: [
3509 // ...
3510 {
3511 matcher: "/store/products",
3512 middlewares: [allowFields("strapi_product")],
3513 },
3514 ],
3515 })
3516 ```
3517
3518 <Note>
3519
3520 `allowFields` is available since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0). In earlier versions, write the middleware yourself, as explained in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields#how-to-override-allowed-fields-of-medusas-api-routes) documentation.
3521
3522 </Note>
3523
3524 This middleware pushes `strapi_product` to the route's allowed fields, so Medusa keeps the field when a request asks for it. The other fields that you'll pass in the next section, such as `*variants.images`, are already among the route's allowed fields.
3525
3526 <Note title="Important">
3527
3528 The middleware must be global, so don't set a `method` property in the route object. Medusa runs a middleware scoped to a method after it validates the `fields` query parameter, so it has no effect.
3529
3530 </Note>
3531
3532 Learn more in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields) documentation.
3533
3534 ### b. Retrieve Strapi Product Data
3535
3536 Since you've created a [virtual read-only link](#step-4-create-virtual-read-only-link-to-strapi-products) to Strapi products in Medusa, you can retrieve Strapi product data when retrieving Medusa products.
3537
3538 To retrieve Strapi product data, open `src/lib/data/product.ts`, and add `*strapi_product` to the `fields` query parameter passed in the `listProducts` function:
3539
3540 ```ts title="src/lib/data/product.ts" badgeLabel="Storefront" badgeColor="blue" highlights={[["16"]]}
3541 export const listProducts = async ({
3542 // ...
3543 }: {
3544 // ...
3545 }): Promise<{
3546 // ...
3547 }> => {
3548 // ...
3549
3550 return sdk.client
3551 .fetch<{ products: HttpTypes.StoreProduct[]; count: number }>(
3552 `/store/products`,
3553 {
3554 query: {
3555 fields:
3556 "*variants.calculated_price,+variants.inventory_quantity,*variants.images,+metadata,+tags,*strapi_product",
3557 // ...
3558 },
3559 // ...
3560 }
3561 )
3562 // ...
3563 }
3564 ```
3565
3566 The Strapi product data will now be included in the `strapi_product` property of each Medusa product.
3567
3568 ### c. Define Strapi Product Types
3569
3570 Next, you'll define types for the Strapi product data to use in the storefront.
3571
3572 Create the file `src/types/strapi.ts` with the following content:
3573
3574 ```ts title="src/types/strapi.ts" badgeLabel="Storefront" badgeColor="blue"
3575 export interface StrapiMedia {
3576 id: number
3577 url: string
3578 alternativeText?: string
3579 caption?: string
3580 width?: number
3581 height?: number
3582 formats?: {
3583 thumbnail?: { url: string; width: number; height: number }
3584 small?: { url: string; width: number; height: number }
3585 medium?: { url: string; width: number; height: number }
3586 large?: { url: string; width: number; height: number }
3587 }
3588 }
3589
3590 export interface StrapiProductOptionValue {
3591 id: number
3592 medusaId: string
3593 value: string
3594 locale: string
3595 option?: StrapiProductOption
3596 variants?: StrapiProductVariant[]
3597 }
3598
3599 export interface StrapiProductOption {
3600 id: number
3601 medusaId: string
3602 title: string
3603 locale: string
3604 product?: StrapiProduct
3605 values?: StrapiProductOptionValue[]
3606 }
3607
3608 export interface StrapiProductVariant {
3609 id: number
3610 medusaId: string
3611 title: string
3612 sku?: string
3613 locale: string
3614 product?: StrapiProduct
3615 option_values?: StrapiProductOptionValue[]
3616 images?: StrapiMedia[]
3617 thumbnail?: StrapiMedia
3618 }
3619
3620 export interface StrapiProduct {
3621 id: number
3622 medusaId: string
3623 title: string
3624 subtitle?: string
3625 description?: string
3626 handle: string
3627 images?: StrapiMedia[]
3628 thumbnail?: StrapiMedia
3629 locale: string
3630 variants?: StrapiProductVariant[]
3631 options?: StrapiProductOption[]
3632 }
3633 ```
3634
3635 You define types for Strapi media, product option values, product options, product variants, and products.
3636
3637 ### d. Add Strapi Product Utilities
3638
3639 Next, add utilities that will allow you to easily retrieve Strapi product data from a product object.
3640
3641 Create the file `src/lib/util/strapi.ts` with the following content:
3642
3643 ```ts title="src/lib/util/strapi.ts" badgeLabel="Storefront" badgeColor="blue"
3644 import { HttpTypes } from "@medusajs/types"
3645 import {
3646 StrapiProduct,
3647 StrapiMedia,
3648 } from "../../types/strapi"
3649
3650 /**
3651 * Get Strapi product data from a Medusa product
3652 */
3653 export function getStrapiProduct(
3654 product: HttpTypes.StoreProduct
3655 ): StrapiProduct | undefined {
3656 return (product as any).strapi_product as StrapiProduct | undefined
3657 }
3658
3659 /**
3660 * Get product title from Strapi, fallback to Medusa
3661 */
3662 export function getProductTitle(
3663 product: HttpTypes.StoreProduct
3664 ): string {
3665 const strapiProduct = getStrapiProduct(product)
3666 return strapiProduct?.title || product.title || ""
3667 }
3668
3669 /**
3670 * Get product subtitle from Strapi
3671 */
3672 export function getProductSubtitle(
3673 product: HttpTypes.StoreProduct
3674 ): string | undefined {
3675 const strapiProduct = getStrapiProduct(product)
3676 return strapiProduct?.subtitle
3677 }
3678
3679 /**
3680 * Get product description from Strapi, fallback to Medusa
3681 */
3682 export function getProductDescription(
3683 product: HttpTypes.StoreProduct
3684 ): string | null {
3685 const strapiProduct = getStrapiProduct(product)
3686 if (strapiProduct?.description) {
3687 // Strapi richtext is typically stored as a string or structured data
3688 // For now, we'll handle it as a string. You may need to parse it based on your Strapi configuration
3689 return typeof strapiProduct.description === "string"
3690 ? strapiProduct.description
3691 : JSON.stringify(strapiProduct.description)
3692 }
3693 return product.description
3694 }
3695
3696 /**
3697 * Get product thumbnail from Strapi, fallback to Medusa
3698 */
3699 export function getProductThumbnail(
3700 product: HttpTypes.StoreProduct
3701 ): string | null {
3702 const strapiProduct = getStrapiProduct(product)
3703
3704 if (strapiProduct?.thumbnail?.url) {
3705 return strapiProduct.thumbnail.url
3706 }
3707
3708 return product.thumbnail || null
3709 }
3710
3711 /**
3712 * Get product images from Strapi, fallback to Medusa
3713 */
3714 export function getProductImages(
3715 product: HttpTypes.StoreProduct
3716 ): HttpTypes.StoreProductImage[] {
3717 const strapiProduct = getStrapiProduct(product)
3718
3719 if (strapiProduct?.images && strapiProduct.images.length > 0) {
3720 // Convert Strapi media to Medusa product image format
3721 return strapiProduct.images.map((image: StrapiMedia, index: number) => ({
3722 id: image.id.toString(),
3723 url: image.url,
3724 metadata: {
3725 alt: image.alternativeText || `Product image ${index + 1}`,
3726 },
3727 rank: index + 1,
3728 })) as HttpTypes.StoreProductImage[]
3729 }
3730
3731 return product.images || []
3732 }
3733
3734 /**
3735 * Get variant title from Strapi, fallback to Medusa
3736 */
3737 export function getVariantTitle(
3738 variant: HttpTypes.StoreProductVariant,
3739 product: HttpTypes.StoreProduct
3740 ): string {
3741 const strapiProduct = getStrapiProduct(product)
3742 const strapiVariant = strapiProduct?.variants?.find(
3743 (v) => v.medusaId === variant.id
3744 )
3745 return strapiVariant?.title || variant.title || ""
3746 }
3747
3748 /**
3749 * Get option title from Strapi, fallback to Medusa
3750 */
3751 export function getOptionTitle(
3752 option: HttpTypes.StoreProductOption,
3753 product: HttpTypes.StoreProduct
3754 ): string {
3755 const strapiProduct = getStrapiProduct(product)
3756 const strapiOption = strapiProduct?.options?.find(
3757 (o) => o.medusaId === option.id
3758 )
3759 return strapiOption?.title || option.title || ""
3760 }
3761
3762 /**
3763 * Get option value text from Strapi, fallback to Medusa
3764 */
3765 export function getOptionValueText(
3766 optionValue: { id: string; option_id: string; value: string },
3767 product: HttpTypes.StoreProduct
3768 ): string {
3769 const strapiProduct = getStrapiProduct(product)
3770 const strapiOption = strapiProduct?.options?.find(
3771 (o) => o.medusaId === optionValue.option_id
3772 )
3773 const strapiOptionValue = strapiOption?.values?.find(
3774 (v) => v.medusaId === optionValue.id
3775 )
3776 return strapiOptionValue?.value || optionValue.value
3777 }
3778
3779 /**
3780 * Get all option values for a variant with Strapi labels
3781 */
3782 export function getVariantOptionValues(
3783 variant: HttpTypes.StoreProductVariant,
3784 product: HttpTypes.StoreProduct
3785 ): Array<{ optionTitle: string; value: string }> {
3786 if (!variant.options || variant.options.length === 0) {
3787 return []
3788 }
3789
3790 return variant.options
3791 .filter((opt) => opt.option_id && opt.id)
3792 .map((opt) => {
3793 const option = product.options?.find((o) => o.id === opt.option_id)
3794 const optionTitle = option
3795 ? getOptionTitle(option, product)
3796 : ""
3797 const value = getOptionValueText(
3798 { id: opt.id, option_id: opt.option_id!, value: opt.value! },
3799 product
3800 )
3801 return { optionTitle, value }
3802 })
3803 .filter((opt) => opt.optionTitle && opt.value)
3804 }
3805
3806 /**
3807 * Get images for a specific variant from Strapi
3808 */
3809 export function getVariantImages(
3810 variant: HttpTypes.StoreProductVariant,
3811 product: HttpTypes.StoreProduct
3812 ): HttpTypes.StoreProductImage[] {
3813 const strapiProduct = getStrapiProduct(product)
3814 const strapiVariant = strapiProduct?.variants?.find(
3815 (v) => v.medusaId === variant.id
3816 )
3817
3818 // If variant has specific images in Strapi, use those
3819 if (strapiVariant?.images && strapiVariant.images.length > 0) {
3820 return strapiVariant.images.map((image: StrapiMedia, index: number) => ({
3821 id: image.id.toString(),
3822 url: image.url,
3823 metadata: {
3824 alt: image.alternativeText || `Variant image ${index + 1}`,
3825 },
3826 rank: index + 1,
3827 })) as HttpTypes.StoreProductImage[]
3828 }
3829
3830 // Fall back to Medusa variant images
3831 if ((variant as any).images && (variant as any).images.length > 0) {
3832 return (variant as any).images
3833 }
3834
3835 // Finally, fall back to product images
3836 return getProductImages(product)
3837 }
3838 ```
3839
3840 You define the following utilities:
3841
3842 - `getStrapiProduct`: Retrieves the Strapi product data from a Medusa product.
3843 - `getProductTitle`: Retrieves the product title from Strapi, falling back to Medusa if not available.
3844 - `getProductSubtitle`: Retrieves the product subtitle from Strapi.
3845 - `getProductDescription`: Retrieves the product description from Strapi, falling back to Medusa if not available.
3846 - `getProductThumbnail`: Retrieves the product thumbnail from Strapi, falling back to Medusa if not available.
3847 - `getProductImages`: Retrieves the product images from Strapi, falling back to Medusa if not available.
3848 - `getVariantTitle`: Retrieves the variant title from Strapi, falling back to Medusa if not available.
3849 - `getOptionTitle`: Retrieves the option title from Strapi, falling back to Medusa if not available.
3850 - `getOptionValueText`: Retrieves the option value text from Strapi, falling back to Medusa if not available.
3851 - `getVariantOptionValues`: Retrieves all option values for a variant with Strapi labels.
3852 - `getVariantImages`: Retrieves images for a specific variant from Strapi, falling back to Medusa if not available.
3853
3854 ### e. Customize Product Preview
3855
3856 Next, you'll customize the product preview component to show Strapi product data. This component is displayed on the product listing page.
3857
3858 In `src/modules/products/components/product-preview/index.tsx`, add the following imports at the top of the file:
3859
3860 ```tsx title="src/modules/products/components/product-preview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3861 import {
3862 getProductTitle,
3863 getProductImages,
3864 getProductThumbnail,
3865 } from "@lib/util/strapi"
3866 ```
3867
3868 Then, in the `ProductPreview` component, define the following variables before the `return` statement:
3869
3870 ```tsx title="src/modules/products/components/product-preview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3871 const title = getProductTitle(product)
3872 const images = getProductImages(product)
3873 const thumbnail = getProductThumbnail(product) || product.thumbnail
3874 ```
3875
3876 Finally, replace the `return` statement with the following:
3877
3878 ```tsx title="src/modules/products/components/product-preview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3879 return (
3880 <LocalizedClientLink href={`/products/${product.handle}`} className="group">
3881 <div data-testid="product-wrapper">
3882 <Thumbnail
3883 thumbnail={thumbnail}
3884 images={images}
3885 size="full"
3886 isFeatured={isFeatured}
3887 />
3888 <div className="flex txt-compact-medium mt-4 justify-between">
3889 <Text className="text-ui-fg-subtle" data-testid="product-title">
3890 {title}
3891 </Text>
3892 <div className="flex items-center gap-x-2">
3893 {cheapestPrice && <PreviewPrice price={cheapestPrice} />}
3894 </div>
3895 </div>
3896 </div>
3897 </LocalizedClientLink>
3898 )
3899 ```
3900
3901 You make two key changes:
3902
3903 1. Pass the `images` and `thumbnail` variables as props to the `Thumbnail` component to show Strapi product images.
3904 2. Use the `title` variable to display the Strapi product title.
3905
3906 ### f. Customize Product Details Metadata
3907
3908 Next, you'll customize the product details component to show Strapi product data.
3909
3910 First, you'll use the Strapi product title, subtitle, and images in the page's metadata.
3911
3912 In `src/app/[countryCode]/(main)/products/[handle]/page.tsx`, add the following imports at the top of the file:
3913
3914 ```tsx title="src/app/[countryCode]/(main)/products/[handle]/page.tsx" badgeLabel="Storefront" badgeColor="blue"
3915 import {
3916 getProductImages,
3917 getVariantImages,
3918 getProductTitle,
3919 getProductSubtitle,
3920 getProductThumbnail,
3921 } from "@lib/util/strapi"
3922 import { StrapiMedia } from "../../../../../types/strapi"
3923 ```
3924
3925 Then, replace the `getImagesForVariant` function with the following:
3926
3927 ```tsx title="src/app/[countryCode]/(main)/products/[handle]/page.tsx" badgeLabel="Storefront" badgeColor="blue"
3928 function getImagesForVariant(
3929 product: HttpTypes.StoreProduct,
3930 selectedVariantId?: string
3931 ) {
3932 // Get Strapi images or fallback to Medusa images
3933 const productImages = getProductImages(product)
3934
3935 if (!selectedVariantId || !product.variants) {
3936 return productImages
3937 }
3938
3939 const variant = product.variants!.find((v) => v.id === selectedVariantId)
3940 if (!variant) {
3941 return productImages
3942 }
3943
3944 // Get variant images from Strapi or fallback to Medusa
3945 const variantImages = getVariantImages(variant, product)
3946
3947 // If variant has specific images, use those; otherwise use product images
3948 if (
3949 variantImages.length > 0 &&
3950 (variant as any).images &&
3951 (variant as any).images.length > 0
3952 ) {
3953 const imageIdsMap = new Map((variant as any)
3954 .images.map((i: StrapiMedia) => [i.id, true]))
3955 return productImages.filter((i) => imageIdsMap.has(i.id))
3956 }
3957
3958 return productImages
3959 }
3960 ```
3961
3962 This function now retrieves product and variant images from Strapi using the utilities you defined earlier. These images will be shown on the product's details page.
3963
3964 Next, in the `generateMetadata` function, replace the `return` statement with the following:
3965
3966 ```tsx title="src/app/[countryCode]/(main)/products/[handle]/page.tsx" badgeLabel="Storefront" badgeColor="blue"
3967 const title = getProductTitle(product)
3968 const subtitle = getProductSubtitle(product)
3969 const thumbnail = getProductThumbnail(product) || product.thumbnail
3970
3971 return {
3972 title: `${title} | Medusa Store`,
3973 description: subtitle || title,
3974 openGraph: {
3975 title: `${title} | Medusa Store`,
3976 description: subtitle || title,
3977 images: thumbnail ? [thumbnail] : [],
3978 },
3979 }
3980 ```
3981
3982 You use the Strapi product title, subtitle, and thumbnail in the page's metadata.
3983
3984 ### g. Customize Product Details Page
3985
3986 Next, you'll customize the product details page to show Strapi product data.
3987
3988 <Note>
3989
3990 The images for the product details page were already customized in the previous section when you updated the `getImagesForVariant` function.
3991
3992 </Note>
3993
3994 #### Show Product Title and Description
3995
3996 First, you'll show the Strapi product title and description on the product details page.
3997
3998 Since the product description is in markdown format, you need to install the `react-markdown` package to render it. Run the following command in your storefront directory:
3999
4000 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
4001 npm install react-markdown
4002 ```
4003
4004 Then, in `src/modules/products/templates/product-info/index.tsx`, add the following imports at the top of the file:
4005
4006 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4007 import {
4008 getProductTitle,
4009 getProductDescription,
4010 } from "@lib/util/strapi"
4011 import Markdown from "react-markdown"
4012 ```
4013
4014 Next, in the `ProductInfo` component, define the following variables before the `return` statement:
4015
4016 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4017 const title = getProductTitle(product)
4018 const description = getProductDescription(product)
4019 ```
4020
4021 Finally, in the `return` statement, replace `{product.title}` with `{title}`:
4022
4023 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4024 return (
4025 <div id="product-info">
4026 {/* ... */}
4027 <Heading
4028 // ...
4029 >
4030 {title}
4031 </Heading>
4032 </div>
4033 )
4034 ```
4035
4036 Then, find the `Text` component wrapping the `{product.description}` and replace it with the following:
4037
4038 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4039 <div
4040 className="text-medium text-ui-fg-subtle whitespace-pre-line"
4041 data-testid="product-description"
4042 >
4043 <Markdown
4044 allowedElements={[
4045 "p", "ul", "ol", "li", "strong", "em", "blockquote", "hr", "br", "a",
4046 ]}
4047 unwrapDisallowed
4048 >
4049 {description}
4050 </Markdown>
4051 </div>
4052 ```
4053
4054 #### Show Option Titles and Values
4055
4056 Next, you'll show Strapi option titles and values on the product details page.
4057
4058 Replace the content of `src/modules/products/components/product-actions/option-select.tsx` with the following:
4059
4060 ```tsx title="src/modules/products/components/product-actions/option-select.tsx" badgeLabel="Storefront" badgeColor="blue"
4061 import { HttpTypes } from "@medusajs/types"
4062 import { clx } from "@medusajs/ui"
4063 import React from "react"
4064 import { getOptionValueText } from "@lib/util/strapi"
4065
4066 type OptionSelectProps = {
4067 option: HttpTypes.StoreProductOption
4068 current: string | undefined
4069 updateOption: (title: string, value: string) => void
4070 title: string
4071 product: HttpTypes.StoreProduct
4072 disabled: boolean
4073 "data-testid"?: string
4074 }
4075
4076 const OptionSelect: React.FC<OptionSelectProps> = ({
4077 option,
4078 current,
4079 updateOption,
4080 title,
4081 product,
4082 "data-testid": dataTestId,
4083 disabled,
4084 }) => {
4085 const filteredOptions = (option.values ?? []).map((v) => ({
4086 originalValue: v.value,
4087 displayValue: getOptionValueText(
4088 { id: v.id, option_id: option.id, value: v.value },
4089 product
4090 ),
4091 }))
4092
4093 return (
4094 <div className="flex flex-col gap-y-3">
4095 <span className="text-sm">Select {title}</span>
4096 <div
4097 className="flex flex-wrap justify-between gap-2"
4098 data-testid={dataTestId}
4099 >
4100 {filteredOptions.map(({ originalValue, displayValue }) => {
4101 return (
4102 <button
4103 onClick={() => updateOption(option.id, originalValue)}
4104 key={originalValue}
4105 className={clx(
4106 "border-ui-border-base bg-ui-bg-subtle border text-small-regular h-10 rounded-rounded p-2 flex-1 ",
4107 {
4108 "border-ui-border-interactive": originalValue === current,
4109 "hover:shadow-elevation-card-rest transition-shadow ease-in-out duration-150":
4110 originalValue !== current,
4111 }
4112 )}
4113 disabled={disabled}
4114 data-testid="option-button"
4115 >
4116 {displayValue}
4117 </button>
4118 )
4119 })}
4120 </div>
4121 </div>
4122 )
4123 }
4124
4125 export default OptionSelect
4126 ```
4127
4128 You make the following key changes:
4129
4130 - Add the `product` prop to the `OptionSelect` component.
4131 - Use the `getOptionValueText` utility to get the option value text from Strapi.
4132 - Display the Strapi option value text in the option buttons.
4133
4134 Then, in `src/modules/products/components/product-actions/index.tsx`, add the following import at the top of the file:
4135
4136 ```tsx title="src/modules/products/components/product-actions/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4137 import { getOptionTitle } from "@lib/util/strapi"
4138 ```
4139
4140 And in the `return` statement, find the `product.options` loop and replace it with the following:
4141
4142 ```tsx title="src/modules/products/components/product-actions/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4143 return (
4144 <>
4145 {/* ... */}
4146 {(product.options || []).map((option) => {
4147 const optionTitle = getOptionTitle(option, product)
4148 return (
4149 <div key={option.id}>
4150 <OptionSelect
4151 option={option}
4152 current={options[option.id]}
4153 updateOption={setOptionValue}
4154 title={optionTitle}
4155 product={product}
4156 data-testid="product-options"
4157 disabled={!!disabled || isAdding}
4158 />
4159 </div>
4160 )
4161 })}
4162 {/* ... */}
4163 </>
4164 )
4165 ```
4166
4167 You use the `getOptionTitle` utility to get the option title from Strapi and pass the `product` prop to the `OptionSelect` component.
4168
4169 You need to make similar changes in the `src/modules/products/components/product-actions/mobile-actions.tsx` component. First, add the following imports at the top of the file:
4170
4171 ```tsx title="src/modules/products/components/product-actions/mobile-actions.tsx" badgeLabel="Storefront" badgeColor="blue"
4172 import { getProductTitle, getOptionTitle } from "@lib/util/strapi"
4173 ```
4174
4175 Then, in the `return` statement, replace the `{product.title}` with the following:
4176
4177 ```tsx title="src/modules/products/components/product-actions/mobile-actions.tsx" badgeLabel="Storefront" badgeColor="blue"
4178 return (
4179 <>
4180 {/* ... */}
4181 <span data-testid="mobile-title">{getProductTitle(product)}</span>
4182 {/* ... */}
4183 </>
4184 )
4185 ```
4186
4187 Then, find the `product.options` loop and replace it with the following:
4188
4189 ```tsx title="src/modules/products/components/product-actions/mobile-actions.tsx" badgeLabel="Storefront" badgeColor="blue"
4190 return (
4191 <>
4192 {/* ... */}
4193 {(product.options || []).map((option) => {
4194 const optionTitle = getOptionTitle(option, product)
4195 return (
4196 <div key={option.id}>
4197 <OptionSelect
4198 option={option}
4199 current={options[option.id]}
4200 updateOption={updateOptions}
4201 title={optionTitle}
4202 product={product}
4203 disabled={optionsDisabled}
4204 />
4205 </div>
4206 )
4207 })}
4208 {/* ... */}
4209 </>
4210 )
4211 ```
4212
4213 You retrieve the Strapi option title and pass the `product` prop to the `OptionSelect` component.
4214
4215 ### h. Customize Line Item Options
4216
4217 Finally, you'll customize the line item options to either show Strapi variant titles or option titles and values.
4218
4219 Replace the content of `src/modules/common/components/line-item-options/index.tsx` with the following:
4220
4221 ```tsx title="src/modules/common/components/line-item-options/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4222 import { HttpTypes } from "@medusajs/types"
4223 import { Text } from "@medusajs/ui"
4224 import { getVariantTitle, getVariantOptionValues } from "@lib/util/strapi"
4225
4226 type LineItemOptionsProps = {
4227 variant: HttpTypes.StoreProductVariant | undefined
4228 product?: HttpTypes.StoreProduct
4229 "data-testid"?: string
4230 "data-value"?: HttpTypes.StoreProductVariant
4231 }
4232
4233 const LineItemOptions = ({
4234 variant,
4235 product,
4236 "data-testid": dataTestid,
4237 "data-value": dataValue,
4238 }: LineItemOptionsProps) => {
4239 if (!variant) {
4240 return null
4241 }
4242
4243 // Get product from variant if not provided
4244 const productData = product || (variant as any).product
4245
4246 // Get variant title from Strapi
4247 const variantTitle = productData
4248 ? getVariantTitle(variant, productData)
4249 : variant.title
4250
4251 // Get option values from Strapi
4252 const optionValues = productData
4253 ? getVariantOptionValues(variant, productData)
4254 : []
4255
4256 // If we have option values, show them; otherwise show variant title
4257 if (optionValues.length > 0) {
4258 const displayText = optionValues
4259 .map((opt) => `${opt.optionTitle}: ${opt.value}`)
4260 .join(" / ")
4261
4262 return (
4263 <Text
4264 data-testid={dataTestid}
4265 data-value={dataValue}
4266 className="inline-block txt-medium text-ui-fg-subtle w-full overflow-hidden text-ellipsis"
4267 >
4268 {displayText}
4269 </Text>
4270 )
4271 }
4272
4273 return (
4274 <Text
4275 data-testid={dataTestid}
4276 data-value={dataValue}
4277 className="inline-block txt-medium text-ui-fg-subtle w-full overflow-hidden text-ellipsis"
4278 >
4279 Variant: {variantTitle}
4280 </Text>
4281 )
4282 }
4283
4284 export default LineItemOptions
4285 ```
4286
4287 You make the following key changes:
4288
4289 - Add a `product` prop to the `LineItemOptions` component.
4290 - Use the `getVariantTitle` utility to get the variant title from Strapi.
4291 - Use the `getVariantOptionValues` utility to get the option titles and values from Strapi.
4292 - If option values are available, display them; otherwise, display the variant title.
4293
4294 This component is used in cart and order components to show line item details. So, you need to pass the `product` prop where the component is used.
4295
4296 In `src/modules/cart/components/item/index.tsx`, find the `LineItemOptions` component in the `return` statement and update it as follows:
4297
4298 ```tsx title="src/modules/cart/components/item/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4299 return (
4300 <Table.Row>
4301 {/* ... */}
4302 <LineItemOptions
4303 variant={item.variant}
4304 product={item.variant?.product!}
4305 data-testid="product-variant"
4306 />
4307 {/* ... */}
4308 </Table.Row>
4309 )
4310 ```
4311
4312 Next, in `src/modules/layout/components/cart-dropdown/index.tsx`, find the `LineItemOptions` component in the `return` statement and update it as follows:
4313
4314 ```tsx title="src/modules/layout/components/cart-dropdown/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4315 return (
4316 <div>
4317 {/* ... */}
4318 <LineItemOptions
4319 variant={item.variant}
4320 product={item.variant?.product!}
4321 data-testid="cart-item-variant"
4322 data-value={item.variant}
4323 />
4324 {/* ... */}
4325 </div>
4326 )
4327 ```
4328
4329 Finally, in `src/modules/order/components/item/index.tsx`, find the `LineItemOptions` component in the `return` statement and update it as follows:
4330
4331 ```tsx title="src/modules/order/components/item/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4332 return (
4333 <Table.Row>
4334 {/* ... */}
4335 <LineItemOptions
4336 variant={item.variant}
4337 product={item.variant?.product!}
4338 data-testid="product-variant"
4339 />
4340 {/* ... */}
4341 </Table.Row>
4342 )
4343 ```
4344
4345 This will show Strapi variant titles or option titles and values in the cart and order line items.
4346
4347 ### Test Storefront Customizations
4348
4349 To test the storefront customizations, make sure both the Medusa and Strapi servers are running.
4350
4351 Then, run the following command in the Next.js Starter Storefront directory to start the storefront:
4352
4353 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
4354 npm run dev
4355 ```
4356
4357 You can open the storefront in your browser at `http://localhost:8000`.
4358
4359 You'll see the Strapi product data in the following places:
4360
4361 1. Go to Menu -> Store. On the product listing page, you'll see the Strapi product titles and images.
4362 2. Open a product's details page. You'll see the Strapi product title, description, images, option titles, and option values.
4363 3. Add the product to the cart. You'll see the Strapi variant titles or option titles and values in the cart dropdown and cart page.
4364 4. Place an order. You'll see the Strapi variant titles or option titles and values in the order confirmation page.
4365
4366 ---
4367
4368 ## Step 8: Handle More Product Events
4369
4370 Your setup now supports creating products in Strapi when they're created in Medusa. However, you should also support updating and deleting products and their related models to keep data in sync between systems.
4371
4372 For each product event, such as `product.deleted` or `product-variant.updated`, you need to:
4373
4374 1. Create a workflow that updates or deletes the corresponding data in Strapi using the Strapi Module's service.
4375 2. Create a subscriber that listens for the event and triggers the workflow.
4376
4377 You can find all workflows and subscribers for product events in the [Strapi Integration Repository](https://github.com/medusajs/examples/tree/main/strapi-integration/medusa).
4378
4379 ---
4380
4381 ## Next Steps
4382
4383 You've successfully integrated Medusa with Strapi to manage content related to products, variants, and options. You can expand this integration by adding more features, such as:
4384
4385 1. Managing the content of other entities, like categories or collections. The process is similar to what you've done for products:
4386 1. Create a content type in Strapi for the entity.
4387 2. Create Medusa workflows and subscribers to handle the creation, update, and deletion of the entity.
4388 3. Display the Strapi data in your Next.js Starter Storefront.
4389 2. Enable [internationalization](https://docs.strapi.io/cms/features/internationalization) in Strapi to support multiple languages:
4390 - You only need to manage the localized content in Strapi. Only the default locale will be synced with Medusa.
4391 - You can display the localized content in your Next.js Starter Storefront based on the customer's locale.
4392 3. Add custom fields to the Strapi content types that are relevant to the storefront, such as SEO metadata or promotional banners.
4393
4394 ### Learn More about Medusa
4395
4396 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
4397
4398 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
4399
4400 ### Troubleshooting
4401
4402 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
4403
4404 ### Getting Help
4405
4406 If you encounter issues not covered in the troubleshooting guides:
4407
4408 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
4409 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.