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