1 ---
2 sidebar_label: "Integrate Contentful"
3 tags:
4 - server
5 - name: product
6 label: "Localization with Contentful"
7 - tutorial
8 products:
9 - product
10 ---
11
12 import { Card, Prerequisites, Details, WorkflowDiagram } from "docs-ui"
13 import { Github, PlaySolid } from "@medusajs/icons"
14
15 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1746006829/Medusa%20Resources/localization_dtiqtb.jpg"
16
17 export const metadata = {
18 title: `Implement Localization in Medusa by Integrating Contentful`,
19 openGraph: {
20 images: [
21 {
22 url: ogImage,
23 width: 1600,
24 height: 900,
25 type: "image/jpeg"
26 }
27 ],
28 },
29 twitter: {
30 images: [
31 {
32 url: ogImage,
33 width: 1600,
34 height: 900,
35 type: "image/jpeg"
36 }
37 ]
38 }
39 }
40
41 # {metadata.title}
42
43 In this tutorial, you'll learn how to localize your Medusa store's data with Contentful.
44
45 <Note>
46
47 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.
48
49 </Note>
50
51 <Note title="Tip">
52
53 [Translation Module](../../../commerce-modules/translation/page.mdx) is available since [Medusa v2.12.3](https://github.com/medusajs/medusa/releases/tag/v2.12.3). It allows you to manage translations for product-related resources through Medusa's Store API routes. For general localization needs, consider using the Translation Module instead of integrating a third-party CMS.
54
55 </Note>
56
57 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. While Medusa provides features essential for internationalization, such as support for multiple [regions](../../../commerce-modules/region/page.mdx) and [currencies](../../../commerce-modules/currency/page.mdx), it doesn't provide content localization.
58
59 However, Medusa's architecture supports the integration of third-party services to provide additional features, such as data localization. One service you can integrate is [Contentful](https://www.contentful.com/), a headless content management system (CMS) that allows you to manage and deliver content across multiple channels.
60
61 ## Summary
62
63 By following this tutorial, you'll learn how to:
64
65 - Install and set up Medusa.
66 - Integrate Contentful with Medusa.
67 - Create content types in Contentful for Medusa models.
68 - Trigger syncing products and related data to Contentful when:
69 - A product is created.
70 - The admin user triggers syncing the products.
71 - Customize the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) to fetch localized data from Contentful through Medusa.
72 - Listen to webhook events in Contentful to update Medusa's data accordingly.
73
74 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
75
76 ![Diagram illustrating the integration of Contentful with Medusa](https://res.cloudinary.com/dza7lstvk/image/upload/v1744791908/Medusa%20Resources/contentful-summary_j5cpdx.jpg)
77
78 <CardList items={[
79 {
80 href: "https://github.com/medusajs/examples/tree/main/localization-contentful",
81 title: "Tutorial Repository",
82 text: "Find the full code for this guide in this repository.",
83 icon: Github,
84 },
85 {
86 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1744790686/OpenApi/Contentful_jysc07.yaml",
87 title: "OpenApi Specs for Postman",
88 text: "Import this OpenApi Specs file into tools like Postman.",
89 icon: PlaySolid,
90 },
91 ]} />
92
93 ---
94
95 ## Step 1: Install a Medusa Application
96
97 <Prerequisites items={[
98 {
99 text: "Node.js v20.19.0+ or v22.12.0+",
100 link: "https://nodejs.org/en/download"
101 },
102 {
103 text: "Git CLI tool",
104 link: "https://git-scm.com/downloads"
105 },
106 {
107 text: "PostgreSQL",
108 link: "https://www.postgresql.org/download/"
109 }
110 ]} />
111
112 Start by installing the Medusa application on your machine with the following command:
113
114 ```bash
115 npx create-medusa-app@latest
116 ```
117
118 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."
119
120 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.
121
122 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.
123
124 <Note title="Ran into Errors?">
125
126 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
127
128 </Note>
129
130 <Note>
131
132 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
133
134 </Note>
135
136 ---
137
138 ## Step 2: Create Contentful Module
139
140 To integrate third-party services into Medusa, you create a module. A [module](!docs!/learn/fundamentals/modules) is a reusable package that provides functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
141
142 In this step, you'll create a module that provides the necessary functionalities to integrate Contentful with Medusa.
143
144 <Note>
145
146 Refer to the [Modules](!docs!/learn/fundamentals/modules) documentation to learn more about modules and their structure.
147
148 </Note>
149
150 ### Install Contentful SDKs
151
152 Before building the module, you need to install Contentful's management and delivery JS SDKs. So, run the following command in the `apps/backend` directory:
153
154 ```bash npm2yarn
155 npm install contentful contentful-management
156 ```
157
158 Where `contentful` is the delivery SDK and `contentful-management` is the management SDK.
159
160 ### Create Module Directory
161
162 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/contentful`.
163
164 ### Create Loader
165
166 When the Medusa application starts, you want to establish a connection to Contentful, then create the necessary content types if they don't exist in Contentful.
167
168 A module can specify a task to run on the Medusa application's startup using [loaders](!docs!/learn/fundamentals/modules/loaders). A loader is an asynchronous function that a module exports. Then, when the Medusa application starts, it runs the loader. The loader can be used to perform one-time tasks such as connecting to a database, creating content types, or initializing data.
169
170 <Note>
171
172 Refer to the [Loaders](!docs!/learn/fundamentals/modules/loaders) documentation to learn more about how loaders work and when to use them.
173
174 </Note>
175
176 Loaders are created in a TypeScript or JavaScript file under the `loaders` directory of a module. So, create the file `src/modules/contentful/loader/create-content-models.ts` with the following content:
177
178 export const loaderHighlights = [
179 ["11", "ModuleOptions", "The type of options that the module expects."],
180 ["20", "container", "The module's container, which is a\nregistry of resources available to the module."],
181 ["21", "options", "The options passed to the module."],
182 ["23", "if", "Validate that the module's options are valid."],
183 ["33", "resolve", "Resolve a resource from the module's container."],
184 ["38", "createClient", "Create a Contentful management client."],
185 ["48", "createDeliveryClient", "Create a Contentful delivery client."],
186 ]
187
188 ```ts title="src/modules/contentful/loader/create-content-models.ts" highlights={loaderHighlights}
189 import { LoaderOptions } from "@medusajs/framework/types"
190 import { asValue } from "@medusajs/framework/awilix"
191 import { createClient } from "contentful-management"
192 import {
193 MedusaError,
194 ContainerRegistrationKeys,
195 } from "@medusajs/framework/utils"
196
197 const { createClient: createDeliveryClient } = require("contentful")
198
199 export type ModuleOptions = {
200 management_access_token: string
201 delivery_token: string
202 space_id: string
203 environment: string
204 default_locale?: string
205 }
206
207 export default async function syncContentModelsLoader({
208 container,
209 options,
210 }: LoaderOptions<ModuleOptions>) {
211 if (
212 !options?.management_access_token || !options?.delivery_token ||
213 !options?.space_id || !options?.environment
214 ) {
215 throw new MedusaError(
216 MedusaError.Types.INVALID_DATA,
217 "Contentful access token, space ID and environment are required"
218 )
219 }
220
221 const logger = container.resolve(
222 ContainerRegistrationKeys.LOGGER
223 )
224
225 try {
226 const managementClient = createClient({
227 accessToken: options.management_access_token,
228 }, {
229 type: "plain",
230 defaults: {
231 spaceId: options.space_id,
232 environmentId: options.environment,
233 },
234 })
235
236 const deliveryClient = createDeliveryClient({
237 accessToken: options.delivery_token,
238 space: options.space_id,
239 environment: options.environment,
240 })
241
242
243 // TODO try to create content types
244
245 } catch (error) {
246 logger.error(
247 `Failed to connect to Contentful: ${error}`
248 )
249 throw error
250 }
251 }
252 ```
253
254 The loader file exports an asynchronous function that accepts an object having the following properties:
255
256 - `container`: The [Module container](!docs!/learn/fundamentals/modules/container), which is a registry of resources available to the module. You can use it to resolve or register resources in the module's container.
257 - `options`: An object of options passed to the module. These options are useful to pass secrets or options that may change per environment. You'll learn how to pass these options later.
258 - The Contentful Module expects the options to include the Contentful tokens for the management and delivery APIs, the space ID, environment, and optionally the default locale to use.
259
260 In the loader function, you validate the options passed to the module, and throw an error if they're invalid. Then, you resolve from the Module's container the [Logger](!docs!/learn/debugging-and-testing/logging) used to log messages in the terminal.
261
262 Finally, you create clients for Contentful's management and delivery APIs, passing them the necessary module's options. If the connection fails, an error is thrown, which is handled in the `catch` block.
263
264 #### Create Content Types
265
266 In the loader, you need to create content types in Contentful if they don't already exist.
267
268 In this tutorial, you'll only create content types for a product and its variants and options. However, you can create content types for other data models, such as categories or collections, by following the same approach.
269
270 <Note title="Tip">
271
272 You can learn more about the product-related data models, which the content types are based on, in the [Product Module's Data Models](/references/product/models) reference.
273
274 </Note>
275
276 To create the content type for products, replace the `TODO` in the loader with the following:
277
278 ```ts title="src/modules/contentful/loader/create-content-models.ts"
279 // Try to create the product content type
280 try {
281 await managementClient.contentType.get({
282 contentTypeId: "product",
283 })
284 } catch (error) {
285 const productContentType = await managementClient.contentType.createWithId({
286 contentTypeId: "product",
287 }, {
288 name: "Product",
289 description: "Product content type synced from Medusa",
290 displayField: "title",
291 fields: [
292 {
293 id: "title",
294 name: "Title",
295 type: "Symbol",
296 required: true,
297 localized: true,
298 },
299 {
300 id: "handle",
301 name: "Handle",
302 type: "Symbol",
303 required: true,
304 localized: false,
305 },
306 {
307 id: "medusaId",
308 name: "Medusa ID",
309 type: "Symbol",
310 required: true,
311 localized: false,
312 },
313 {
314 type: "RichText",
315 name: "description",
316 id: "description",
317 validations: [
318 {
319 enabledMarks: [
320 "bold",
321 "italic",
322 "underline",
323 "code",
324 "superscript",
325 "subscript",
326 "strikethrough",
327 ],
328 },
329 {
330 enabledNodeTypes: [
331 "heading-1",
332 "heading-2",
333 "heading-3",
334 "heading-4",
335 "heading-5",
336 "heading-6",
337 "ordered-list",
338 "unordered-list",
339 "hr",
340 "blockquote",
341 "embedded-entry-block",
342 "embedded-asset-block",
343 "table",
344 "asset-hyperlink",
345 "embedded-entry-inline",
346 "entry-hyperlink",
347 "hyperlink",
348 ],
349 },
350 {
351 nodes: {},
352 },
353 ],
354 localized: true,
355 required: true,
356 },
357 {
358 type: "Symbol",
359 name: "subtitle",
360 id: "subtitle",
361 localized: true,
362 required: false,
363 validations: [],
364 },
365 {
366 type: "Array",
367 items: {
368 type: "Link",
369 linkType: "Asset",
370 validations: [],
371 },
372 name: "images",
373 id: "images",
374 localized: true,
375 required: false,
376 validations: [],
377 },
378 {
379 id: "productVariants",
380 name: "Product Variants",
381 type: "Array",
382 localized: false,
383 required: false,
384 items: {
385 type: "Link",
386 validations: [
387 {
388 linkContentType: ["productVariant"],
389 },
390 ],
391 linkType: "Entry",
392 },
393 disabled: false,
394 omitted: false,
395 },
396 {
397 id: "productOptions",
398 name: "Product Options",
399 type: "Array",
400 localized: false,
401 required: false,
402 items: {
403 type: "Link",
404 validations: [
405 {
406 linkContentType: ["productOption"],
407 },
408 ],
409 linkType: "Entry",
410 },
411 disabled: false,
412 omitted: false,
413 },
414 ],
415 })
416
417 await managementClient.contentType.publish({
418 contentTypeId: "product",
419 }, productContentType)
420 }
421
422 // TODO create product variant content type
423 ```
424
425 In the above snippet, you first try to retrieve the product content type using Contentful's Management APIs. If the content type doesn't exist, an error is thrown, which you handle in the `catch` block.
426
427 In the `catch` block, you create the product content type with the following fields:
428
429 - `title`: The product's title, which is a localized field.
430 - `handle`: The product's handle, which is used to create a human-readable URL for the product in the storefront.
431 - `medusaId`: The product's ID in Medusa, which is a non-localized field. You'll store in this field the ID of the product in Medusa.
432 - `description`: The product's description, which is a localized rich-text field.
433 - `subtitle`: The product's subtitle, which is a localized field.
434 - `images`: The product's images, which is a localized array of assets in Contentful.
435 - `productVariants`: The product's variants, which is an array that references content of the `productVariant` content type.
436 - `productOptions`: The product's options, which is an array that references content of the `productOption` content type.
437
438 Next, you'll create the `productVariant` content type that represents a product's variant. A variant is a combination of the product's options that customers can purchase. For example, a "red" shirt is a variant whose color option is `red`.
439
440 To create the variant content type, replace the new `TODO` with the following:
441
442 ```ts title="src/modules/contentful/loader/create-content-models.ts"
443 // Try to create the product variant content type
444 try {
445 await managementClient.contentType.get({
446 contentTypeId: "productVariant",
447 })
448 } catch (error) {
449 const productVariantContentType = await managementClient.contentType.createWithId({
450 contentTypeId: "productVariant",
451 }, {
452 name: "Product Variant",
453 description: "Product variant content type synced from Medusa",
454 displayField: "title",
455 fields: [
456 {
457 id: "title",
458 name: "Title",
459 type: "Symbol",
460 required: true,
461 localized: true,
462 },
463 {
464 id: "product",
465 name: "Product",
466 type: "Link",
467 required: true,
468 localized: false,
469 validations: [
470 {
471 linkContentType: ["product"],
472 },
473 ],
474 disabled: false,
475 omitted: false,
476 linkType: "Entry",
477 },
478 {
479 id: "medusaId",
480 name: "Medusa ID",
481 type: "Symbol",
482 required: true,
483 localized: false,
484 },
485 {
486 id: "productOptionValues",
487 name: "Product Option Values",
488 type: "Array",
489 localized: false,
490 required: false,
491 items: {
492 type: "Link",
493 validations: [
494 {
495 linkContentType: ["productOptionValue"],
496 },
497 ],
498 linkType: "Entry",
499 },
500 disabled: false,
501 omitted: false,
502 },
503 ],
504 })
505
506 await managementClient.contentType.publish({
507 contentTypeId: "productVariant",
508 }, productVariantContentType)
509 }
510
511 // TODO create product option content type
512 ```
513
514 In the above snippet, you create the `productVariant` content type with the following fields:
515
516 - `title`: The product variant's title, which is a localized field.
517 - `product`: References the `product` content type, which is the product that the variant belongs to.
518 - `medusaId`: The product variant's ID in Medusa, which is a non-localized field. You'll store in this field the ID of the variant in Medusa.
519 - `productOptionValues`: The product variant's option values, which is an array that references content of the `productOptionValue` content type.
520
521 Then, you'll create the `productOption` content type that represents a product's option, like size or color. Replace the new `TODO` with the following:
522
523 ```ts title="src/modules/contentful/loader/create-content-models.ts"
524 // Try to create the product option content type
525 try {
526 await managementClient.contentType.get({
527 contentTypeId: "productOption",
528 })
529 } catch (error) {
530 const productOptionContentType = await managementClient.contentType.createWithId({
531 contentTypeId: "productOption",
532 }, {
533 name: "Product Option",
534 description: "Product option content type synced from Medusa",
535 displayField: "title",
536 fields: [
537 {
538 id: "title",
539 name: "Title",
540 type: "Symbol",
541 required: true,
542 localized: true,
543 },
544 {
545 id: "product",
546 name: "Product",
547 type: "Link",
548 required: false,
549 localized: false,
550 validations: [
551 {
552 linkContentType: ["product"],
553 },
554 ],
555 disabled: false,
556 omitted: false,
557 linkType: "Entry",
558 },
559 {
560 id: "medusaId",
561 name: "Medusa ID",
562 type: "Symbol",
563 required: true,
564 localized: false,
565 },
566 {
567 id: "values",
568 name: "Values",
569 type: "Array",
570 required: false,
571 localized: false,
572 items: {
573 type: "Link",
574 validations: [
575 {
576 linkContentType: ["productOptionValue"],
577 },
578 ],
579 linkType: "Entry",
580 },
581 disabled: false,
582 omitted: false,
583 },
584 ],
585 })
586
587 await managementClient.contentType.publish({
588 contentTypeId: "productOption",
589 }, productOptionContentType)
590 }
591
592 // TODO create product option value content type
593 ```
594
595 In the above snippet, you create the `productOption` content type with the following fields:
596
597 - `title`: The product option's title, which is a localized field.
598 - `product`: References the `product` content type. This field is optional since product options can be globally shared across multiple products.
599 - `medusaId`: The product option's ID in Medusa, which is a non-localized field. You'll store in this field the ID of the option in Medusa.
600 - `values`: The product option's values, which is an array that references content of the `productOptionValue` content type.
601
602 Finally, you'll create the `productOptionValue` content type that represents a product's option value, like "red" or "blue" for the color option. A variant references option values.
603
604 To create the option value content type, replace the new `TODO` with the following:
605
606 ```ts title="src/modules/contentful/loader/create-content-models.ts"
607 // Try to create the product option value content type
608 try {
609 await managementClient.contentType.get({
610 contentTypeId: "productOptionValue",
611 })
612 } catch (error) {
613 const productOptionValueContentType = await managementClient.contentType.createWithId({
614 contentTypeId: "productOptionValue",
615 }, {
616 name: "Product Option Value",
617 description: "Product option value content type synced from Medusa",
618 displayField: "value",
619 fields: [
620 {
621 id: "value",
622 name: "Value",
623 type: "Symbol",
624 required: true,
625 localized: true,
626 },
627 {
628 id: "medusaId",
629 name: "Medusa ID",
630 type: "Symbol",
631 required: true,
632 localized: false,
633 },
634 ],
635 })
636
637 await managementClient.contentType.publish({
638 contentTypeId: "productOptionValue",
639 }, productOptionValueContentType)
640 }
641
642 // TODO register clients in container
643 ```
644
645 In the above snippet, you create the `productOptionValue` content type with the following fields:
646
647 - `value`: The product option value, which is a localized field.
648 - `medusaId`: The product option value's ID in Medusa, which is a non-localized field. You'll store in this field the ID of the option value in Medusa.
649
650 You've now created all the necessary content types to localize products.
651
652 ### Register Clients in the Container
653
654 The last step in the loader is to register the Contentful management and delivery clients in the module's container. This will allow you to resolve and use them in the module's service, which you'll create next.
655
656 To register resources in the container, you can use its `register` method, which accepts an object containing key-value pairs. The keys are the names of the resources in the container, and the values are the resources themselves.
657
658 To register the management and delivery clients, replace the last `TODO` in the loader with the following:
659
660 ```ts title="src/modules/contentful/loader/create-content-models.ts"
661 container.register({
662 contentfulManagementClient: asValue(managementClient),
663 contentfulDeliveryClient: asValue(deliveryClient),
664 })
665
666 logger.info("Connected to Contentful")
667 ```
668
669 Now, you can resolve the management and delivery clients from the module's container using the keys `contentfulManagementClient` and `contentfulDeliveryClient`, respectively.
670
671 ### Create Service
672
673 You define a module's functionality in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or perform actions with a third-party service.
674
675 In this section, you'll create the Contentful Module's service that can be used to retrieve content from Contentful, create content, and more.
676
677 To create the service, create the file `src/modules/contenful/service.ts` with the following content:
678
679 export const serviceHighlights = [
680 ["16", "contentfulManagementClient", "Resolve the Contentful management client from the module's container."],
681 ["17", "contentfulDeliveryClient", "Resolve the Contentful delivery client from the module's container."],
682 ["19", "options", "The options passed to the module."],
683 ["25", "default_locale", "Set the default locale to `en-US`\nif it's not provided in the module's options."],
684 ]
685
686 ```ts title="src/modules/contentful/service.ts" highlights={serviceHighlights}
687 import { ModuleOptions } from "./loader/create-content-models"
688 import { PlainClientAPI } from "contentful-management"
689
690 type InjectedDependencies = {
691 contentfulManagementClient: PlainClientAPI;
692 contentfulDeliveryClient: any;
693 }
694
695 export default class ContentfulModuleService {
696 private managementClient: PlainClientAPI
697 private deliveryClient: any
698 private options: ModuleOptions
699
700 constructor(
701 {
702 contentfulManagementClient,
703 contentfulDeliveryClient,
704 }: InjectedDependencies,
705 options: ModuleOptions
706 ) {
707 this.managementClient = contentfulManagementClient
708 this.deliveryClient = contentfulDeliveryClient
709 this.options = {
710 ...options,
711 default_locale: options.default_locale || "en-US",
712 }
713 }
714
715 // TODO add methods
716 }
717 ```
718
719 You export a class that will be the Contentful Module's main service. In the class, you define properties for the Contentful clients and options passed to the module.
720
721 You also add a constructor to the class. A service's constructor accepts the following params:
722
723 1. The module's container, which you can use to resolve resources. You use it to resolve the Contentful clients you previously registered in the loader.
724 2. The options passed to the module.
725
726 In the constructor, you assign the clients and options to the class properties. You also set the default locale to `en-US` if it's not provided in the module's options.
727
728 <Note title="Order of Execution">
729
730 Since the loader is executed on application start-up, if an error occurs while connecting to Contentful, the module will not be registered and the service will not be executed. So, in the service, you're guaranteed that the clients are registered in the container and have successful connection to Contentful.
731
732 </Note>
733
734 As you implement the syncing and content retrieval features later, you'll add the necessary methods for them.
735
736 ### Export Module Definition
737
738 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.
739
740 To create the module's definition, create the file `src/modules/contentful/index.ts` with the following content:
741
742 export const moduleHighlights = [
743 ["5", "CONTENTFUL_MODULE", "The module's name."],
744 ["8", "service", "The module's service."],
745 ["9", "loaders", "The module's loaders."],
746 ]
747
748 ```ts title="src/modules/contentful/index.ts" highlights={moduleHighlights}
749 import { Module } from "@medusajs/framework/utils"
750 import ContentfulModuleService from "./service"
751 import createContentModelsLoader from "./loader/create-content-models"
752
753 export const CONTENTFUL_MODULE = "contentful"
754
755 export default Module(CONTENTFUL_MODULE, {
756 service: ContentfulModuleService,
757 loaders: [
758 createContentModelsLoader,
759 ],
760 })
761 ```
762
763 You use `Module` from the Modules SDK to create the module's definition. It accepts two parameters:
764
765 1. The module's name, which is `contentful`.
766 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.
767
768 Aside from the module definition, you export the module's name as `CONTENTFUL_MODULE` so you can reference it later.
769
770 ### Add Module to Medusa's Configurations
771
772 Once you finish building the module, add it to Medusa's configurations to start using it.
773
774 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
775
776 ```ts title="medusa-config.ts"
777 module.exports = defineConfig({
778 // ...
779 modules: [
780 {
781 resolve: "./src/modules/contentful",
782 options: {
783 management_access_token: process.env.CONTENTFUL_MANAGEMNT_ACCESS_TOKEN,
784 delivery_token: process.env.CONTENTFUL_DELIVERY_TOKEN,
785 space_id: process.env.CONTENTFUL_SPACE_ID,
786 environment: process.env.CONTENTFUL_ENVIRONMENT,
787 default_locale: "en-US",
788 },
789 },
790 ],
791 })
792 ```
793
794 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.
795
796 You also pass an `options` property with the module's options, including the Contentful's tokens for the management and delivery APIs, the Contentful's space ID, environment, and default locale.
797
798 ### Note about Locales
799
800 By default, your Contentful space will have one locale (for example, `en-US`). You can add locales as explained in the [Contentful documentation](https://www.contentful.com/help/localization/manage-locales/).
801
802 When you add a locale, make sure to:
803
804 - Set the fallback locale to the default locale (for example, `en-US`). This ensure that values are retrieved in the default locale if values for the requested locale are not available.
805 - Allow the required fields to be empty for the locale. Otherwise, you'll have to specify the values for the localized fields in each locale when you create the products later.
806
807 ![Example of the locale's settings in the Contentful dashboard](https://res.cloudinary.com/dza7lstvk/image/upload/v1744716537/Medusa%20Resources/Screenshot_2025-04-15_at_2.28.46_PM_v50lrm.png)
808
809 ### Add Environment Variables
810
811 Before you can start using the Contentful Module, you need to add the necessary environment variables used in the module's options.
812
813 Add the following environment variables to your `.env` file:
814
815 ```plain
816 CONTENTFUL_MANAGEMNT_ACCESS_TOKEN=CFPAT-...
817 CONTENTFUL_DELIVERY_TOKEN=eij...
818 CONTENTFUL_SPACE_ID=t2a...
819 CONTENTFUL_ENVIRONMENT=master
820 ```
821
822 Where:
823
824 - `CONTENTFUL_MANAGEMNT_ACCESS_TOKEN`: The Contentful management API access token. To create it on the Contentful dashboard:
825 - Click on the cog icon at the top right, then choose "CMA tokens" from the dropdown.
826
827 ![The cog icon is at the top right next to the user avatar. If you click on it, a dropdown will show where you can click on "CMA tokens".](https://res.cloudinary.com/dza7lstvk/image/upload/v1744714244/Medusa%20Resources/Screenshot_2025-04-15_at_1.48.35_PM_ct2tfk.png)
828
829 - In the CMA tokens page, click on the "Create personal access token" button.
830 - In the window that pops up, enter a name for the token, and choose an expiry date. Once you're done, click the Generate button.
831 - The token is generated and shown in the pop-up. Make sure to copy it and use it in the `.env` file, as you can't access it again.
832
833 ![Click on the copy button to copy the key](https://res.cloudinary.com/dza7lstvk/image/upload/v1744714749/Medusa%20Resources/Screenshot_2025-04-15_at_1.58.12_PM_tuugam.png)
834
835 - `CONTENTFUL_DELIVERY_TOKEN`: An API token that you can use with the delivery API. To create it on the Contentful dashboard:
836 - Click on the cog icon at the top right, then choose "API keys" from the dropdown.
837
838 ![The cog icon is at the top right next to the user avatar. If you click on it, a dropdown will show where you can click on "API keys".](https://res.cloudinary.com/dza7lstvk/image/upload/v1744714971/Medusa%20Resources/Screenshot_2025-04-15_at_2.02.31_PM_qfsn1h.png)
839
840 - In the APIs page, click on the "Add API key" button.
841 - In the window that pops up, enter a name for the token, then click the Add API Key button.
842 - This will create an API key and opens its page. On its page, copy the token for the "Content Delivery API" and use it as the value for `CONTENTFUL_DELIVERY_TOKEN`.
843
844 ![Copy the API key from the "Content Delivery API - access token" field](https://res.cloudinary.com/dza7lstvk/image/upload/v1744715228/Medusa%20Resources/Screenshot_2025-04-15_at_2.06.44_PM_ifu1mx.png)
845
846 - `CONTENTFUL_SPACE_ID`: The ID of your Contentful space. You can copy this from the dashboard's URL which is of the format `https://app.contentful.com/spaces/{space_id}/...`.
847 - `CONTENTFUL_ENVIRONMENT`: The environment to manage and retrieve the content in. By default, you have the `master` environment which you can use. However, you can use another Contentful environment that you've created.
848
849 Your module is now ready for use.
850
851 ### Test the Module
852
853 To test out the module, you'll start the Medusa application, which will run the module's loader.
854
855 To start the Medusa application, run the following command:
856
857 ```bash npm2yarn
858 npm run dev
859 ```
860
861 If the loader ran successfully, you'll see the following message in the terminal:
862
863 ```bash
864 info: Connected to Contentful
865 ```
866
867 You can also see on the Contentful dashboard that the content types were created. To view them, go to the Content Model page.
868
869 ![In the Contentful dashboard, go to the Content Model page](https://res.cloudinary.com/dza7lstvk/image/upload/v1744715783/Medusa%20Resources/Screenshot_2025-04-15_at_2.16.09_PM_w7oszm.png)
870
871 ---
872
873 ## Step 3: Create Products in Contentful
874
875 Now that you have the Contentful Module ready for use, you can start creating products in Contentful.
876
877 In this step, you'll implement the logic to create products in Contentful. Later, you'll execute it when:
878
879 - A product is created in Medusa.
880 - The admin user triggers a sync manually.
881
882 ### Add Methods to Contentful Module Service
883
884 To create products in Contentful, you need to add the necessary methods in the Contentful Module's service. Then, you can use these methods later when building the creation flow.
885
886 To create a product in Contentful, you'll need three methods: One to create the product's variants, another to create the product's options and values, and a third to create the product.
887
888 In the service at `src/modules/contentful/service.ts`, start by adding the method to create the product's variants:
889
890 ```ts title="src/modules/contentful/service.ts"
891 // imports...
892 import { ProductVariantDTO } from "@medusajs/framework/types"
893 import { EntryProps } from "contentful-management"
894
895 export default class ContentfulModuleService {
896 // ...
897
898 private async createProductVariant(
899 variants: ProductVariantDTO[],
900 productEntry: EntryProps
901 ) {
902 for (const variant of variants) {
903 await this.managementClient.entry.createWithId(
904 {
905 contentTypeId: "productVariant",
906 entryId: variant.id,
907 },
908 {
909 fields: {
910 medusaId: {
911 [this.options.default_locale!]: variant.id,
912 },
913 title: {
914 [this.options.default_locale!]: variant.title,
915 },
916 product: {
917 [this.options.default_locale!]: {
918 sys: {
919 type: "Link",
920 linkType: "Entry",
921 id: productEntry.sys.id,
922 },
923 },
924 },
925 productOptionValues: {
926 [this.options.default_locale!]: variant.options.map((option) => ({
927 sys: {
928 type: "Link",
929 linkType: "Entry",
930 id: option.id,
931 },
932 })),
933 },
934 },
935 }
936 )
937 }
938 }
939 }
940 ```
941
942 You define a private method `createProductVariant` that accepts two parameters:
943
944 1. The product's variants to create in Contentful.
945 2. The product's entry in Contentful.
946
947 In the method, you iterate over the product's variants and create a new entry in Contentful for each variant. You set the fields based on the product variant content type you created earlier.
948
949 For each field, you specify the value for the default locale. In the Contentful dashboard, you can manage the values for other locales.
950
951 Next, add the method to create the product's options and values:
952
953 ```ts title="src/modules/contentful/service.ts"
954 // other imports...
955 import { ProductOptionDTO } from "@medusajs/framework/types"
956
957 export default class ContentfulModuleService {
958 // ...
959 async createOrUpdateProductOption(option: ProductOptionDTO): Promise<EntryProps> {
960 // Check if option already exists
961 let optionEntry: EntryProps
962 try {
963 optionEntry = await this.managementClient.entry.get({
964 environmentId: this.options.environment,
965 entryId: option.id,
966 })
967
968 // Update existing option
969 const valueIds: {
970 sys: {
971 type: "Link",
972 linkType: "Entry",
973 id: string
974 }
975 }[] = []
976
977 for (const value of option.values) {
978 // Create or get value entry
979 let valueEntry: EntryProps
980 try {
981 valueEntry = await this.managementClient.entry.get({
982 environmentId: this.options.environment,
983 entryId: value.id,
984 })
985
986 // Update existing value
987 await this.managementClient.entry.update(
988 {
989 entryId: value.id,
990 },
991 {
992 sys: valueEntry.sys,
993 fields: {
994 ...valueEntry.fields,
995 value: {
996 [this.options.default_locale!]: value.value,
997 },
998 medusaId: {
999 [this.options.default_locale!]: value.id,
1000 },
1001 },
1002 }
1003 )
1004 } catch (e) {
1005 // Create new value
1006 await this.managementClient.entry.createWithId(
1007 {
1008 contentTypeId: "productOptionValue",
1009 entryId: value.id,
1010 },
1011 {
1012 fields: {
1013 value: {
1014 [this.options.default_locale!]: value.value,
1015 },
1016 medusaId: {
1017 [this.options.default_locale!]: value.id,
1018 },
1019 },
1020 }
1021 )
1022 }
1023
1024 valueIds.push({
1025 sys: {
1026 type: "Link",
1027 linkType: "Entry",
1028 id: value.id,
1029 },
1030 })
1031 }
1032
1033 // Update option entry (without product link since it's global)
1034 await this.managementClient.entry.update(
1035 {
1036 entryId: option.id,
1037 },
1038 {
1039 sys: optionEntry.sys,
1040 fields: {
1041 ...optionEntry.fields,
1042 medusaId: {
1043 [this.options.default_locale!]: option.id,
1044 },
1045 title: {
1046 [this.options.default_locale!]: option.title,
1047 },
1048 values: {
1049 [this.options.default_locale!]: valueIds,
1050 },
1051 },
1052 }
1053 )
1054
1055 return optionEntry
1056 } catch (e) {
1057 // Create new option
1058 const valueIds: {
1059 sys: {
1060 type: "Link",
1061 linkType: "Entry",
1062 id: string
1063 }
1064 }[] = []
1065
1066 for (const value of option.values) {
1067 // Create value entry
1068 await this.managementClient.entry.createWithId(
1069 {
1070 contentTypeId: "productOptionValue",
1071 entryId: value.id,
1072 },
1073 {
1074 fields: {
1075 value: {
1076 [this.options.default_locale!]: value.value,
1077 },
1078 medusaId: {
1079 [this.options.default_locale!]: value.id,
1080 },
1081 },
1082 }
1083 )
1084
1085 valueIds.push({
1086 sys: {
1087 type: "Link",
1088 linkType: "Entry",
1089 id: value.id,
1090 },
1091 })
1092 }
1093
1094 // Create option entry (without product link since it's global)
1095 optionEntry = await this.managementClient.entry.createWithId(
1096 {
1097 contentTypeId: "productOption",
1098 entryId: option.id,
1099 },
1100 {
1101 fields: {
1102 medusaId: {
1103 [this.options.default_locale!]: option.id,
1104 },
1105 title: {
1106 [this.options.default_locale!]: option.title,
1107 },
1108 values: {
1109 [this.options.default_locale!]: valueIds,
1110 },
1111 },
1112 }
1113 )
1114
1115 return optionEntry
1116 }
1117 }
1118 }
1119 ```
1120
1121 You define the method `createOrUpdateProductOption` that accepts a single product option.
1122
1123 In the method, you:
1124
1125 1. Check that the option exists in Contentful.
1126 2. If so, you update the option and its values.
1127 3. Otherwise, you create a new option entry.
1128 4. You return the option entry.
1129
1130 Next, add a method to retrieve Medusa options from Contentful:
1131
1132 ```ts title="src/modules/contentful/service.ts"
1133 export default class ContentfulModuleService {
1134 // ...
1135 async getOptions(optionIds: string[]): Promise<EntryProps[]> {
1136 const options: EntryProps[] = []
1137
1138 for (const optionId of optionIds) {
1139 try {
1140 const option = await this.managementClient.entry.get({
1141 environmentId: this.options.environment,
1142 entryId: optionId,
1143 })
1144 options.push(option)
1145 } catch (error) {
1146 // Option entry doesn't exist, skip it
1147 continue
1148 }
1149 }
1150
1151 return options
1152 }
1153 }
1154 ```
1155
1156 This method retrieves Contentful option entries by their entry IDs. It's useful to retrieve existing options from Contentful.
1157
1158 Next, add a method to delete a product option:
1159
1160 ```ts title="src/modules/contentful/service.ts"
1161 import { MedusaError } from "@medusajs/framework/utils"
1162
1163 export default class ContentfulModuleService {
1164 // ...
1165 async deleteProductOption(optionId: string) {
1166 try {
1167 // Get the option entry
1168 const optionEntry = await this.managementClient.entry.get({
1169 environmentId: this.options.environment,
1170 entryId: optionId,
1171 })
1172
1173 if (!optionEntry) {
1174 return
1175 }
1176
1177 // Delete option values first
1178 const values = optionEntry.fields.values?.[this.options.default_locale!] || []
1179 for (const value of values) {
1180 try {
1181 await this.managementClient.entry.unpublish({
1182 environmentId: this.options.environment,
1183 entryId: value.sys.id,
1184 })
1185
1186 await this.managementClient.entry.delete({
1187 environmentId: this.options.environment,
1188 entryId: value.sys.id,
1189 })
1190 } catch (error) {
1191 // Value might not exist or already deleted, continue
1192 }
1193 }
1194
1195 // Delete the option entry
1196 await this.managementClient.entry.unpublish({
1197 environmentId: this.options.environment,
1198 entryId: optionId,
1199 })
1200
1201 await this.managementClient.entry.delete({
1202 environmentId: this.options.environment,
1203 entryId: optionId,
1204 })
1205 } catch (error) {
1206 throw new MedusaError(
1207 MedusaError.Types.INVALID_DATA,
1208 `Failed to delete product option from Contentful: ${error.message}`
1209 )
1210 }
1211 }
1212 }
1213 ```
1214
1215 This method deletes a product option and all its associated values from Contentful.
1216
1217 Finally, add the method to create the product:
1218
1219 ```ts title="src/modules/contentful/service.ts"
1220 // other imports...
1221 import { ProductDTO } from "@medusajs/framework/types"
1222
1223 export default class ContentfulModuleService {
1224 // ...
1225 async createProduct(
1226 product: ProductDTO
1227 ) {
1228 try {
1229 // check if product already exists
1230 const productEntry = await this.managementClient.entry.get({
1231 environmentId: this.options.environment,
1232 entryId: product.id,
1233 })
1234
1235 return productEntry
1236 } catch(e) {}
1237
1238 // Create product entry in Contentful
1239 const productEntry = await this.managementClient.entry.createWithId(
1240 {
1241 contentTypeId: "product",
1242 entryId: product.id,
1243 },
1244 {
1245 fields: {
1246 medusaId: {
1247 [this.options.default_locale!]: product.id,
1248 },
1249 title: {
1250 [this.options.default_locale!]: product.title,
1251 },
1252 description: product.description ? {
1253 [this.options.default_locale!]: {
1254 nodeType: "document",
1255 data: {},
1256 content: [
1257 {
1258 nodeType: "paragraph",
1259 data: {},
1260 content: [
1261 {
1262 nodeType: "text",
1263 value: product.description,
1264 marks: [],
1265 data: {},
1266 },
1267 ],
1268 },
1269 ],
1270 },
1271 } : undefined,
1272 subtitle: product.subtitle ? {
1273 [this.options.default_locale!]: product.subtitle,
1274 } : undefined,
1275 handle: product.handle ? {
1276 [this.options.default_locale!]: product.handle,
1277 } : undefined,
1278 },
1279 }
1280 )
1281
1282 // Reference existing options (options are now global and created separately)
1283 // We just link to them if they exist
1284 const optionLinks: {
1285 sys: {
1286 type: "Link",
1287 linkType: "Entry",
1288 id: string
1289 }
1290 }[] = []
1291
1292 if (product.options?.length) {
1293 for (const option of product.options) {
1294 try {
1295 // Check if option exists in Contentful
1296 await this.managementClient.entry.get({
1297 environmentId: this.options.environment,
1298 entryId: option.id,
1299 })
1300 optionLinks.push({
1301 sys: {
1302 type: "Link",
1303 linkType: "Entry",
1304 id: option.id,
1305 },
1306 })
1307 } catch (e) {
1308 // Option doesn't exist yet, skip it (should be created separately)
1309 }
1310 }
1311 }
1312
1313 // Create variants if they exist
1314 if (product.variants?.length) {
1315 await this.createProductVariant(product.variants, productEntry)
1316 }
1317
1318 // update product entry with variants and options
1319 await this.managementClient.entry.update(
1320 {
1321 entryId: productEntry.sys.id,
1322 },
1323 {
1324 sys: productEntry.sys,
1325 fields: {
1326 ...productEntry.fields,
1327 productVariants: {
1328 [this.options.default_locale!]: product.variants?.map((variant) => ({
1329 sys: {
1330 type: "Link",
1331 linkType: "Entry",
1332 id: variant.id,
1333 },
1334 })),
1335 },
1336 productOptions: {
1337 [this.options.default_locale!]: optionLinks,
1338 },
1339 },
1340 }
1341 )
1342
1343 return productEntry
1344 }
1345 }
1346 ```
1347
1348 You define a public method `createProduct` that accepts a product object as a parameter.
1349
1350 In the method, you first check that the product exists in Contentful. If so, you return the existing product entry. Otherwise, you create a new product entry with the fields based on the product content type you created earlier.
1351
1352 Then, you reference existing product options by linking to them if they exist in Contentful.
1353
1354 Finally, you create entries for the product's variants using the method you created earlier and update the product entry with the variant and option links.
1355
1356 Finally, you update the product entry to reference the variants and options in Contentful.
1357
1358 You now have all the methods to create products in Contentful. You'll also need one last method to delete a product in Contentful. This is useful when you implement the rollback mechanism in the flow that creates the products.
1359
1360 Add the following method to the service:
1361
1362 export const deleteProductHighlights = [
1363 ["9", "get", "Try to retrieve the existing product entry in Contentful."],
1364 ["19", "unpublish", "Unpublish the product entry."],
1365 ["24", "delete", "Delete the product entry."],
1366 ["31", "unpublish", "Unpublish the product variant entries."],
1367 ["36", "delete", "Delete the product variant entries."],
1368 ]
1369
1370 ```ts title="src/modules/contentful/service.ts" highlights={deleteProductHighlights}
1371 // other imports...
1372 import { MedusaError } from "@medusajs/framework/utils"
1373
1374 export default class ContentfulModuleService {
1375 // ...
1376 async deleteProduct(productId: string) {
1377 try {
1378 // Get the product entry
1379 const productEntry = await this.managementClient.entry.get({
1380 environmentId: this.options.environment,
1381 entryId: productId,
1382 })
1383
1384 if (!productEntry) {
1385 return
1386 }
1387
1388 // Delete the product entry
1389 await this.managementClient.entry.unpublish({
1390 environmentId: this.options.environment,
1391 entryId: productId,
1392 })
1393
1394 await this.managementClient.entry.delete({
1395 environmentId: this.options.environment,
1396 entryId: productId,
1397 })
1398
1399 // Delete the product variant entries
1400 for (const variant of productEntry.fields.productVariants[this.options.default_locale!]) {
1401 await this.managementClient.entry.unpublish({
1402 environmentId: this.options.environment,
1403 entryId: variant.sys.id,
1404 })
1405
1406 await this.managementClient.entry.delete({
1407 environmentId: this.options.environment,
1408 entryId: variant.sys.id,
1409 })
1410 }
1411 } catch (error) {
1412 throw new MedusaError(
1413 MedusaError.Types.INVALID_DATA,
1414 `Failed to delete product from Contentful: ${error.message}`
1415 )
1416 }
1417 }
1418 }
1419 ```
1420
1421 You define a public method `deleteProduct` that accepts a product ID as a parameter.
1422
1423 In the method, you retrieve the product entry from Contentful and delete it along with its variant entries.
1424
1425 You now have all the methods necessary to build the creation flow.
1426
1427 ### Create Contentful Product Workflow
1428
1429 To implement the logic that's triggered when a product is created in Medusa, or when the admin user triggers a sync manually, you need to create a workflow.
1430
1431 A [workflow](!docs!/learn/fundamentals/workflows) is a series of actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features.
1432
1433 <Note>
1434
1435 Learn more about workflows in the [Workflows documentation](!docs!/learn/fundamentals/workflows).
1436
1437 </Note>
1438
1439 In this section, you'll create a workflow that creates Medusa products in Contentful using the Contentful Module.
1440
1441 The workflow has the following steps:
1442
1443 <WorkflowDiagram
1444 workflow={{
1445 name: "createProductsContentfulWorkflow",
1446 steps: [
1447 {
1448 type: "step",
1449 name: "useQueryGraphStep",
1450 description: "Retrieve products to create in Contentful.",
1451 link: "/references/helper-steps/useQueryGraphStep",
1452 depth: 1
1453 },
1454 {
1455 type: "step",
1456 name: "getOptionsContentfulStep",
1457 description: "Get the existing options in Contentful.",
1458 depth: 2
1459 },
1460 {
1461 type: "when",
1462 condition: "data.newOptions.length > 0",
1463 steps: [
1464 {
1465 type: "step",
1466 name: "createProductOptionsContentfulStep",
1467 description: "Create new product options in Contentful.",
1468 depth: 1
1469 }
1470 ],
1471 depth: 3
1472 },
1473 {
1474 type: "step",
1475 name: "createProductsContentfulStep",
1476 description: "Create the products in Contentful.",
1477 depth: 4
1478 }
1479 ]
1480 }}
1481 hideLegend
1482 />
1483
1484 Medusa provides the `useQueryGraphStep` in its `@medusajs/medusa/core-flows` package. You need to implement the steps to create options and products.
1485
1486 #### getOptionsContentfulStep
1487
1488 The first step is to get the existing options in Contentful.
1489
1490 To create the step, create the file `src/workflows/steps/get-options-contentful.ts` with the following content:
1491
1492 ```ts title="src/workflows/steps/get-options-contentful.ts"
1493 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1494 import ContentfulModuleService from "../../modules/contentful/service"
1495 import { CONTENTFUL_MODULE } from "../../modules/contentful"
1496
1497 type StepInput = {
1498 option_ids: string[]
1499 }
1500
1501 export const getOptionsContentfulStep = createStep(
1502 "get-options-contentful-step",
1503 async (input: StepInput, { container }) => {
1504 const contentfulModuleService: ContentfulModuleService =
1505 container.resolve(CONTENTFUL_MODULE)
1506
1507 const options = await contentfulModuleService.getOptions(input.option_ids)
1508
1509 return new StepResponse(options)
1510 }
1511 )
1512 ```
1513
1514 You create a step with `createStep` from the Workflows SDK. It accepts three parameters:
1515
1516 1. The step's unique name, which is `get-options-contentful-step`.
1517 2. An async function that receives two parameters:
1518 - The step's input, which is in this case an object holding an array of option IDs to retrieve from Contentful.
1519 - 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.
1520
1521 <Note>
1522
1523 The Medusa container is different from the module's container. Since modules are isolated, they each have a container with their resources. Refer to the [Module Container](!docs!/learn/fundamentals/modules/container) documentation for more information.
1524
1525 </Note>
1526
1527 In the step function, you resolve the Contentful Module's service from the Medusa container using the name you exported in the module definition's file.
1528
1529 Then, you retrieve the options from Contentful using the `getOptions` method you created earlier.
1530
1531 A step function must return a `StepResponse` instance that accepts the step's output, which are the options retrieved from Contentful.
1532
1533 #### createProductOptionsContentfulStep
1534
1535 Next, you'll create a step to create product options in Contentful.
1536
1537 To create the step, create the file `src/workflows/steps/create-product-options-contentful.ts` with the following content:
1538
1539 ```ts title="src/workflows/steps/create-product-options-contentful.ts"
1540 import { ProductOptionDTO } from "@medusajs/framework/types"
1541 import { CONTENTFUL_MODULE } from "../../modules/contentful"
1542 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1543 import ContentfulModuleService from "../../modules/contentful/service"
1544 import { EntryProps } from "contentful-management"
1545
1546 type StepInput = {
1547 options: ProductOptionDTO[]
1548 }
1549
1550 export const createProductOptionsContentfulStep = createStep(
1551 "create-product-options-contentful-step",
1552 async (input: StepInput, { container }) => {
1553 const contentfulModuleService: ContentfulModuleService =
1554 container.resolve(CONTENTFUL_MODULE)
1555
1556 const options: EntryProps[] = []
1557
1558 try {
1559 for (const option of input.options) {
1560 options.push(await contentfulModuleService.createOrUpdateProductOption(option))
1561 }
1562 } catch(e) {
1563 return StepResponse.permanentFailure(
1564 `Error creating product options in Contentful: ${e.message}`,
1565 options
1566 )
1567 }
1568
1569 return new StepResponse(
1570 options,
1571 options
1572 )
1573 },
1574 async (options, { container }) => {
1575 if (!options) {
1576 return
1577 }
1578
1579 const contentfulModuleService: ContentfulModuleService =
1580 container.resolve(CONTENTFUL_MODULE)
1581
1582 // Delete options that were created during this step
1583 for (const option of options) {
1584 try {
1585 await contentfulModuleService.deleteProductOption(option.sys.id)
1586 } catch (error) {
1587 // Option might not exist or already deleted, continue
1588 }
1589 }
1590 }
1591 )
1592 ```
1593
1594 This step creates or updates product options in Contentful using the `createOrUpdateProductOption` method.
1595
1596 You also pass a compensation function as a third parameter to `createStep`. It receives the created options as a parameter and deletes them from Contentful using the `deleteProductOption` method you created earlier.
1597
1598 <Note>
1599
1600 Learn more about compensation functions in the [Workflows documentation](!docs!/learn/fundamentals/workflows/compensation-function).
1601
1602 </Note>
1603
1604 #### createProductsContentfulStep
1605
1606 Next, you'll create the step to create products in Contentful.
1607
1608 To create the step, create the file `src/workflows/steps/create-products-contentful.ts` with the following content:
1609
1610 <Note>
1611
1612 If you get a type error on resolving the Contentful 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).
1613
1614 </Note>
1615
1616 export const createProductsContentfulStepHighlights = [
1617 ["12", `"create-products-contentful-step"`, "The step's unique name."],
1618 ["13", "input", "The step's input."],
1619 ["15", "container", "The Medusa container, useful to resolve Framework and commerce tools."],
1620 ["15", "resolve", "Resolve the Contentful Module's service from the Medusa container."],
1621 ["21", "createProduct", "Create a new product entry in Contentful."],
1622 ["24", "permanentFailure", "If an error occurs, fail the step and\npass the created products to the compensation function."],
1623 ["31", "products", "Return the created products."],
1624 ["32", "products", "Pass the created products to the compensation function."],
1625 ["44", "deleteProduct", "Delete the created product entries in Contentful\nif an error occurs."],
1626 ]
1627
1628 ```ts title="src/workflows/steps/create-products-contentful.ts" highlights={createProductsContentfulStepHighlights}
1629 import { ProductDTO } from "@medusajs/framework/types"
1630 import { CONTENTFUL_MODULE } from "../../modules/contentful"
1631 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1632 import ContentfulModuleService from "../../modules/contentful/service"
1633 import { EntryProps } from "contentful-management"
1634
1635 type StepInput = {
1636 products: ProductDTO[]
1637 }
1638
1639 export const createProductsContentfulStep = createStep(
1640 "create-products-contentful-step",
1641 async (input: StepInput, { container }) => {
1642 const contentfulModuleService: ContentfulModuleService =
1643 container.resolve(CONTENTFUL_MODULE)
1644
1645 const products: EntryProps[] = []
1646
1647 try {
1648 for (const product of input.products) {
1649 products.push(await contentfulModuleService.createProduct(product))
1650 }
1651 } catch(e) {
1652 return StepResponse.permanentFailure(
1653 `Error creating products in Contentful: ${e.message}`,
1654 products
1655 )
1656 }
1657
1658 return new StepResponse(
1659 products,
1660 products
1661 )
1662 },
1663 async (products, { container }) => {
1664 if (!products) {
1665 return
1666 }
1667
1668 const contentfulModuleService: ContentfulModuleService =
1669 container.resolve(CONTENTFUL_MODULE)
1670
1671 for (const product of products) {
1672 await contentfulModuleService.deleteProduct(product.sys.id)
1673 }
1674 }
1675 )
1676 ```
1677
1678 This step receives the products to create in Contentful and creates a new entry in Contentful for each product using the `createProduct` method you created earlier. If the creation of any product fails, you fail the step and pass the created products to the compensation function.
1679
1680 The compensation function accepts as a parameter the created product entries.
1681
1682 In the compensation function, you iterate over the created product entries and delete them from Contentful using the `deleteProduct` method you created earlier.
1683
1684 #### Create the Workflow
1685
1686 Now that you have all the necessary steps, you can create the workflow.
1687
1688 To create the workflow, create the file `src/workflows/create-products-contentful.ts` with the following content:
1689
1690 ```ts title="src/workflows/create-products-contentful.ts"
1691 import { createWorkflow, WorkflowResponse, transform, when } from "@medusajs/framework/workflows-sdk"
1692 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1693 import { createProductsContentfulStep } from "./steps/create-products-contentful"
1694 import { createProductOptionsContentfulStep } from "./steps/create-product-options-contentful"
1695 import { getOptionsContentfulStep } from "./steps/get-options-contentful"
1696 import { ProductDTO, ProductOptionDTO } from "@medusajs/framework/types"
1697
1698 type WorkflowInput = {
1699 product_ids: string[]
1700 }
1701
1702 export const createProductsContentfulWorkflow = createWorkflow(
1703 { name: "create-products-contentful-workflow" },
1704 (input: WorkflowInput) => {
1705 const { data: products } = useQueryGraphStep({
1706 entity: "product",
1707 fields: [
1708 "id",
1709 "title",
1710 "description",
1711 "subtitle",
1712 "handle",
1713 "variants.id",
1714 "variants.title",
1715 "variants.options.id",
1716 "variants.options.value",
1717 "variants.options.option_id",
1718 "options.id",
1719 "options.title",
1720 "options.product_id",
1721 "options.values.id",
1722 "options.values.value",
1723 ],
1724 filters: {
1725 id: input.product_ids,
1726 },
1727 })
1728
1729 // Extract unique options from products using transform
1730 const uniqueOptions = transform(
1731 { products },
1732 (data): ProductOptionDTO[] => {
1733 const productData = data.products as unknown as ProductDTO[]
1734 const optionsMap = new Map<string, ProductOptionDTO>()
1735
1736 productData.forEach((product) => {
1737 product.options?.forEach((option) => {
1738 if (!optionsMap.has(option.id)) {
1739 optionsMap.set(option.id, option)
1740 }
1741 })
1742 })
1743
1744 return Array.from(optionsMap.values())
1745 }
1746 )
1747
1748 // Get existing options from Contentful
1749 const optionIds = transform(
1750 { uniqueOptions },
1751 (data) => data.uniqueOptions.map((option) => option.id)
1752 )
1753
1754 const existingOptions = getOptionsContentfulStep({
1755 option_ids: optionIds,
1756 })
1757
1758 // Filter out existing options and only create new ones
1759 const newOptions = transform(
1760 { uniqueOptions, existingOptions },
1761 (data) => {
1762 const existingIdsSet = new Set(data.existingOptions.map((option) => option.sys.id))
1763 return data.uniqueOptions.filter(
1764 (option) => !existingIdsSet.has(option.id)
1765 )
1766 }
1767 )
1768
1769 // Only create options that don't already exist in Contentful
1770 when({ newOptions }, (data) => data.newOptions.length > 0)
1771 .then(() => {
1772 createProductOptionsContentfulStep({
1773 options: newOptions,
1774 })
1775 })
1776
1777 // Then sync products (which will reference the options)
1778 const contentfulProducts = createProductsContentfulStep({
1779 products: products as unknown as ProductDTO[],
1780 })
1781
1782 return new WorkflowResponse(contentfulProducts)
1783 }
1784 )
1785 ```
1786
1787 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
1788
1789 It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case the product IDs to create in Contentful.
1790
1791 In the workflow's constructor function, you:
1792
1793 1. Retrieve the Medusa products using the `useQueryGraphStep` helper step. This step uses Medusa's [Query](!docs!/learn/fundamentals/query) tool to retrieve data across modules. You pass it the product IDs to retrieve.
1794 2. Extract unique options from all products using `transform`.
1795 3. Extract option IDs from the unique options using `transform`.
1796 4. Get the existing options from Contentful using the `getOptionsContentfulStep` step.
1797 5. Filter out the existing options and only create new ones using `transform`.
1798 6. Create the new options in Contentful using the `createProductOptionsContentfulStep` step (conditionally with `when`).
1799 7. Create the product entries in Contentful using the `createProductsContentfulStep` step.
1800
1801 A workflow must return an instance of `WorkflowResponse`. The `WorkflowResponse` constructor accepts the workflow's output as a parameter, which is the product entries created in Contentful.
1802
1803 You now have the workflow that you can execute when a product is created in Medusa, or when the admin user triggers a sync manually.
1804
1805 ---
1806
1807 ## Step 4: Trigger Sync on Product Creation
1808
1809 Medusa has an event system that allows you to listen for events, such as `product.created`, and perform an asynchronous action when the event is emitted.
1810
1811 You listen to events in a subscriber. A [subscriber](!docs!/learn/fundamentals/events-and-subscribers) is an asynchronous function that listens to one or more events and performs actions when these events are emitted. A subscriber is useful when syncing data across systems, as the operation can be time-consuming and should be performed in the background.
1812
1813 In this step, you'll create a subscriber that listens to the `product.created` event and executes the `createProductsContentfulWorkflow` workflow.
1814
1815 <Note>
1816
1817 Learn more about subscribers in the [Events and Subscribers documentation](!docs!/learn/fundamentals/events-and-subscribers).
1818
1819 </Note>
1820
1821 To create a subscriber, create the file `src/subscribers/create-product.ts` with the following content:
1822
1823 export const createProductSubscriberHighlights = [
1824 ["9", "handleProductCreate", "The subscriber function."],
1825 ["10", "data", "The event's data payload."],
1826 ["13", "createProductsContentfulWorkflow", "Create the product entries in Contentful."],
1827 ["24", `"product.created"`, "The event the subscriber listens to."],
1828 ]
1829
1830 ```ts title="src/subscribers/create-product.ts" highlights={createProductSubscriberHighlights}
1831 import {
1832 type SubscriberConfig,
1833 type SubscriberArgs,
1834 } from "@medusajs/framework"
1835 import {
1836 createProductsContentfulWorkflow,
1837 } from "../workflows/create-products-contentful"
1838
1839 export default async function handleProductCreate({
1840 event: { data },
1841 container,
1842 }: SubscriberArgs<{ id: string }>) {
1843 await createProductsContentfulWorkflow(container)
1844 .run({
1845 input: {
1846 product_ids: [data.id],
1847 },
1848 })
1849
1850 console.log("Product created in Contentful")
1851 }
1852
1853 export const config: SubscriberConfig = {
1854 event: "product.created",
1855 }
1856 ```
1857
1858 A subscriber file must export:
1859
1860 1. An asynchronous function, which is the subscriber that is executed when the event is emitted.
1861 2. A configuration object that holds the name of the event the subscriber listens to, which is `product.created` in this case.
1862
1863 The subscriber function receives an object as a parameter that has the following properties:
1864
1865 - `event`: An object that holds the event's data payload. The payload of the `product.created` event is an array of product IDs.
1866 - `container`: The Medusa container to access the Framework and commerce tools.
1867
1868 In the subscriber function, you execute the `createProductsContentfulWorkflow` by invoking it, passing the Medusa container as a parameter. Then, you chain a `run` method, passing it the product ID from the event's data payload as input.
1869
1870 Finally, you log a message to the console to indicate that the product was created in Contentful.
1871
1872 ### Test the Subscriber
1873
1874 To test out the subscriber, start the Medusa application:
1875
1876 ```bash npm2yarn
1877 npm run dev
1878 ```
1879
1880 Then, open the Medusa Admin dashboard and login.
1881
1882 <Note>
1883
1884 Can't remember the credentials? Learn how to create a user in the [Medusa CLI reference](../../../medusa-cli/commands/user/page.mdx).
1885
1886 </Note>
1887
1888 Next, open the Products page and create a new product.
1889
1890 You should see the following message in the terminal:
1891
1892 ```bash
1893 info: Product created in Contentful
1894 ```
1895
1896 You can also see the product in the Contentful dashboard by going to the Content page.
1897
1898 ---
1899
1900 ## Step 5: Trigger Product Sync Manually
1901
1902 The other way to sync products is when the admin user triggers a sync manually. This is useful when you already have products in Medusa and you want to sync them to Contentful.
1903
1904 To allow admin users to trigger a sync manually, you need:
1905
1906 1. A subscriber that listens to a custom event.
1907 2. An API route that emits the custom event when a request is sent to it.
1908 3. A UI route in the Medusa Admin that displays a button to trigger the sync.
1909
1910 ### Create Manual Sync Subscriber
1911
1912 You'll start by creating the subscriber that listens to a custom event to sync the Medusa products to Contentful.
1913
1914 To create the subscriber, create the file `src/subscribers/sync-products.ts` with the following content:
1915
1916 export const syncProductsSubscriberHighlights = [
1917 ["13", "query", "Resolve Query from the Medusa container."],
1918 ["24", "graph", "Retrieve the Medusa products with pagination."],
1919 ["36", "createProductsContentfulWorkflow", "Create the product entries in Contentful."],
1920 ["52", `"products.sync"`, "The custom event to listen to."],
1921 ]
1922
1923 ```ts title="src/subscribers/sync-products.ts" highlights={syncProductsSubscriberHighlights}
1924 import type {
1925 SubscriberConfig,
1926 SubscriberArgs,
1927 } from "@medusajs/framework"
1928 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
1929 import {
1930 createProductsContentfulWorkflow,
1931 } from "../workflows/create-products-contentful"
1932
1933 export default async function syncProductsHandler({
1934 container,
1935 }: SubscriberArgs<Record<string, unknown>>) {
1936 const query = container.resolve(ContainerRegistrationKeys.QUERY)
1937
1938 const batchSize = 100
1939 let hasMore = true
1940 let offset = 0
1941 let totalCount = 0
1942
1943 while (hasMore) {
1944 const {
1945 data: products,
1946 metadata: { count } = {},
1947 } = await query.graph({
1948 entity: "product",
1949 fields: [
1950 "id",
1951 ],
1952 pagination: {
1953 skip: offset,
1954 take: batchSize,
1955 },
1956 })
1957
1958 if (products.length) {
1959 await createProductsContentfulWorkflow(container).run({
1960 input: {
1961 product_ids: products.map((product) => product.id),
1962 },
1963 })
1964 }
1965
1966 hasMore = products.length === batchSize
1967 offset += batchSize
1968 totalCount = count ?? 0
1969 }
1970
1971 console.log(`Synced ${totalCount} products to Contentful`)
1972 }
1973
1974 export const config: SubscriberConfig = {
1975 event: "products.sync",
1976 }
1977 ```
1978
1979 You create a subscriber that listens to the `products.sync` event.
1980
1981 In the subscriber function, you use [Query](!docs!/learn/fundamentals/query) to retrieve all the products in Medusa with pagination. Then, for each batch of products, you execute the `createProductsContentfulWorkflow` workflow, passing the product IDs to the workflow.
1982
1983 Finally, you log a message to the console to indicate that the products were synced to Contentful.
1984
1985 ### Create API Route to Trigger Sync
1986
1987 Next, to allow the admin user to trigger the sync manually, you need to create an API route that emits the `products.sync` event.
1988
1989 An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts.
1990
1991 <Note>
1992
1993 Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes).
1994
1995 </Note>
1996
1997 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`.
1998
1999 So, to create an API route at the path `/admin/contentful/sync`, create the file `src/api/admin/contentful/sync/route.ts` with the following content:
2000
2001 export const syncProductsRouteHighlights = [
2002 ["7", "POST", "The route handler function that exposes a POST API route."],
2003 ["11", "eventService", "Resolve the Event Module's service from the Medusa container."],
2004 ["13", "emit", "Emit the custom event."],
2005 ]
2006
2007 ```ts title="src/api/admin/contentful/sync/route.ts" highlights={syncProductsRouteHighlights}
2008 import {
2009 MedusaRequest,
2010 MedusaResponse,
2011 } from "@medusajs/framework/http"
2012 import { Modules } from "@medusajs/framework/utils"
2013
2014 export const POST = async (
2015 req: MedusaRequest,
2016 res: MedusaResponse
2017 ) => {
2018 const eventService = req.scope.resolve(Modules.EVENT_BUS)
2019
2020 await eventService.emit({
2021 name: "products.sync",
2022 data: {},
2023 })
2024
2025 res.status(200).json({
2026 message: "Products sync triggered successfully",
2027 })
2028 }
2029 ```
2030
2031 Since you export a `POST` route handler function, you expose an `API` route at `/admin/contentful/sync`. The route handler function accepts two parameters:
2032
2033 1. A request object with details and context on the request, such as body parameters or authenticated user details.
2034 2. A response object to manipulate and send the response.
2035
2036 In the route handler, you resolve the [Event Module](../../../infrastructure-modules/event/page.mdx)'s service from the Medusa container and emit the `products.sync` event.
2037
2038 ### Create UI Route to Trigger Sync
2039
2040 Finally, you'll add a new page to the Medusa Admin dashboard that displays a button to trigger the sync. To add a page, you need to create a UI route.
2041
2042 A [UI route](!docs!/learn/fundamentals/admin/ui-routes) is a React component that specifies the content to be shown in a new page of the Medusa Admin dashboard. You'll create a UI route to display a button that triggers product syncing to Contentful when clicked.
2043
2044 <Note>
2045
2046 Refer to the [UI Routes](!docs!/learn/fundamentals/admin/ui-routes) documentation for more information.
2047
2048 </Note>
2049
2050 #### Configure JS SDK
2051
2052 Before creating the UI route, you'll configure Medusa's [JS SDK](../../../js-sdk/page.mdx) so that you can use it to send requests to the Medusa server.
2053
2054 The JS SDK is installed by default in your Medusa application. To configure it, create the file `src/admin/lib/sdk.ts` with the following content:
2055
2056 ```ts title="src/admin/lib/sdk.ts"
2057 import Medusa from "@medusajs/js-sdk"
2058
2059 export const sdk = new Medusa({
2060 baseUrl: "http://localhost:9000",
2061 debug: import.meta.env.NODE_ENV === "development",
2062 auth: {
2063 type: "session",
2064 },
2065 })
2066 ```
2067
2068 You create an instance of the JS SDK using the `Medusa` class from the JS SDK. You pass it an object having the following properties:
2069
2070 - `baseUrl`: The base URL of the Medusa server.
2071 - `debug`: A boolean indicating whether to log debug information into the console.
2072 - `auth`: An object specifying the authentication type. When using the JS SDK for admin customizations, you use the `session` authentication type.
2073
2074 #### Create UI Route
2075
2076 UI routes are created in a `page.tsx` file under a sub-directory of `src/admin/routes` directory. The file's path relative to `src/admin/routes` determines its path in the dashboard.
2077
2078 So, create the file `src/admin/routes/contentful/page.tsx` with the following content:
2079
2080 export const contentfulPageHighlights = [
2081 ["7", "ContentfulSettingsPage", "The React component that defines the content of the page."],
2082 ["8", "mutate", "A function that sends a request to\nthe API route to trigger the sync."],
2083 ["25", "Button", "The button that triggers the syncing."],
2084 ["38", "defineRouteConfig", "A function that defines the route's configuration."],
2085 ]
2086
2087 ```tsx title="src/admin/routes/contentful/page.tsx" highlights={contentfulPageHighlights}
2088 import { defineRouteConfig } from "@medusajs/admin-sdk"
2089 import { Container, Heading, Button } from "@medusajs/ui"
2090 import { useMutation } from "@tanstack/react-query"
2091 import { sdk } from "../../lib/sdk"
2092 import { toast } from "@medusajs/ui"
2093
2094 const ContentfulSettingsPage = () => {
2095 const { mutate, isPending } = useMutation({
2096 mutationFn: () =>
2097 sdk.client.fetch("/admin/contentful/sync", {
2098 method: "POST",
2099 }),
2100 onSuccess: () => {
2101 toast.success("Sync to Contentful triggered successfully")
2102 },
2103 })
2104
2105 return (
2106 <Container className="p-6">
2107 <div className="flex flex-col gap-y-4">
2108 <div>
2109 <Heading level="h1">Contentful Settings</Heading>
2110 </div>
2111 <div>
2112 <Button
2113 variant="primary"
2114 onClick={() => mutate()}
2115 isLoading={isPending}
2116 >
2117 Sync to Contentful
2118 </Button>
2119 </div>
2120 </div>
2121 </Container>
2122 )
2123 }
2124
2125 export const config = defineRouteConfig({
2126 label: "Contentful",
2127 })
2128
2129 export default ContentfulSettingsPage
2130 ```
2131
2132 A UI route's file must export:
2133
2134 1. A React component that defines the content of the page.
2135 2. A configuration object that specifies the route's label in the dashboard. This label is used to show a sidebar item for the new route.
2136
2137 In the React component, you use `useMutation` hook from `@tanstack/react-query` to create a mutation that sends a `POST` request to the API route you created earlier. In the mutation function, you use the JS SDK to send the request.
2138
2139 Then, in the return statement, you display a button that triggers the mutation when clicked, which sends a request to the API route you created earlier.
2140
2141 ### Test the Sync
2142
2143 To test out the sync, start the Medusa application:
2144
2145 ```bash npm2yarn
2146 npm run dev
2147 ```
2148
2149 Then, open the Medusa Admin dashboard and login. In the sidebar, you'll find a new "Contentful" item. If you click on it, you'll see the page you created with the button to trigger the sync.
2150
2151 ![The Contentful page in the Medusa Admin dashboard with a button to trigger the sync](https://res.cloudinary.com/dza7lstvk/image/upload/v1744718825/Medusa%20Resources/Screenshot_2025-04-15_at_3.06.53_PM_va8e20.png)
2152
2153 If you click on the button, you'll see the following message in the terminal:
2154
2155 ```bash
2156 info: Synced 4 products to Contentful
2157 ```
2158
2159 Assuming you have `4` products in Medusa, the message indicates that the sync was successful.
2160
2161 You can also see the products in the Contentful dashboard.
2162
2163 ![The Contentful dashboard showing the synced products](https://res.cloudinary.com/dza7lstvk/image/upload/v1744718896/Medusa%20Resources/Screenshot_2025-04-15_at_3.08.02_PM_qexr0x.png)
2164
2165 ---
2166
2167 ## Step 6: Retrieve Locales API Route
2168
2169 In the next steps, you'll implement customizations that are useful for storefronts. A storefront should show the customer a list of available locales and allow them to select from them.
2170
2171 In this step, you will:
2172
2173 1. Add the logic to retrieve locales from Contentful in the Contentful Module's service.
2174 2. Create an API route that exposes the locales to the storefront.
2175 3. Customize the Next.js Starter Storefront to show the locales to customers.
2176
2177 ### Retrieve Locales from Contentful Method
2178
2179 You'll start by adding two methods to the Contentful Module's service that are useful to retrieve locales from Contentful.
2180
2181 The first method retrieves all locales from Contentful. Add it to the service at `src/modules/contentful/service.ts`:
2182
2183 ```ts title="src/modules/contentful/service.ts"
2184 export default class ContentfulModuleService {
2185 // ...
2186 async getLocales() {
2187 return await this.managementClient.locale.getMany({})
2188 }
2189 }
2190 ```
2191
2192 You use the `locale.getMany` method of the Contentful Management API client to retrieve all locales.
2193
2194 The second method returns the code of the default locale:
2195
2196 ```ts title="src/modules/contentful/service.ts"
2197 export default class ContentfulModuleService {
2198 // ...
2199 async getDefaultLocaleCode() {
2200 return this.options.default_locale
2201 }
2202 }
2203 ```
2204
2205 You return the default locale using the `default_locale` option you set in the module's options.
2206
2207 ### Create API Route to Retrieve Locales
2208
2209 Next, you'll create an API route that exposes the locales to the storefront.
2210
2211 To create the API route, create the file `src/api/store/locales/route.ts` with the following content:
2212
2213 export const getLocalesRouteHighlights = [
2214 ["12", "contentfulModuleService", "Resolve the Contentful Module's service from the Medusa container."],
2215 ["16", "locales", "Retrieve the locales from Contentful."],
2216 ["17", "defaultLocaleCode", "Retrieve the default locale code from the module's options."],
2217 ["19", "formattedLocales", "Format the locales to include their name, code, and whether they are the default locale."],
2218 ]
2219
2220 ```ts title="src/api/store/locales/route.ts" highlights={getLocalesRouteHighlights}
2221 import {
2222 MedusaRequest,
2223 MedusaResponse,
2224 } from "@medusajs/framework/http"
2225 import { CONTENTFUL_MODULE } from "../../../modules/contentful"
2226 import ContentfulModuleService from "../../../modules/contentful/service"
2227
2228 export const GET = async (
2229 req: MedusaRequest,
2230 res: MedusaResponse
2231 ) => {
2232 const contentfulModuleService: ContentfulModuleService = req.scope.resolve(
2233 CONTENTFUL_MODULE
2234 )
2235
2236 const locales = await contentfulModuleService.getLocales()
2237 const defaultLocaleCode = await contentfulModuleService.getDefaultLocaleCode()
2238
2239 const formattedLocales = locales.items.map((locale) => {
2240 return {
2241 name: locale.name,
2242 code: locale.code,
2243 is_default: locale.code === defaultLocaleCode,
2244 }
2245 })
2246
2247 res.json({
2248 locales: formattedLocales,
2249 })
2250 }
2251 ```
2252
2253 Since you export a `GET` route handler function, you expose a `GET` route at `/store/locales`.
2254
2255 In the route handler, you resolve the Contentful Module's service from the Medusa container to retrieve the locales and the default locale code.
2256
2257 Then, you format the locales to include their name, code, and whether they are the default locale.
2258
2259 Finally, you return the formatted locales in the JSON response.
2260
2261 ### Customize Storefront to Show Locales
2262
2263 In the first step of this tutorial, you installed the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) along with the Medusa application. This storefront provides ecommerce features like a product catalog, a cart, and a checkout.
2264
2265 In this section, you'll customize the storefront to show the locales to customers and allow them to select from them. The selected locale will be stored in the browser's cookies, allowing you to use it later when retrieving a product's localized data.
2266
2267 <Note title="Reminder" forceMultiline>
2268
2269 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
2270
2271 ```bash
2272 cd apps/storefront
2273 ```
2274
2275 </Note>
2276
2277 #### Add Cookie Functions
2278
2279 You'll start by adding two functions that retrieve and set the locale in the browser's cookies.
2280
2281 In `src/lib/data/cookies.ts` add the following functions:
2282
2283 export const getLocaleHighlights = [
2284 ["1", "getLocale", "Retrieve the locale from the browser's cookies."],
2285 ["6", "setLocale", "Set the locale in the browser's cookies."],
2286 ]
2287
2288 ```ts title="src/lib/data/cookies.ts" highlights={getLocaleHighlights} badgeLabel="Storefront" badgeColor="blue"
2289 export const getLocale = async () => {
2290 const cookies = await nextCookies()
2291 return cookies.get("_medusa_locale")?.value
2292 }
2293
2294 export const setLocale = async (locale: string) => {
2295 const cookies = await nextCookies()
2296 cookies.set("_medusa_locale", locale, {
2297 maxAge: 60 * 60 * 24 * 7,
2298 })
2299 }
2300 ```
2301
2302 The `getLocale` function retrieves the locale from the browser's cookies, and the `setLocale` function sets the locale in the browser's cookies.
2303
2304 #### Manage Locales Functions
2305
2306 Next, you'll add server actions to retrieve the locales and set the selected locale.
2307
2308 Create the file `src/lib/data/locale.ts` with the following content:
2309
2310 export const getLocalesHighlights = [
2311 ["13", "getLocales", "Retrieve the locales from the Medusa server."],
2312 ["19", "getSelectedLocale", "Retrieve the selected locale either from the browser's cookies\nor the default locale."],
2313 ["28", "setSelectedLocale", "Set the selected locale in the browser's cookies."],
2314 ]
2315
2316 ```ts title="src/lib/data/locale.ts" highlights={getLocalesHighlights} badgeLabel="Storefront" badgeColor="blue"
2317 "use server"
2318
2319 import { sdk } from "@lib/config"
2320 import type { Document } from "@contentful/rich-text-types"
2321 import { getLocale, setLocale } from "./cookies"
2322
2323 export type Locale = {
2324 name: string
2325 code: string
2326 is_default: boolean
2327 }
2328
2329 export async function getLocales() {
2330 return await sdk.client.fetch<{
2331 locales: Locale[]
2332 }>("/store/locales")
2333 }
2334
2335 export async function getSelectedLocale() {
2336 let localeCode = await getLocale()
2337 if (!localeCode) {
2338 const locales = await getLocales()
2339 localeCode = locales.locales.find((l) => l.is_default)?.code
2340 }
2341 return localeCode
2342 }
2343
2344 export async function setSelectedLocale(locale: string) {
2345 await setLocale(locale)
2346 }
2347 ```
2348
2349 You add the following functions:
2350
2351 1. `getLocales`: Retrieves the locales from the Medusa server using the API route you created earlier.
2352 2. `getSelectedLocale`: Retrieves the selected locale from the browser's cookies, or the default locale if no locale is selected.
2353 3. `setSelectedLocale`: Sets the selected locale in the browser's cookies.
2354
2355 You'll use these functions as you add the UI to show the locales next.
2356
2357 #### Show Locales in the Storefront
2358
2359 You'll now add the UI to show the locales to customers and allow them to select from them.
2360
2361 Create the file `src/modules/layout/components/locale-select/index.tsx` with the following content:
2362
2363 export const localeSelectHighlights = [
2364 ["9", "LocaleSelect", "The React component that defines the locale selector."],
2365 ["10", "locales", "The list of locales retrieved from the Medusa server."],
2366 ["11", "locale", "The selected locale."],
2367 ["12", "open", "A boolean indicating whether the dropdown is open."],
2368 ["14", "useEffect", "Retrieve the locales and set them in the `locales` state variable."],
2369 ["21", "useEffect", "Set the selected locale after the locales are retrieved."],
2370 ["32", "useEffect", "Set the newly selected locale in the browser's cookies."],
2371 ["38", "handleChange", "Set the selected locale and close the dropdown."],
2372 ]
2373
2374 ```tsx title="src/modules/layout/components/locale-select/index.tsx" highlights={localeSelectHighlights} badgeLabel="Storefront" badgeColor="blue"
2375 "use client"
2376
2377 import { useState, useEffect, Fragment } from "react"
2378 import { getLocales, Locale, getSelectedLocale, setSelectedLocale } from "../../../../lib/data/locale"
2379 import { Listbox, ListboxButton, ListboxOption, ListboxOptions, Transition } from "@headlessui/react"
2380 import { ArrowRightMini } from "@medusajs/icons"
2381 import { clx } from "@medusajs/ui"
2382
2383 const LocaleSelect = () => {
2384 const [locales, setLocales] = useState<Locale[]>([])
2385 const [locale, setLocale] = useState<Locale | undefined>()
2386 const [open, setOpen] = useState(false)
2387
2388 useEffect(() => {
2389 getLocales()
2390 .then(({ locales }) => {
2391 setLocales(locales)
2392 })
2393 }, [])
2394
2395 useEffect(() => {
2396 if (!locales.length || locale) {
2397 return
2398 }
2399
2400 getSelectedLocale().then((locale) => {
2401 const localeDetails = locales.find((l) => l.code === locale)
2402 setLocale(localeDetails)
2403 })
2404 }, [locales])
2405
2406 useEffect(() => {
2407 if (locale) {
2408 setSelectedLocale(locale.code)
2409 }
2410 }, [locale])
2411
2412 const handleChange = (locale: Locale) => {
2413 setLocale(locale)
2414 setOpen(false)
2415 }
2416
2417 // TODO add return statement
2418 }
2419
2420 export default LocaleSelect
2421 ```
2422
2423 You create a `LocaleSelect` component with the following state variables:
2424
2425 1. `locales`: The list of locales retrieved from the Medusa server.
2426 2. `locale`: The selected locale.
2427 3. `open`: A boolean indicating whether the dropdown is open.
2428
2429 Then, you use three `useEffect` hooks:
2430
2431 1. The first `useEffect` hook retrieves the locales using the `getLocales` function and sets them in the `locales` state variable.
2432 2. The second `useEffect` hook is triggered when the `locales` state variable changes. It retrieves the selected locale using the `getSelectedLocale` function and sets the `locale` state variable.
2433 3. The third `useEffect` hook is triggered when the `locale` state variable changes. It sets the selected locale in the browser's cookies using the `setSelectedLocale` function.
2434
2435 You also create a `handleChange` function that sets the selected locale and closes the dropdown. You'll execute this function when the customer selects a locale from the dropdown.
2436
2437 Finally, you'll add a return statement that shows the locale dropdown. Replace the `TODO` with the following:
2438
2439 ```tsx title="src/modules/layout/components/locale-select/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2440 return (
2441 <div
2442 className="flex justify-between"
2443 onMouseEnter={() => setOpen(true)}
2444 onMouseLeave={() => setOpen(false)}
2445 >
2446 <div>
2447 <Listbox as="span" onChange={handleChange} defaultValue={locale}>
2448 <ListboxButton className="py-1 w-full">
2449 <div className="txt-compact-small flex items-start gap-x-2">
2450 <span>Language:</span>
2451 {locale && (
2452 <span className="txt-compact-small flex items-center gap-x-2">
2453 {locale.name}
2454 </span>
2455 )}
2456 </div>
2457 </ListboxButton>
2458 <div className="flex relative w-full min-w-[320px]">
2459 <Transition
2460 show={open}
2461 as={Fragment}
2462 leave="transition ease-in duration-150"
2463 leaveFrom="opacity-100"
2464 leaveTo="opacity-0"
2465 >
2466 <ListboxOptions
2467 className="absolute -bottom-[calc(100%-36px)] left-0 xsmall:left-auto xsmall:right-0 max-h-[442px] overflow-y-scroll z-[900] bg-white drop-shadow-md text-small-regular uppercase text-black no-scrollbar rounded-rounded w-full"
2468 static
2469 >
2470 {locales?.map((l, index) => {
2471 return (
2472 <ListboxOption
2473 key={index}
2474 value={l}
2475 className="py-2 hover:bg-gray-200 px-3 cursor-pointer flex items-center gap-x-2"
2476 >
2477 {l.name}
2478 </ListboxOption>
2479 )
2480 })}
2481 </ListboxOptions>
2482 </Transition>
2483 </div>
2484 </Listbox>
2485 </div>
2486 <ArrowRightMini
2487 className={clx(
2488 "transition-transform duration-150",
2489 open ? "-rotate-90" : ""
2490 )}
2491 />
2492 </div>
2493 )
2494 ```
2495
2496 You show the selected locale. Then, when the customer hovers over the locale, the dropdown is shown to select a different locale.
2497
2498 When the customer selects a locale, you execute the `handleChange` function, which sets the selected locale and closes the dropdown.
2499
2500 #### Add Locale Select to the Side Menu
2501
2502 The last step is to show the locale selector in the side menu after the country selector.
2503
2504 In `src/modules/layout/components/side-menu/index.tsx`, add the following import:
2505
2506 ```tsx title="src/modules/layout/components/side-menu/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2507 import LocaleSelect from "../locale-select"
2508 ```
2509
2510 Then, add the `LocaleSelect` component in the return statement of the `SideMenu` component, after the `div` wrapping the country selector:
2511
2512 ```tsx title="src/modules/layout/components/side-menu/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2513 <LocaleSelect />
2514 ```
2515
2516 The locale selector will now show in the side menu after the country selector.
2517
2518 ### Test out the Locale Selector
2519
2520 To test out all the changes made in this step, start the Medusa application by running the following command in the `apps/backend` directory:
2521
2522 ```bash npm2yarn
2523 npm run dev
2524 ```
2525
2526 Then, start the Next.js Starter Storefront by running the following command in the storefront's directory:
2527
2528 ```bash npm2yarn
2529 npm run dev
2530 ```
2531
2532 The storefront will run at `http://localhost:8000`. Open it in your browser, then click on "Menu" at the top right. You'll see at the bottom of the side menu the locale selector.
2533
2534 ![The locale selector in the side menu](https://res.cloudinary.com/dza7lstvk/image/upload/v1744720332/Medusa%20Resources/Screenshot_2025-04-15_at_3.31.51_PM_vdqou5.png)
2535
2536 You can try selecting a different locale. The selected locale will be stored, but products will still be shown in the default locale. You'll implement the locale-based product retrieval in the next step.
2537
2538 ---
2539
2540 ## Step 7: Retrieve Product Details for Locale
2541
2542 The next feature you'll implement is retrieving and displaying product details for a selected locale.
2543
2544 You'll implement this feature by:
2545
2546 1. Linking Medusa's product to Contentful's product.
2547 2. Adding the method to retrieve product details for a selected locale from Contentful.
2548 3. Adding a new route to retrieve the product details for a selected locale.
2549 4. Customizing the storefront to show the product details for the selected locale.
2550
2551 ### Link Medusa's Product to Contentful's Product
2552
2553 Medusa facilitates retrieving data across systems using [module links](!docs!/learn/fundamentals/module-links). A module link forms an association between data models of two modules while maintaining module isolation.
2554
2555 Not only do module links support Medusa data models, but they also support virtual data models that are not persisted in Medusa's database. In that case, you create a [read-only module link](!docs!/learn/fundamentals/module-links/read-only) that allows you to retrieve data across systems.
2556
2557 In this section, you'll define a read-only module link between Medusa's product and Contentful's product, allowing you to later retrieve a product's entry in Contentful within a single query.
2558
2559 <Note>
2560
2561 Learn more about read-only module links in the [Read-Only Module Links](!docs!/learn/fundamentals/module-links/read-only) documentation.
2562
2563 </Note>
2564
2565 Module links are defined in a TypeScript or JavaScript file under the `src/links` directory. So, create the file `src/links/product-contentful.ts` with the following content:
2566
2567 export const productContentfulLinkHighlights = [
2568 ["5", "defineLink", "Define the module link."],
2569 ["7", "linkable", "The Medusa data model to link."],
2570 ["8", "field", "The field in the Medusa data model that holds the ID of the product."],
2571 ["11", "linkable", "The Contentful virtual data model to link."],
2572 ["12", "serviceName", "The name of the Contentful Module."],
2573 ["13", "alias", "The alias to use when querying the linked records."],
2574 ["14", "primaryKey", "The field in the Contentful virtual data model that holds the ID of a product."],
2575 ["18", "readOnly", "The module link is read-only."],
2576 ]
2577
2578 ```ts title="src/links/product-contentful.ts" highlights={productContentfulLinkHighlights}
2579 import { defineLink } from "@medusajs/framework/utils"
2580 import ProductModule from "@medusajs/medusa/product"
2581 import { CONTENTFUL_MODULE } from "../modules/contentful"
2582
2583 export default defineLink(
2584 {
2585 linkable: ProductModule.linkable.product,
2586 field: "id",
2587 },
2588 {
2589 linkable: {
2590 serviceName: CONTENTFUL_MODULE,
2591 alias: "contentful_product",
2592 primaryKey: "product_id",
2593 },
2594 },
2595 {
2596 readOnly: true,
2597 }
2598 )
2599 ```
2600
2601 You define a module link using `defineLink` from the Modules SDK. It accepts three parameters:
2602
2603 1. An object with the linkable configuration of the data model in Medusa, and the field that will be passed as a filter to the Contentful Module's service.
2604 2. An object with the linkable configuration of the virtual data model in Contentful. This object must have the following properties:
2605 - `serviceName`: The name of the service, which is the Contentful Module's name. Medusa uses this name to resolve the module's service from the Medusa container.
2606 - `alias`: The alias to use when querying the linked records. You'll see how that works in a bit.
2607 - `primaryKey`: The field in Contentful's virtual data model that holds the ID of a product.
2608 3. An object with the `readOnly` property set to `true`.
2609
2610 You'll see how the module link works in the upcoming steps.
2611
2612 ### List Contentful Products Method
2613
2614 Next, you'll add a method that lists Contentful products for a given locale.
2615
2616 Add the following method to the Contentful Module's service at `src/modules/contentful/service.ts`:
2617
2618 export const listContentfulProductsMethodHighlights = [
2619 ["4", "filter", "The filter to apply on the retrieved products."],
2620 ["6", "context", "The context that includes the locale code."],
2621 ["11", "getEntries", "Retrieve the products from Contentful."],
2622 ["14", `"fields.medusaId"`, "Filter the products by their `medusaId` field."],
2623 ["15", "locale", "The locale code to retrieve the fields of the product in that locale."],
2624 ["16", "include", "The depth of the included nested entries."],
2625 ["19", "map", "Format the retrieved products."],
2626 ["24", "product_id", "Pass the product's ID in the `product_id` property."],
2627 ]
2628
2629 ```ts title="src/modules/contentful/service.ts" highlights={listContentfulProductsMethodHighlights}
2630 export default class ContentfulModuleService {
2631 // ...
2632 async list(
2633 filter: {
2634 id: string | string[]
2635 context?: {
2636 locale: string
2637 }
2638 }
2639 ) {
2640 const contentfulProducts = await this.deliveryClient.getEntries({
2641 limit: 15,
2642 content_type: "product",
2643 "fields.medusaId": filter.id,
2644 locale: filter.context?.locale,
2645 include: 3,
2646 })
2647
2648 return contentfulProducts.items.map((product) => {
2649 // remove links
2650 const { productVariants: _, productOptions: __, ...productFields } = product.fields
2651 return {
2652 ...productFields,
2653 product_id: product.fields.medusaId,
2654 variants: product.fields.productVariants.map((variant) => {
2655 // remove circular reference
2656 const { product: _, productOptionValues: __, ...variantFields } = variant.fields
2657 return {
2658 ...variantFields,
2659 product_variant_id: variant.fields.medusaId,
2660 options: variant.fields.productOptionValues.map((option) => {
2661 // remove circular reference
2662 const { productOption: _, ...optionFields } = option.fields
2663 return {
2664 ...optionFields,
2665 product_option_id: option.fields.medusaId,
2666 }
2667 }),
2668 }
2669 }),
2670 options: product.fields.productOptions.map((option) => {
2671 // remove circular reference
2672 const { product: _, ...optionFields } = option.fields
2673 return {
2674 ...optionFields,
2675 product_option_id: option.fields.medusaId,
2676 values: option.fields.values.map((value) => {
2677 // remove circular reference
2678 const { productOptionValue: _, ...valueFields } = value.fields
2679 return {
2680 ...valueFields,
2681 product_option_value_id: value.fields.medusaId,
2682 }
2683 }),
2684 }
2685 }),
2686 }
2687 })
2688 }
2689 }
2690 ```
2691
2692 You add a `list` method that accepts an object with the following properties:
2693
2694 1. `id`: The ID of the product(s) in Medusa to retrieve their entries in Contentful.
2695 2. `context`: An object with the `locale` property that holds the locale code to retrieve the product's entry in Contentful for that locale.
2696
2697 In the method, you use the Delivery API client's `getEntries` method to retrieve the products. You pass the following parameters:
2698
2699 - `limit`: The maximum number of products to retrieve.
2700 - `content_type`: The content type of the entries to retrieve, which is `product`.
2701 - `fields.medusaId`: Filter the products by their `medusaId` field, which holds the ID of the product in Medusa.
2702 - `locale`: The locale code to retrieve the fields of the product in that locale.
2703 - `include`: The depth of the included nested entries. This ensures that you can retrieve the product's variants and options, and their values.
2704
2705 Then, you format the retrieved products to:
2706
2707 - Pass the product's ID in the `product_id` property. This is essential to map a product in Medusa to its entry in Contentful.
2708 - Remove the circular references in the product's variants, options, and values to avoid infinite loops.
2709
2710 <Note title="Tip">
2711
2712 To paginate the retrieved products, implement a `listAndCount` method as explained in the [Query Context](!docs!/learn/fundamentals/query/query-context#using-pagination-with-query) documentation.
2713
2714 </Note>
2715
2716 ### Retrieve Product Details for Locale API Route
2717
2718 You'll now create the API route that returns a product's details for a given locale.
2719
2720 You can create an API route that accepts path parameters by creating a directory within the route file's path whose name is of the format `[param]`.
2721
2722 So, create the file `src/api/store/products/[id]/[locale]/route.ts` with the following content:
2723
2724 export const getProductLocaleDetailsRouteHighlights = [
2725 ["14", "locale", "Retrieve the locale from the request's path parameters."],
2726 ["14", "id", "Retrieve the product's ID from the request's path parameters."],
2727 ["16", "query", "Resolve Query from the Medusa container."],
2728 ["20", "data", "Retrieve the product's details from Contentful."],
2729 ["24", `"contentful_product.*"`, "Retrieve the product's details from Contentful."],
2730 ["29", "context", "Pass the locale code in the query's context."]
2731 ]
2732
2733 ```ts title="src/api/store/products/[id]/[locale]/route.ts" highlights={getProductLocaleDetailsRouteHighlights}
2734 import {
2735 MedusaRequest,
2736 MedusaResponse,
2737 } from "@medusajs/framework/http"
2738 import {
2739 QueryContext,
2740 ContainerRegistrationKeys,
2741 } from "@medusajs/framework/utils"
2742
2743 export const GET = async (
2744 req: MedusaRequest,
2745 res: MedusaResponse
2746 ) => {
2747 const { locale, id } = req.params
2748
2749 const query = req.scope.resolve(
2750 ContainerRegistrationKeys.QUERY
2751 )
2752
2753 const { data } = await query.graph({
2754 entity: "product",
2755 fields: [
2756 "id",
2757 "contentful_product.*",
2758 ],
2759 filters: {
2760 id,
2761 },
2762 context: {
2763 contentful_product: QueryContext({
2764 locale,
2765 }),
2766 },
2767 })
2768
2769 res.json({
2770 product: data[0],
2771 })
2772 }
2773 ```
2774
2775 Since you export a `GET` route handler function, you expose a `GET` route at `/store/products/[id]/[locale]`. The route accepts two path parameters: the product's ID and the locale code.
2776
2777 In the route handler, you retrieve the `locale` and `id` path parameters from the request. Then, you resolve [Query](!docs!/learn/fundamentals/query) from the Medusa container.
2778
2779 Next, you use Query to retrieve the localized details of the specified product. To do that, you pass an object with the following properties:
2780
2781 - `entity`: The entity to retrieve, which is `product`.
2782 - `fields`: The fields to retrieve. Notice that you include the `contentful_product.*` field, which is available through the module link you created earlier.
2783 - `filters`: The filter to apply on the retrieved products. You apply the product's ID as a filter.
2784 - `context`: An additional context to be passed to the methods retrieving the data. To pass a context, you use [Query Context](!docs!/learn/fundamentals/query/query-context).
2785
2786 By specifying `contentful_product.*` in the `fields` property, Medusa will retrieve the product's entry from Contentful using the `list` method you added to the Contentful Module's service.
2787
2788 Medusa passes the filters and context to the `list` method, and attaches the returned data to the Medusa product if its `product_id` matches the product's ID.
2789
2790 Finally, you return the product's details in the JSON response.
2791
2792 You can now use this route to retrieve a product's details for a given locale.
2793
2794 ### Show Localized Product Details in Storefront
2795
2796 Now that you expose the localized product details, you can customize the storefront to show them.
2797
2798 #### Install Contentful Rich Text Package
2799
2800 When you retrieve the entries from Contentful, rich-text fields are returned as an object that requires special rendering. So, Contentful provides a package to render rich-text fields.
2801
2802 Install the package by running the following command:
2803
2804 ```bash npm2yarn
2805 npm install @contentful/@contentful/rich-text-types
2806 ```
2807
2808 You'll use this package to render the product's description.
2809
2810 #### Retrieve Localized Product Details Function
2811
2812 To retrieve a product's details for a given locale, you'll add a function that sends a request to the API route you created.
2813
2814 First, add the following import at the top of `src/lib/data/locale.ts`:
2815
2816 ```ts title="src/lib/data/locale.ts" badgeLabel="Storefront" badgeColor="blue"
2817 import type { Document } from "@contentful/rich-text-types"
2818 ```
2819
2820 Then, add the following type and function at the end of the file:
2821
2822 ```ts title="src/lib/data/locale.ts" badgeLabel="Storefront" badgeColor="blue"
2823 export type ProductLocaleDetails = {
2824 id: string
2825 contentful_product: {
2826 product_id: string
2827 title: string
2828 handle: string
2829 description: Document
2830 subtitle?: string
2831 variants: {
2832 title: string
2833 product_variant_id: string
2834 options: {
2835 value: string
2836 product_option_id: string
2837 }[]
2838 }[]
2839 options: {
2840 title: string
2841 product_option_id: string
2842 values: {
2843 title: string
2844 product_option_value_id: string
2845 }[]
2846 }[]
2847 }
2848 }
2849
2850 export async function getProductLocaleDetails(
2851 productId: string
2852 ) {
2853 const localeCode = await getSelectedLocale()
2854
2855 return await sdk.client.fetch<{
2856 product: ProductLocaleDetails
2857 }>(`/store/products/${productId}/${localeCode}`)
2858 }
2859 ```
2860
2861 You define a `ProductLocaleDetails` type that describes the structure of a localized product's details.
2862
2863 You also define a `getProductLocaleDetails` function that sends a request to the API route you created and returns the localized product's details.
2864
2865 #### Show Localized Product Title in Products Listing
2866
2867 Next, you'll customize existing components to show the localized product details.
2868
2869 The component defined in `src/modules/products/components/product-preview/index.tsx` shows the product's details in the products listing page. You need to retrieve the localized product details and show the product's title in the selected locale.
2870
2871 In `src/modules/products/components/product-preview/index.tsx`, add the following import:
2872
2873 ```tsx title="src/modules/products/components/product-preview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2874 import { getProductLocaleDetails } from "@lib/data/locale"
2875 ```
2876
2877 Then, in the `ProductPreview` component in the same file, add the following before the `return` statement:
2878
2879 ```tsx title="src/modules/products/components/product-preview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2880 const productLocaleDetails = await getProductLocaleDetails(product.id!)
2881 ```
2882
2883 This will retrieve the localized product details for the selected locale.
2884
2885 Finally, to show the localized product title, find in the `ProductPreview` component's `return` statement the following line:
2886
2887 ```tsx title="src/modules/products/components/product-preview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2888 {product.title}
2889 ```
2890
2891 And replace it with the following:
2892
2893 ```tsx title="src/modules/products/components/product-preview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2894 {productLocaleDetails.product.contentful_product?.title || product.title}
2895 ```
2896
2897 You'll test it out after the next step.
2898
2899 #### Show Localized Product Details in Product Page
2900
2901 Next, you'll customize the product page to show the localized product details.
2902
2903 The product's details page is defined in `src/app/[countryCode]/(main)/products/[handle]/page.tsx`. So, add the following import at the top of the file:
2904
2905 ```tsx title="src/app/[countryCode]/(main)/products/[handle]/page.tsx" badgeLabel="Storefront" badgeColor="blue"
2906 import { getProductLocaleDetails } from "@lib/data/locale"
2907 ```
2908
2909 Then, in the `ProductPage` component in the same file, add the following before the `return` statement:
2910
2911 ```tsx title="src/app/[countryCode]/(main)/products/[handle]/page.tsx" badgeLabel="Storefront" badgeColor="blue"
2912 const productLocaleDetails = await getProductLocaleDetails(pricedProduct.id!)
2913 ```
2914
2915 This will retrieve the localized product details for the selected locale.
2916
2917 Finally, in the `ProductPage` component in the same file, pass the following prop to `ProductTemplate`:
2918
2919 ```tsx title="src/app/[countryCode]/(main)/products/[handle]/page.tsx" badgeLabel="Storefront" badgeColor="blue"
2920 return (
2921 <ProductTemplate
2922 // ...
2923 productLocaleDetails={productLocaleDetails.product}
2924 />
2925 )
2926 ```
2927
2928 Next, you'll customize the `ProductTemplate` component to accept and use this prop.
2929
2930 In `src/modules/products/templates/index.tsx`, add the following import:
2931
2932 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2933 import { ProductLocaleDetails } from "@lib/data/locale"
2934 ```
2935
2936 Then, update the `ProductTemplateProps` type to include the `productLocaleDetails` prop:
2937
2938 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2939 export type ProductTemplateProps = {
2940 // ...
2941 productLocaleDetails: ProductLocaleDetails
2942 }
2943 ```
2944
2945 Next, update the `ProductTemplate` component to destructure the `productLocaleDetails` prop:
2946
2947 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2948 const ProductTemplate: React.FC<ProductTemplateProps> = ({
2949 // ...
2950 productLocaleDetails,
2951 }) => {
2952 // ...
2953 }
2954 ```
2955
2956 Finally, pass the `productLocaleDetails` prop to the `ProductInfo` component in the `return` statement:
2957
2958 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2959 <ProductInfo
2960 // ...
2961 productLocaleDetails={productLocaleDetails}
2962 />
2963 ```
2964
2965 The `ProductInfo` component shows the product's details. So, you need to update it to accept and use the `productLocaleDetails` prop.
2966
2967 In `src/modules/products/templates/product-info/index.tsx`, add the following imports:
2968
2969 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2970 import { ProductLocaleDetails } from "@lib/data/locale"
2971 import { documentToHtmlString } from "@contentful/rich-text-html-renderer"
2972 ```
2973
2974 Then, update the `ProductInfoProps` type to include the `productLocaleDetails` prop:
2975
2976 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2977 export type ProductInfoProps = {
2978 // ...
2979 productLocaleDetails: ProductLocaleDetails
2980 }
2981 ```
2982
2983 Next, update the `ProductInfo` component to destructure the `productLocaleDetails` prop:
2984
2985 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2986 const ProductInfo = ({ product, productLocaleDetails }: ProductInfoProps) => {
2987 // ...
2988 }
2989 ```
2990
2991 Then, find the following line in the `return` statement:
2992
2993 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
2994 {product.title}
2995 ```
2996
2997 And replace it with the following:
2998
2999 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3000 {productLocaleDetails.contentful_product?.title || product.title}
3001 ```
3002
3003 Also, find the following line:
3004
3005 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3006 {product.description}
3007 ```
3008
3009 And replace it with the following:
3010
3011 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3012 {productLocaleDetails.contentful_product?.description ?
3013 <div dangerouslySetInnerHTML={{ __html: documentToHtmlString(productLocaleDetails.contentful_product?.description) }} /> :
3014 product.description
3015 }
3016 ```
3017
3018 You use the `documentToHtmlString` function to render the rich-text field. The function returns an HTML string that you can use to render the description.
3019
3020 ### Test out the Localized Product Details
3021
3022 You can now test out all the changes made in this step.
3023
3024 To do that, start the Medusa application by running the following command in the `apps/backend` directory:
3025
3026 ```bash npm2yarn
3027 npm run dev
3028 ```
3029
3030 Then, start the Next.js Starter Storefront by running the following command in the storefront's directory:
3031
3032 ```bash npm2yarn
3033 npm run dev
3034 ```
3035
3036 Open the storefront at `http://localhost:8000` and select a different locale.
3037
3038 Then, open the products listing page by clicking on Menu -> Store. You'll see the product titles in the selected locale.
3039
3040 ![The product titles are shown in the selected locale](https://res.cloudinary.com/dza7lstvk/image/upload/v1744723796/Medusa%20Resources/Screenshot_2025-04-15_at_4.29.39_PM_izxt6j.png)
3041
3042 Then, if you click on a product, you'll see the product's title and description in the selected locale.
3043
3044 ![The product's title and description are shown in the selected locale](https://res.cloudinary.com/dza7lstvk/image/upload/v1744723844/Medusa%20Resources/Screenshot_2025-04-15_at_4.30.31_PM_pt6ngz.png)
3045
3046 ---
3047
3048 ## Step 8: Sync Changes from Contentful to Medusa
3049
3050 The last feature you'll implement is syncing changes from Contentful to Medusa.
3051
3052 Contentful's webhooks allow you to listen to changes in your Contentful entries. You can then set up a webhook listener API route in Medusa that updates the product's data.
3053
3054 In this step, you'll set up a webhook listener that updates Medusa's product data when a Contentful entry is published.
3055
3056 ### Prerequisites: Public Server
3057
3058 Webhooks can only trigger deployed listeners. So, you must either [deploy your Medusa application](../../../deployment/page.mdx), or use tools like [ngrok](https://ngrok.com/) to publicly expose your local application.
3059
3060 ### Set Up Webhooks in Contentful
3061
3062 Before setting up the webhook listener, you need to set up a webhook in Contentful. To do that, on the Contentful dashboard:
3063
3064 1. Click on the cog icon at the top right, then choose "Webhooks" from the dropdown.
3065
3066 ![The cog icon is at the top right next to the avatar icon. When you click on it, you see a dropdown with the "Webhooks" option](https://res.cloudinary.com/dza7lstvk/image/upload/v1744733023/Medusa%20Resources/Screenshot_2025-04-15_at_7.03.21_PM_ji7ohw.png)
3067
3068 2. On the Webhooks page, click on the "Add Webhook" button.
3069 3. In the webhook form:
3070 - In the Name fields, enter a name, such as "Medusa".
3071 - In the URL field, enter `{your_app}/hooks/contentful`, where `{your_app}` is the public URL of your Medusa application. You'll create the `/hooks/contentful` API route in a bit.
3072 - In the Triggers section, select the "Published" trigger for "Entry".
3073
3074 ![The webhook form with the URL and triggers highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1744733332/Medusa%20Resources/Screenshot_2025-04-15_at_7.08.24_PM_coq6oo.png)
3075
3076 - Scroll down to the "Headers" section, and choose "application/json" for the "Content type" field.
3077
3078 ![The webhook form](https://res.cloudinary.com/dza7lstvk/image/upload/v1744733411/Medusa%20Resources/Screenshot_2025-04-15_at_7.09.53_PM_kvlppv.png)
3079
3080 4. Once you're done, click the Save button.
3081
3082 ### Setup Webhook Secret in Contentful
3083
3084 You also need to add a webhook secret in Contentful. To do that, on the Contentful dashboard:
3085
3086 1. Click on the cog icon at the top right, then choose "Webhooks" from the dropdown.
3087 2. On the Webhooks page, click on the "Settings" tab.
3088 3. Click on the "Enable request verification" button.
3089
3090 ![The "Enable request verification" button in the "Settings" tab](https://res.cloudinary.com/dza7lstvk/image/upload/v1744786362/Medusa%20Resources/Screenshot_2025-04-16_at_9.51.39_AM_byv3tt.png)
3091
3092 4. Copy the secret that shows up. You can update it later but you can't see the same secret again.
3093
3094 You'll use the secret to verify the webhook request in Medusa next.
3095
3096 ### Update Contentful Module Options
3097
3098 First, add the webhook secret as an environment variable in the Medusa application's `.env` file:
3099
3100 ```plain
3101 CONTENTFUL_WEBHOOK_SECRET=aEl7...
3102 ```
3103
3104 Next, add the webhook secret to the Contentful Module options in the Medusa application's `medusa-config.ts` file:
3105
3106 ```ts title="medusa-config.ts"
3107 module.exports = defineConfig({
3108 // ...
3109 modules: [
3110 {
3111 resolve: "./src/modules/contentful",
3112 options: {
3113 // ...
3114 webhook_secret: process.env.CONTENTFUL_WEBHOOK_SECRET,
3115 },
3116 },
3117 ],
3118 })
3119 ```
3120
3121 Finally, update the `ModuleOptions` type in `src/modules/contentful/loader/create-content-models.ts` to include the `webhook_secret` option:
3122
3123 ```ts title="src/modules/contentful/loader/create-content-models.ts"
3124 export type ModuleOptions = {
3125 // ...
3126 webhook_secret: string
3127 }
3128 ```
3129
3130 ### Add Verify Request Method
3131
3132 Next, you'll add a method to the Contentful Module's service that verifies a webhook request.
3133
3134 To verify the request, you'll need the `@contentful/node-apps-toolkit` package that provides utility functions for Node.js applications.
3135
3136 So, run the following command to install it:
3137
3138 ```bash npm2yarn
3139 npm install @contentful/node-apps-toolkit
3140 ```
3141
3142 Then, add the following method to the Contentful Module's service in `src/modules/contentful/service.ts`:
3143
3144 ```ts title="src/modules/contentful/service.ts"
3145 // other imports...
3146 import {
3147 CanonicalRequest,
3148 verifyRequest,
3149 } from "@contentful/node-apps-toolkit"
3150
3151 export default class ContentfulModuleService {
3152 // ...
3153 async verifyWebhook(request: CanonicalRequest) {
3154 if (!this.options.webhook_secret) {
3155 throw new MedusaError(
3156 MedusaError.Types.INVALID_DATA,
3157 "Webhook secret is not set"
3158 )
3159 }
3160 return verifyRequest(this.options.webhook_secret, request, 0)
3161 }
3162 }
3163 ```
3164
3165 You add a `verifyWebhook` method that verifies a webhook request using the `verifyRequest` function.
3166
3167 You pass to the `verifyRequest` function the webhook secret from the module's options with the request's details. You also disable time-to-live (TTL) check by passing `0` as the third argument.
3168
3169 ### Handle Contentful Webhook Workflow
3170
3171 Before you add the webhook listener, the last piece you need is to add a workflow that handles the necessary updates based on the webhook event.
3172
3173 The workflow will have the following steps:
3174
3175 <WorkflowDiagram
3176 workflow={{
3177 name: "handleContentfulHookWorkflow",
3178 steps: [
3179 {
3180 type: "step",
3181 name: "prepareUpdateDataStep",
3182 description: "Prepare the data for the update",
3183 depth: 1,
3184 },
3185 {
3186 type: "when",
3187 condition: `input.entry.sys.contentType.sys.id === "product"`,
3188 steps: [
3189 {
3190 type: "workflow",
3191 name: "updateProductsWorkflow",
3192 description: "Update the product if that's the entry type",
3193 depth: 2,
3194 link: "/references/medusa-workflows/updateProductsWorkflow"
3195 }
3196 ]
3197 },
3198 {
3199 type: "when",
3200 condition: `input.entry.sys.contentType.sys.id === "productVariant"`,
3201 steps: [
3202 {
3203 type: "workflow",
3204 name: "updateProductVariantsWorkflow",
3205 description: "Update the product variant if that's the entry type",
3206 depth: 2,
3207 link: "/references/medusa-workflows/updateProductVariantsWorkflow"
3208 }
3209 ]
3210 },
3211 {
3212 type: "when",
3213 condition: `input.entry.sys.contentType.sys.id === "productOption"`,
3214 steps: [
3215 {
3216 type: "workflow",
3217 name: "updateProductOptionsWorkflow",
3218 description: "Update the product option if that's the entry type",
3219 depth: 2,
3220 link: "/references/medusa-workflows/updateProductOptionsWorkflow"
3221 }
3222 ]
3223 }
3224 ]
3225 }}
3226 />
3227
3228 You only need to implement the first step, as Medusa provides the other workflows (running as steps) in the `@medusajs/medusa/core-flows` package.
3229
3230 #### prepareUpdateDataStep
3231
3232 The first step receives the webhook data payload and, based on the entry type, returns the data necessary for the update.
3233
3234 To create the step, create the file `src/workflows/steps/prepare-update-data.ts` with the following content:
3235
3236 ```ts title="src/workflows/steps/prepare-update-data.ts"
3237 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
3238 import { EntryProps } from "contentful-management"
3239 import ContentfulModuleService from "../../modules/contentful/service"
3240 import { CONTENTFUL_MODULE } from "../../modules/contentful"
3241
3242 type StepInput = {
3243 entry: EntryProps
3244 }
3245
3246 export const prepareUpdateDataStep = createStep(
3247 "prepare-update-data",
3248 async ({ entry }: StepInput, { container }) => {
3249 const contentfulModuleService: ContentfulModuleService =
3250 container.resolve(CONTENTFUL_MODULE)
3251
3252 const defaultLocale = await contentfulModuleService.getDefaultLocaleCode()
3253
3254 let data: Record<string, unknown> = {}
3255
3256 switch (entry.sys.contentType.sys.id) {
3257 case "product":
3258 // Extract Medusa option IDs from productOptions field
3259 // We need to fetch the option entries to get their medusaId values
3260 const optionLinks = entry.fields.productOptions?.[defaultLocale!] || []
3261 const optionEntryIds = optionLinks.map(
3262 (optionLink: { sys: { id: string } }) => optionLink.sys.id
3263 )
3264 const options = await contentfulModuleService.getOptions(optionEntryIds)
3265 const optionsMedusaIds = options.map((option) => option.fields.medusaId[defaultLocale!])
3266
3267 data = {
3268 id: entry.fields.medusaId[defaultLocale!],
3269 title: entry.fields.title[defaultLocale!],
3270 subtitle: entry.fields.subtitle?.[defaultLocale!] || undefined,
3271 handle: entry.fields.handle[defaultLocale!],
3272 option_ids: optionsMedusaIds,
3273 }
3274 break
3275 case "productVariant":
3276 data = {
3277 id: entry.fields.medusaId[defaultLocale!],
3278 title: entry.fields.title[defaultLocale!],
3279 }
3280 break
3281 case "productOption":
3282 data = {
3283 selector: {
3284 id: entry.fields.medusaId[defaultLocale!],
3285 },
3286 update: {
3287 title: entry.fields.title[defaultLocale!],
3288 },
3289 }
3290 break
3291 }
3292
3293 return new StepResponse(data)
3294 }
3295 )
3296 ```
3297
3298 You define a `prepareUpdateDataStep` function that receives the webhook data payload as an input.
3299
3300 In the step, you resolve the Contentful Module's service and use it to retrieve the default locale code. You need it to find the value to update the fields in Medusa.
3301
3302 Next, you prepare the data to return based on the entry type:
3303
3304 - `product`: The product's ID, title, subtitle, handle, and option IDs.
3305 - `productVariant`: The product variant's ID and title.
3306 - `productOption`: The product option's ID and title.
3307
3308 The data is prepared based on the expected input for the workflows that will be used to update the data.
3309
3310 #### Create the Workflow
3311
3312 You can now create the workflow that handles the webhook event.
3313
3314 Create the file `src/workflows/handle-contentful-hook.ts` with the following content:
3315
3316 export const handleContentfulHookWorkflowHighlights = [
3317 ["16", "entry", "Receive the webhook data payload as an input."],
3318 ["22", "prepareUpdateData", "Prepare the data for the update."],
3319 ["26", "when", "Check if the entry type is a product."],
3320 ["28", "updateProductsWorkflow", "Update the product."],
3321 ["35", "when", "Check if the entry type is a product variant."],
3322 ["39", "updateProductVariantsWorkflow", "Update the product variant."],
3323 ["46", "when", "Check if the entry type is a product option."],
3324 ["50", "updateProductOptionsWorkflow", "Update the product option."],
3325 ]
3326
3327 ```ts title="src/workflows/handle-contentful-hook.ts" highlights={handleContentfulHookWorkflowHighlights} collapsibleLines="1-14" expandButtonLabel="Show Imports"
3328 import { createWorkflow, when } from "@medusajs/framework/workflows-sdk"
3329 import { EntryProps } from "contentful-management"
3330 import { prepareUpdateDataStep } from "./steps/prepare-update-data"
3331 import {
3332 updateProductOptionsWorkflow,
3333 updateProductsWorkflow,
3334 updateProductVariantsWorkflow,
3335 UpdateProductOptionsWorkflowInput,
3336 } from "@medusajs/medusa/core-flows"
3337 import {
3338 UpsertProductDTO,
3339 UpsertProductVariantDTO,
3340 } from "@medusajs/framework/types"
3341
3342 export type WorkflowInput = {
3343 entry: EntryProps
3344 }
3345
3346 export const handleContentfulHookWorkflow = createWorkflow(
3347 { name: "handle-contentful-hook-workflow" },
3348 (input: WorkflowInput) => {
3349 const prepareUpdateData = prepareUpdateDataStep({
3350 entry: input.entry,
3351 })
3352
3353 when(input, (input) => input.entry.sys.contentType.sys.id === "product")
3354 .then(() => {
3355 updateProductsWorkflow.runAsStep({
3356 input: {
3357 products: [prepareUpdateData as UpsertProductDTO],
3358 },
3359 })
3360 })
3361
3362 when(input, (input) =>
3363 input.entry.sys.contentType.sys.id === "productVariant"
3364 )
3365 .then(() => {
3366 updateProductVariantsWorkflow.runAsStep({
3367 input: {
3368 product_variants: [prepareUpdateData as UpsertProductVariantDTO],
3369 },
3370 })
3371 })
3372
3373 when(input, (input) =>
3374 input.entry.sys.contentType.sys.id === "productOption"
3375 )
3376 .then(() => {
3377 updateProductOptionsWorkflow.runAsStep({
3378 input: prepareUpdateData as unknown as UpdateProductOptionsWorkflowInput,
3379 })
3380 })
3381 }
3382 )
3383 ```
3384
3385 You define a `handleContentfulHookWorkflow` function that receives the webhook data payload as an input.
3386
3387 In the workflow, you:
3388
3389 - Prepare the data for the update using the `prepareUpdateDataStep` step.
3390 - Use a [when](!docs!/learn/fundamentals/workflows/conditions) condition to check if the entry type is a `product`, and if so, update the product using the `updateProductsWorkflow`.
3391 - Use a `when` condition to check if the entry type is a `productVariant`, and if so, update the product variant using the `updateProductVariantsWorkflow`.
3392 - Use a `when` condition to check if the entry type is a `productOption`, and if so, update the product option using the `updateProductOptionsWorkflow`.
3393
3394 <Note title="Why use When in Workflows?">
3395
3396 You can't perform data manipulation in a workflow's constructor function. Instead, the Workflows SDK includes utility functions like `when` to perform typical operations that requires accessing data values. Learn more about workflow constraints in the [Workflow Constraints](!docs!/learn/fundamentals/workflows/constructor-constraints) documentation.
3397
3398 </Note>
3399
3400 ### Add the Webhook Listener API Route
3401
3402 You can finally add the API route that acts as a webhook listener.
3403
3404 To add the API route, create the file `src/api/hooks/contentful/route.ts` with the following content:
3405
3406 export const contentfulHookRouteHighlights = [
3407 ["15", "contentfulModuleService", "Resolve the Contentful Module's service from the Medusa container."],
3408 ["18", "isValid", "Verify the webhook request."],
3409 ["25", "if", "Throw an error if the request is invalid."],
3410 ["32", "handleContentfulHookWorkflow", "Run the workflow with the request's body as the input."],
3411 ]
3412
3413 ```ts title="src/api/hooks/contentful/route.ts" highlights={contentfulHookRouteHighlights} collapsibleLines="1-10" expandButtonLabel="Show Imports"
3414 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
3415 import {
3416 handleContentfulHookWorkflow,
3417 HandleContentfulHookWorkflowInput,
3418 } from "../../../workflows/handle-contentful-hook"
3419 import { CONTENTFUL_MODULE } from "../../../modules/contentful"
3420 import { CanonicalRequest } from "@contentful/node-apps-toolkit"
3421 import { MedusaError } from "@medusajs/framework/utils"
3422 import ContentfulModuleService from "../../../modules/contentful/service"
3423
3424 export const POST = async (
3425 req: MedusaRequest,
3426 res: MedusaResponse
3427 ) => {
3428 const contentfulModuleService: ContentfulModuleService =
3429 req.scope.resolve(CONTENTFUL_MODULE)
3430
3431 const isValid = await contentfulModuleService.verifyWebhook({
3432 path: req.path,
3433 method: req.method.toUpperCase(),
3434 headers: req.headers,
3435 body: JSON.stringify(req.body),
3436 } as unknown as CanonicalRequest)
3437
3438 if (!isValid) {
3439 throw new MedusaError(
3440 MedusaError.Types.UNAUTHORIZED,
3441 "Invalid webhook request"
3442 )
3443 }
3444
3445 await handleContentfulHookWorkflow(req.scope).run({
3446 input: {
3447 entry: req.body,
3448 } as unknown as HandleContentfulHookWorkflowInput,
3449 })
3450
3451 res.status(200).send("OK")
3452 }
3453 ```
3454
3455 Since you export a `POST` route handler function, you expose a `POST` route at `/hooks/contentful`.
3456
3457 In the route, you first use the `verifyWebhook` method of the Contentful Module's service to verify the request. If the request is invalid, you throw an error.
3458
3459 Then, you run the `handleContentfulHookWorkflow` passing the request's body, which is the webhook data payload, as an input.
3460
3461 Finally, you return a `200` response to Contentful to confirm that the webhook was received and processed.
3462
3463 ### Test the Webhook Listener
3464
3465 To test out the webhook listener, start the Medusa application:
3466
3467 ```bash npm2yarn
3468 npm run dev
3469 ```
3470
3471 Then, try updating a product's title (in the default locale) in Contentful. You should see the product's title updated in Medusa.
3472
3473 ---
3474
3475 ## Next Steps
3476
3477 You've now integrated Contentful with Medusa and supported localized product details. You can expand on the features in this tutorial to:
3478
3479 1. Add support for other data types, such as product categories or collections.
3480 - Refer to the data model references for each [Commerce Module](../../../commerce-modules/page.mdx) to figure out the content types you need to create in Contentful.
3481 2. Listen to other product events and update the Contentful entries accordingly.
3482 - Refer to the [Events Reference](/references/events) for details on all events emitted in Medusa.
3483 3. Add localization for the entire Next.js Starter Storefront. You can either:
3484 - Create content types in Contentful for different sections in the storefront, then use them to retrieve the localized content;
3485 - Or use the approaches recommended in the [Next.js documentation](https://nextjs.org/docs/app/building-your-application/routing/internationalization).
3486
3487 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
3488
3489 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
3490
3491 ### Troubleshooting
3492
3493 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
3494
3495 ### Getting Help
3496
3497 If you encounter issues not covered in the troubleshooting guides:
3498
3499 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
3500 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.
3501 3. Contact the [sales team](https://medusajs.com/contact/) to get help from the Medusa team.