1 ---
2 products:
3 - product
4 ---
5
6 import { Card, Prerequisites, Details } from "docs-ui"
7 import { Github } from "@medusajs/icons"
8
9 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1732200494/Medusa%20Resources/opengraph-image_kstzrn.jpg"
10
11 export const metadata = {
12 title: `Integrate Medusa with Sanity (CMS)`,
13 openGraph: {
14 images: [
15 {
16 url: ogImage,
17 width: 800,
18 height: 450,
19 type: "image/jpeg"
20 }
21 ],
22 },
23 twitter: {
24 images: [
25 {
26 url: ogImage,
27 width: 800,
28 height: 450,
29 type: "image/jpeg"
30 }
31 ]
32 }
33 }
34
35 # {metadata.title}
36
37 In this guide, you'll learn how to integrate Medusa with Sanity.
38
39 When you install a Medusa application, you get a fully-fledged commerce platform with support for customizations. While Medusa allows you to manage basic content, such as product description and images, you might need rich content-management features, such as localized content. The Medusa Framework supports you in integrating a CMS with these features.
40
41 Sanity is a CMS that simplifies managing content from third-party sources into a single interface. By integrating it with Medusa, you can manage your storefront and commerce-related content, such as product details, from a single interface. You also benefit from advanced content-management features, such as live-preview editing.
42
43 This guide will teach you how to:
44
45 - Install and set up Medusa.
46 - Install and set up Sanity with Medusa's Next.js Starter storefront.
47 - Sync product data from Medusa to Sanity when a product is created or updated.
48 - Customize the Medusa Admin dashboard to check the sync status and trigger syncing products to Sanity.
49
50 You can follow this guide whether you're new to Medusa or an advanced Medusa developer. This guide also assumes you're familiar with Sanity concepts, which you can learn about in [their documentation](https://www.sanity.io/docs).
51
52 <Card
53 title="Example Repository"
54 text="Find the full code of the guide in this repository."
55 href="https://github.com/medusajs/examples/tree/main/sanity-integration"
56 icon={Github}
57 />
58
59 ---
60
61 ## Step 1: Install a Medusa Application
62
63 <Prerequisites items={[
64 {
65 text: "Node.js v20.19.0+ or v22.12.0+",
66 link: "https://nodejs.org/en/download"
67 },
68 {
69 text: "Git CLI tool",
70 link: "https://git-scm.com/downloads"
71 },
72 {
73 text: "PostgreSQL",
74 link: "https://www.postgresql.org/download/"
75 }
76 ]} />
77
78 Start by installing the Medusa application on your machine with the following command:
79
80 ```bash
81 npx create-medusa-app@latest
82 ```
83
84 You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js Starter Storefront, choose `Y` for yes.
85
86 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
87
88 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credential and submit the form.
89
90 Afterwards, you can login with the new user and explore the dashboard. The Next.js Starter Storefront is also running at `http://localhost:8000`.
91
92 <Note title="Ran into Errors?">
93
94 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
95
96 </Note>
97
98 <Note>
99
100 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
101
102 </Note>
103
104 ---
105
106 ## Step 2: Install Sanity Client SDK
107
108 In this step, you'll install [Sanity's JavaScript client SDK](https://www.sanity.io/docs/js-client) in the Medusa application, which you'll use later in your code when sending requests to Sanity.
109
110 In your terminal, move to the `apps/backend` directory and run the following command:
111
112 ```bash npm2yarn
113 cd apps/backend
114 npm install @sanity/client
115 ```
116
117 ---
118
119 ## Step 3: Create a Sanity Project
120
121 When the Medusa application connects to Sanity, it must connect to a project in Sanity.
122
123 So, before building the integration in Medusa, create a project in Sanity using their website:
124
125 1. [Sign in or sign up on the Sanity website.](https://www.sanity.io/login)
126 2. On your account's dashboard, click the "Create new project" button.
127
128 ![The Create new project button is at the top of the dashboard page.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732091565/Medusa%20Resources/Screenshot_2024-11-20_at_10.31.10_AM_vvq7y6.png)
129
130 3. Enter a project name and click "Create Project"
131
132 ![A pop-up form will open where you can choose project name and organization.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732091565/Medusa%20Resources/Screenshot_2024-11-20_at_10.32.33_AM_xb0rsn.png)
133
134 You'll go back to the project's setting page in a later step.
135
136 ---
137
138 ## Step 4: Create Sanity Module
139
140 To integrate third-party services into Medusa, you create a custom module. A module is a re-usable package with 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 Sanity Module that provides the interface to connect to and interact with Sanity. In later steps, you'll use the functionalities provided by this module to sync products to Sanity or retrieve documents from it.
143
144 <Note>
145
146 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
147
148 </Note>
149
150 ### Create Module Directory
151
152 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/sanity`.
153
154 ### Create Service
155
156 You define a module's functionalities 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 connect to a third-party service.
157
158 Medusa registers the module's service in the [Medusa container](!docs!/learn/fundamentals/medusa-container), allowing you to easily resolve the service from other customizations and use its methods.
159
160 <Note title="What is the Medusa Container?">
161
162 The Medusa application registers resources, such as a module's service or the [logging tool](!docs!/learn/debugging-and-testing/logging), in the Medusa container so that you can resolve them from other customizations, as you'll see in later sections. Learn more about it in [this documentation](!docs!/learn/fundamentals/medusa-container).
163
164 </Note>
165
166 In this section, you'll create the Sanity Module's service and the methods necessary to connect to Sanity.
167
168 Start by creating the file `src/modules/sanity/service.ts` with the following content:
169
170 ```ts title="src/modules/sanity/service.ts"
171 import {
172 Logger,
173 } from "@medusajs/framework/types"
174 import {
175 SanityClient,
176 } from "@sanity/client"
177
178 class SanityModuleService {
179 private client: SanityClient
180 private studioUrl?: string
181 private logger: Logger
182
183 // TODO
184 }
185
186 export default SanityModuleService
187 ```
188
189 You create the `SanityModuleService` class that for now only has three properties:
190
191 - `client` property of type `SanityClient` (from the Sanity SDK you installed in the previous step) to send requests to Sanity.
192 - `studioUrl` property which will hold the URL to access the Sanity studio.
193 - `logger` property, which is an instance of Medusa's [Logger](!docs!/learn/debugging-and-testing/logging), to log messages.
194
195 In the service, you want to initialize the client early-on so that you can use it in the service's methods. This requires options to be passed to the client, like the Sanity API key or project ID.
196
197 So, add after the import at the top of the file the following types:
198
199 ```ts title="src/modules/sanity/service.ts"
200 // other imports...
201
202 const SyncDocumentTypes = {
203 PRODUCT: "product",
204 } as const
205
206 type SyncDocumentTypes =
207 (typeof SyncDocumentTypes)[keyof typeof SyncDocumentTypes];
208
209 type ModuleOptions = {
210 api_token: string;
211 project_id: string;
212 api_version: string;
213 dataset: "production" | "development";
214 type_map?: Record<SyncDocumentTypes, string>;
215 studio_url?: string;
216 }
217 ```
218
219 The `ModuleOptions` type defines the type of options that the module expects:
220
221 - `api_token`: API token to connect to Sanity.
222 - `project_id`: The ID of the Sanity project.
223 - `api_version`: The Sanity API version.
224 - `dataset`: The dataset to use, which is either `production` or `development`.
225 - `type_map`: The types to sync from Medusa to Sanity. For simplicity, this guide only covers syncing products, but you can support other data types like product categories, too.
226 - `studio_url`: The URL to the Sanity studio. This is used to show the studio URL later in the Medusa Admin dashboard.
227
228 You can now initialize the client, which you'll do in the `constructor` of the `SanityModuleService`:
229
230 ```ts title="src/modules/sanity/service.ts"
231 import {
232 // other imports...
233 createClient,
234 } from "@sanity/client"
235
236 // types...
237
238 type InjectedDependencies = {
239 logger: Logger
240 };
241
242 class SanityModuleService {
243 // properties...
244 constructor({
245 logger,
246 }: InjectedDependencies, options: ModuleOptions) {
247 this.client = createClient({
248 projectId: options.project_id,
249 apiVersion: options.api_version,
250 dataset: options.dataset,
251 token: options.api_token,
252 })
253 this.logger = logger
254
255 this.logger.info("Connected to Sanity")
256
257 this.studioUrl = options.studio_url
258
259 // TODO initialize more properties
260 }
261 }
262 ```
263
264 The service's constructor accepts two parameters:
265
266 1. Resources to resolve from the Module's container. A module has a different container than the Medusa application, which you can learn more about it in [this documentation](!docs!/learn/fundamentals/modules/container).
267 2. The options passed to the module.
268
269 In the constructor, you create a Sanity client using the `createClient` function imported from `@sanity/client`. You pass it the options that the module receives.
270
271 You also initialize the `logger` and `studioUrl` properties, and log a message indicating that connection to Sanity was successful.
272
273 #### Transform Product Data
274
275 When you create or update products in Sanity, you must prepare the product object based on what Sanity expects.
276
277 So, you'll add methods to the service that transform a Medusa product to a Sanity document object.
278
279 Start by adding the following types and class properties to `src/modules/sanity/service.ts`:
280
281 ```ts title="src/modules/sanity/service.ts"
282 type SyncDocumentInputs<T> = T extends "product"
283 ? ProductDTO
284 : never
285
286 type TransformationMap<T> = Record<
287 SyncDocumentTypes,
288 (data: SyncDocumentInputs<T>) => any
289 >;
290
291 class SanityModuleService {
292 // other properties...
293 private typeMap: Record<SyncDocumentTypes, string>
294 private createTransformationMap: TransformationMap<SyncDocumentTypes>
295 private updateTransformationMap: TransformationMap<SyncDocumentTypes>
296
297 // ...
298 }
299 ```
300
301 First, you define types for a transformation map, which is a map that pairs up a document type (such as `product`) to a function that handles transforming its data.
302
303 Then, in the service, you define three new properties:
304
305 - `typeMap`: Pair of `SyncDocumentTypes` values (for example, `product`) and their type name in Sanity.
306 - `createTransformationMap`: Pair of `SyncDocumentTypes` values (for example, `product`) and the method used to transform a Medusa product to a Sanity document data to be created.
307 - `updateTransformationMap`: Pair of `SyncDocumentTypes` values (for example, `product`) and the method used to transform a Medusa product to a Sanity update operation.
308
309 Next, add the following two methods to transform a product:
310
311 ```ts title="src/modules/sanity/service.ts"
312 // other imports...
313 import {
314 ProductDTO,
315 } from "@medusajs/framework/types"
316
317 class SanityModuleService {
318 // ...
319 private transformProductForCreate = (product: ProductDTO) => {
320 return {
321 _type: this.typeMap[SyncDocumentTypes.PRODUCT],
322 _id: product.id,
323 title: product.title,
324 specs: [
325 {
326 _key: product.id,
327 _type: "spec",
328 title: product.title,
329 lang: "en",
330 },
331 ],
332 }
333 }
334
335 private transformProductForUpdate = (product: ProductDTO) => {
336 return {
337 set: {
338 title: product.title,
339 },
340 }
341 }
342 }
343 ```
344
345 The `transformProductForCreate` method accepts a product and returns an object that you'll later pass to Sanity to create the product document. Similarly, the `transformProductForUpdate` method accepts a product and returns an object that you'll later pass to Sanity to update the product document.
346
347 <Note title="Tip">
348
349 The Sanity document's schema type will be defined in a later chapter. If you add other fields to it, make sure to edit these methods.
350
351 </Note>
352
353 Finally, initialize the new properties you added in the `SanityModuleService`'s constructor:
354
355 ```ts title="src/modules/sanity/service.ts"
356 class SanityModuleService {
357 // ...
358 constructor({
359 logger,
360 }: InjectedDependencies, options: ModuleOptions) {
361 // ...
362 this.typeMap = Object.assign(
363 {},
364 {
365 [SyncDocumentTypes.PRODUCT]: "product",
366 },
367 options.type_map || {}
368 )
369
370 this.createTransformationMap = {
371 [SyncDocumentTypes.PRODUCT]: this.transformProductForCreate,
372 }
373
374 this.updateTransformationMap = {
375 [SyncDocumentTypes.PRODUCT]: this.transformProductForUpdate,
376 }
377 }
378 // ...
379 }
380 ```
381
382 You initialize the `typeMap` property to map the `product` type in Medusa to the `product` schema type in Sanity. You also initialize the `createTransformationMap` and `updateTransformationMap` to map the methods to transform a product for creation or update.
383
384 <Note title="Tip">
385
386 You can modify these properties to add support for other schema types, such as product categories or collections.
387
388 </Note>
389
390 #### Methods to Manage Documents
391
392 In this section, you'll add the methods that accept data from Medusa and create or update them as documents in Sanity.
393
394 Add the following methods to the `SanityModuleService` class:
395
396 export const syncMethodsHighlights = [
397 ["9", "upsertSyncDocument", "Creates or updates a document in Sanity for a data type in Medusa."],
398 ["21", "createSyncDocument", "Creates a document in Sanity for a data type in Medusa."],
399 ["30", "updateSyncDocument", "Updates a document in Sanity for a data type in Medusa."]
400 ]
401
402 ```ts title="src/modules/sanity/service.ts" highlights={syncMethodsHighlights}
403 // other imports...
404 import {
405 // ...
406 FirstDocumentMutationOptions,
407 } from "@sanity/client"
408
409 class SanityModuleService {
410 // ...
411 async upsertSyncDocument<T extends SyncDocumentTypes>(
412 type: T,
413 data: SyncDocumentInputs<T>
414 ) {
415 const existing = await this.client.getDocument(data.id)
416 if (existing) {
417 return await this.updateSyncDocument(type, data)
418 }
419
420 return await this.createSyncDocument(type, data)
421 }
422
423 async createSyncDocument<T extends SyncDocumentTypes>(
424 type: T,
425 data: SyncDocumentInputs<T>,
426 options?: FirstDocumentMutationOptions
427 ) {
428 const doc = this.createTransformationMap[type](data)
429 return await this.client.create(doc, options)
430 }
431
432 async updateSyncDocument<T extends SyncDocumentTypes>(
433 type: T,
434 data: SyncDocumentInputs<T>
435 ) {
436 const operations = this.updateTransformationMap[type](data)
437 return await this.client.patch(data.id, operations).commit()
438 }
439 }
440 ```
441
442 You add three methods:
443
444 - `upsertSyncDocument`: Creates or updates a document in Sanity for a data type in Medusa.
445 - `createSyncDocument`: Creates a document in Sanity for a data type in Medusa. It uses the `createTransformationMap` property to use the transform method of the specified Medusa data type (for example, a product's data).
446 - `updateSyncDocument`: Updates a document in Sanity for a data type in Medusa. It uses the `updateTransformationMap` property to use the transform method of the specified Medusa data type (for example, a product's data).
447
448 You also need methods to manage the Sanity documents without transformations. So, add the following methods to `SanityModuleService`:
449
450 export const methodsHighlights = [
451 ["3", "retrieve", "Retrieve a document from Sanity."],
452 ["7", "delete", "Delete a document from Sanity."],
453 ["11", "update", "Updates a document in Sanity."],
454 ["17", "list", "Retrieves a list of Sanity documents."]
455 ]
456
457 ```ts title="src/modules/sanity/service.ts" highlights={methodsHighlights}
458 class SanityModuleService {
459 // ...
460 async retrieve(id: string) {
461 return this.client.getDocument(id)
462 }
463
464 async delete(id: string) {
465 return this.client.delete(id)
466 }
467
468 async update(id: string, data: any) {
469 return await this.client.patch(id, {
470 set: data,
471 }).commit()
472 }
473
474 async list(
475 filter: {
476 id: string | string[]
477 }
478 ) {
479 const data = await this.client.getDocuments(
480 Array.isArray(filter.id) ? filter.id : [filter.id]
481 )
482
483 return data.map((doc) => ({
484 id: doc?._id,
485 ...doc,
486 }))
487 }
488 }
489 ```
490
491 You add other three methods:
492
493 - `retrieve` to retrieve a document by its ID.
494 - `delete` to delete a document by its ID.
495 - `update` to update a document by its ID with new data.
496 - `list` to list documents, with ability to filter them by their IDs. Since a Sanity document's ID is a product's ID, you can pass product IDs as a filter to retrieve their documents.
497
498 ### Export Module Definition
499
500 The `SanityModuleService` class now has the methods necessary to connect to and perform actions in Sanity.
501
502 Next, you must export the Module definition, which lets Medusa know what the Module's name is and what is its service.
503
504 Create the file `src/modules/sanity/index.ts` with the following content:
505
506 ```ts title="src/modules/sanity/index.ts"
507 import { Module } from "@medusajs/framework/utils"
508 import SanityModuleService from "./service"
509
510 export const SANITY_MODULE = "sanity"
511
512 export default Module(SANITY_MODULE, {
513 service: SanityModuleService,
514 })
515 ```
516
517 In the file, you export the `SANITY_MODULE` which is the Module's name. You'll use it later when you resolve the module from the Medusa container.
518
519 You also export the module definition using `Module` from the Modueles SDK, which accepts as a first parameter the module's name, and as a second parameter an object having a `service` property, indicating the module's service.
520
521 ### Add Module to Configurations
522
523 Finally, to register a module in Medusa, you must add it to Medusa's configurations.
524
525 Medusa's configurations are set in the `medusa-config.ts` file, which is at the root directory of your Medusa application. The configuration object accepts a `modules` array, whose value is an array of modules to add to the application.
526
527 Add the `modules` property to the exported configurations in `medusa-config.ts`:
528
529 ```ts title="medusa-config.ts"
530 module.exports = defineConfig({
531 // ...
532 modules: [
533 {
534 resolve: "./src/modules/sanity",
535 options: {
536 api_token: process.env.SANITY_API_TOKEN,
537 project_id: process.env.SANITY_PROJECT_ID,
538 api_version: new Date().toISOString().split("T")[0],
539 dataset: "production",
540 studio_url: process.env.SANITY_STUDIO_URL ||
541 "http://localhost:3000/studio",
542 type_map: {
543 product: "product",
544 },
545 },
546 },
547 ],
548 })
549 ```
550
551 In the `modules` array, you pass a module object having the following properties:
552
553 - `resolve`: The path to the module to register in the application. It can also be the name of an NPM package.
554 - `options`: An object of options to pass to the module. These are the options you expect and use in the module's service.
555
556 Some of the module's options, such as the Sanity API key, are set in environment variables. So, add the following environment variables to `.env`:
557
558 ```shell
559 SANITY_API_TOKEN=
560 SANITY_PROJECT_ID=
561 SANITY_STUDIO_URL=http://localhost:8000/studio
562 ```
563
564 Where:
565
566 - `SANITY_API_TOKEN`: The API key token to connect to Sanity, which you can retrieve from the Sanity project's dashboard:
567 - Go to the API tab.
568
569 ![The API tab is at the top of the project dashboard next to Settings.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732091810/Medusa%20Resources/Screenshot_2024-11-20_at_10.35.29_AM_ltj7cd.png)
570
571 - Scroll down to Tokens and click on the "Add API Token" button.
572
573 ![The Add API token button is at the top right of the Tokens section.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732091810/Medusa%20Resources/Screenshot_2024-11-20_at_10.35.52_AM_ccgsum.png)
574
575 - Enter a name for the API token, choose "Editor" for the permissions, then click Save.
576
577 ![In the Token form, enter the name and choose "Editor" for permissions.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732091811/Medusa%20Resources/Screenshot_2024-11-20_at_10.36.25_AM_nqxa5y.png)
578
579 - `SANITY_PROJECT_ID`: The ID of the project, which you can find at the top section of your Sanity project's dashboard.
580
581 ![The project ID is in the top information of the project.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732091988/Medusa%20Resources/Screenshot_2024-11-20_at_10.39.24_AM_cscir8.png)
582
583 - `SANITY_STUDIO_URL`: The URL to access the studio. You'll set the studio up in a later section, but for now set it to `http://localhost:8000/studio`.
584
585 ### Test the Module
586
587 To test that the module is working, you'll start the Medusa application and see if the "Connected to Sanity" message is logged in the console.
588
589 To start the Medusa application, run the following command in the application's directory:
590
591 ```bash npm2yarn
592 npm run dev
593 ```
594
595 If you see the following message among the logs:
596
597 ```bash
598 info: Connected to Sanity
599 ```
600
601 That means your Sanity credentials were correct, and Medusa was able to connect to Sanity.
602
603 In the next steps, you'll create a link between the Product and Sanity modules to retrieve data between them easily, and build a flow around the Sanity Module to sync data.
604
605 ---
606
607 ## Step 5: Link Product and Sanity Modules
608
609 Since a product has a document in Sanity, you want to build an association between the [Product](../../../commerce-modules/product/page.mdx) and Sanity modules so that when you retrieve a product, you also retrieve its associated Sanity document.
610
611 However, modules are [isolated](!docs!/learn/fundamentals/modules/isolation) to ensure they're re-usable and don't have side effects when integrated into the Medusa application. So, to build associations between modules, you define [module links](!docs!/learn/fundamentals/module-links).
612
613 A Module Link associates two modules' data models while maintaining module isolation. A data model can be a table in the database or a virtual model from an external systems.
614
615 In this section, you'll define a link between the Product and Sanity modules.
616
617 Links are defined in a TypeScript or JavaScript file under the `src/links` directory. So, create the file `src/links/product-sanity.ts` with the following content:
618
619 ```ts title="src/links/product-sanity.ts"
620 import { defineLink } from "@medusajs/framework/utils"
621 import ProductModule from "@medusajs/medusa/product"
622 import { SANITY_MODULE } from "../modules/sanity"
623
624 defineLink(
625 {
626 linkable: ProductModule.linkable.product.id,
627 field: "id",
628 },
629 {
630 linkable: {
631 serviceName: SANITY_MODULE,
632 alias: "sanity_product",
633 primaryKey: "id",
634 },
635 },
636 {
637 readOnly: true,
638 }
639 )
640 ```
641
642 You define a link using `defineLink` from the Modules SDK. It accepts three parameters:
643
644 1. The first data model part of the link. In this case, it's the Product Module's `product` data model. A module has a special `linkable` property that contain link configurations for its data models.
645 2. The second data model part of the link. Since the Sanity Module doesn't have a Medusa data model, you specify the configurations in a `linkable` object that has the following properties:
646 - `serviceName`: The registration name in the Medusa container of the service managing the data model, which in this case is the Sanity Module's name (since the module's service is registered under that name).
647 - `alias`: The name to refer to the model part of this link, such as when retrieving the Sanity document of a product. You'll use this in a later section.
648 - `primaryKey`: The name of the data model's primary key field.
649 3. An object of configurations for the module link. By default, Medusa creates a table in the database to represent the link you define. Since the module link isn't created between two Medusa data models, you enable the `readOnly` configuration, which will tell Medusa not to create a table in the database for this link.
650
651 In the next steps, you'll see how this link allows you to retrieve documents when retrieving products.
652
653 ---
654
655 ## Step 6: Sync Data to Sanity
656
657 After integrating Sanity with a custom module, you now want to sync product data from Medusa to Sanity, automatically and manually. To implement the sync logic, you need a workflow.
658
659 A workflow is a series of queries and 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. You'll see how all of this works in the upcoming sections.
660
661 Within a workflow's steps, you resolve modules to use their service's functionalities as part of a bigger flow. Then, you can execute the workflow from other customizations, such as in response to an event or in an API route.
662
663 <Note>
664
665 Learn more about workflows in [this documentation](!docs!/learn/fundamentals/workflows)
666
667 </Note>
668
669 In this section, you'll create a workflow that syncs products from Medusa to Sanity. Later, you'll execute this workflow when a product is created or updated, or when an admin user triggers the syncing manually.
670
671 ### Create Step
672
673 The syncing workflow will have a single step that syncs products provided as an input to Sanity.
674
675 So, to implement that step, create the file `src/workflows/sanity-sync-products/steps/sync.ts` with the following content:
676
677 <Note>
678
679 If you get a type error on resolving the Sanity 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).
680
681 </Note>
682
683 export const syncStepHighlights = [
684 ["14", "createStep", "Create a step."],
685 ["16", "container", "The Medusa container to resolve resources."],
686 ["37", "graph", "Retrieve a paginated list of products with their sanity document."]
687 ]
688
689 ```ts title="src/workflows/sanity-sync-products/steps/sync.ts" highlights={syncStepHighlights}
690 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
691 import { ProductDTO } from "@medusajs/framework/types"
692 import {
693 ContainerRegistrationKeys,
694 promiseAll,
695 } from "@medusajs/framework/utils"
696 import SanityModuleService from "../../../modules/sanity/service"
697 import { SANITY_MODULE } from "../../../modules/sanity"
698
699 export type SyncStepInput = {
700 product_ids?: string[];
701 }
702
703 export const syncStep = createStep(
704 { name: "sync-step", async: true },
705 async (input: SyncStepInput, { container }) => {
706 const sanityModule: SanityModuleService = container.resolve(SANITY_MODULE)
707 const query = container.resolve(ContainerRegistrationKeys.QUERY)
708
709 const total = 0
710 const upsertMap: {
711 before: any
712 after: any
713 }[] = []
714
715 const batchSize = 200
716 const hasMore = true
717 const offset = 0
718 const filters = input.product_ids ? {
719 id: input.product_ids,
720 } : {}
721
722 while (hasMore) {
723 const {
724 data: products,
725 metadata: { count } = {},
726 } = await query.graph({
727 entity: "product",
728 fields: [
729 "id",
730 "title",
731 "sanity_product.*",
732 ],
733 filters,
734 pagination: {
735 skip: offset,
736 take: batchSize,
737 order: {
738 id: "ASC",
739 },
740 },
741 })
742
743 // TODO sync products
744 }
745 }
746 )
747 ```
748
749 You define the `syncStep` using the `createStep` function, which accepts two parameters:
750
751 - An object of step configurations. The object must have the `name` property, which is this step's unique name. Enabling the `async` property means that the workflow should run asynchronously in the background. This is useful when the workflow is triggered manually through an HTTP request, meaning the response will be returned to the client even if the workflow hasn't finished executing.
752 - The step's function definition as a second parameter.
753
754 The step function accepts the step's input as a first parameter, and an object of options as a second. The object of options has a `container` property, which is an instance of the Medusa container that you can use to resolve resources.
755
756 In the step, you resolve from the Medusa container Sanity Module's service and [Query](!docs!/learn/fundamentals/query), which is a tool that allows you to retrieve data across modules and links.
757
758 You use Query's `graph` method to retrieve products, filtering them by their IDs and applying pagination configurations. The `graph` method accepts a `fields` property in its object parameter, which indicates the product data model's fields and relations to retrieve.
759
760 Notice that you pass `sanity_product.*` in the `fields` array. Medusa will retrieve the Sanity document of each product using Sanity Module's `list` method and attach it to the returned product. So, you don't have to retrieve the products and documents separately. Each product object in the returned array will look similar to this:
761
762 ```json title="Example Product Object"
763 {
764 "id": "prod_123",
765 "title": "Shirt",
766 "sanity_product": {
767 "id": "prod_123",
768 "_type": "product",
769 // other Sanity fields...
770 }
771 }
772 ```
773
774 Next, you want to sync the retrieved products. So, replace the `TODO` in the `while` loop with the following:
775
776 ```ts title="src/workflows/sanity-sync-products/steps/sync.ts"
777 while (hasMore) {
778 // ...
779 try {
780 await promiseAll(
781 products.map(async (prod) => {
782 const after = await sanityModule.upsertSyncDocument(
783 "product",
784 prod as unknown as ProductDTO
785 )
786
787 upsertMap.push({
788 // @ts-ignore
789 before: prod.sanity_product,
790 after,
791 })
792
793 return after
794 })
795 )
796 } catch (e) {
797 return StepResponse.permanentFailure(
798 `An error occurred while syncing documents: ${e}`,
799 upsertMap
800 )
801 }
802
803 offset += batchSize
804 hasMore = offset < count
805 total += products.length
806 }
807 ```
808
809 In the `while` loop, you loop over the array of products to sync them to Sanity. You use the `promiseAll` Medusa utility that loops over an array of promises and ensures that all transactions within these promises are rolled back in case an error occurs.
810
811 For each product, you upsert it into Sanity, then push its document before and after the update to the `upsertMap`. You'll learn more about its use later.
812
813 You also wrap the `promiseAll` function within a try-catch block. In the catch block, you invoke and return `StepResponse.permanentFailure` which indicates that the step has failed but still invokes the rollback mechanism that you'll implement in a bit. The first parameter of `permanentFailure` is the error message, and the second is the data to use in the rollback mechanism.
814
815 Finally, after the `while` loop and at the end of the step, add the following return statement:
816
817 ```ts title="src/workflows/sanity-sync-products/steps/sync.ts"
818 return new StepResponse({ total }, upsertMap)
819 ```
820
821 If no errors occur, the step returns an instance of `StepResponse`, which must be returned by any step. It accepts as a first parameter the data to return to the workflow that executed this step.
822
823 #### Add Compensation Function
824
825 `StepResponse` accepts a second parameter, which is passed to the compensation function. A compensation function defines the rollback logic of a step, and it's only executed if an error occurs in the workflow. This eliminates data inconsistency if an error occurs and the workflow can't finish execution successfully.
826
827 <Note title="Tip">
828
829 Learn more about compensation functions in [this documentation](!docs!/learn/fundamentals/workflows/compensation-function).
830
831 </Note>
832
833 The `syncStep` creates or updates products in Sanity. So, the compensation function must delete created documents or revert the update of a document to its previous data. The compensation function is only executed if an error occurs.
834
835 To define the compensation function, pass a third-parameter to the `createStep` function:
836
837 ```ts title="src/workflows/sanity-sync-products/steps/sync.ts"
838 export const syncStep = createStep(
839 { name: "sync-step", async: true },
840 async (input: SyncStepInput, { container }) => {
841 // ...
842 },
843 async (upsertMap, { container }) => {
844 if (!upsertMap) {
845 return
846 }
847
848 const sanityModule: SanityModuleService = container.resolve(SANITY_MODULE)
849
850 await promiseAll(
851 upsertMap.map(({ before, after }) => {
852 if (!before) {
853 // delete the document
854 return sanityModule.delete(after._id)
855 }
856
857 const { _id: id, ...oldData } = before
858
859 return sanityModule.update(
860 id,
861 oldData
862 )
863 })
864 )
865 }
866 )
867 ```
868
869 The compensation function accepts the data passed in the step's `StepResponse` second parameter (in this case, `upsertMap`), and an object of options similar to that of the step.
870
871 In the compensation function, you resolve the Sanity Module's service, then loop over the `upsertMap` to delete created documents, or revert existing ones.
872
873 ### Create Workflow
874
875 You'll now create the workflow that uses the `syncStep`. This is the workflow that you'll later execute to sync data automatically or manually.
876
877 Workflows are created in a file under the `src/workflows` directory. So, create the file `src/workflows/sanity-sync-products/index.ts` with the following content:
878
879 ```ts title="src/workflows/sanity-sync-products/index.ts"
880 import {
881 createWorkflow,
882 WorkflowResponse,
883 } from "@medusajs/framework/workflows-sdk"
884 import { syncStep } from "./steps/sync"
885
886 export type SanitySyncProductsWorkflowInput = {
887 product_ids?: string[];
888 };
889
890 export const sanitySyncProductsWorkflow = createWorkflow(
891 { name: "sanity-sync-products", retentionTime: 10000 },
892 function (input: SanitySyncProductsWorkflowInput) {
893 const result = syncStep(input)
894
895 return new WorkflowResponse(result)
896 }
897 )
898 ```
899
900 You create a workflow using the `createWorkflow` from the Workflows SDK. It accepts an object of options as a first parameter, where the `name` property is required and indicates the workflow's unique name.
901
902 The `retentionTime` property indicates how long should the workflow's progress be saved in the database. This is useful if you later want to track whether the workflow is successfully executing.
903
904 `createWorkflow` accepts as a second parameter a constructor function, which is the workflow's implementation. In the function, you execute the `syncStep` to sync the specified products in the input, then return its result. Workflows must return an instance of `WorkflowResponse`.
905
906 <Note title="Tip">
907
908 A workflow's constructor function has some constraints in implementation. Learn more about them in [this documentation](!docs!/learn/fundamentals/workflows/constructor-constraints).
909
910 </Note>
911
912 You'll execute and test this workflow in the next steps.
913
914 ---
915
916 ## Step 7: Handle Product Changes in Medusa
917
918 You've defined the workflow to sync the products. Now, you want to execute it when a product is created or updated.
919
920 Medusa emits events when certain actions occur, such as when a product is created. Then, you can listen to those events in a subscriber.
921
922 A subscriber is an asynchronous function that listens to one or more events. Then, when those events are emitted, the subscriber is executed in the background of your application.
923
924 Subscribers are useful when you want to perform an action that isn't an integral part of a flow, but as a reaction to a performed action. In this case, syncing the products to Sanity isn't integral to creating a product, so you do it in a subscriber after the product is created.
925
926 <Note>
927
928 Learn more about events and subscribers in [this documentation](!docs!/learn/fundamentals/events-and-subscribers). You can also find the list of emitted events in [this reference](/references/events).
929
930 </Note>
931
932 So, to run the workflow you defined in the previous event when a product is created or updated, you'll create a subscriber that listens to the `product.created` and `product.updated` events.
933
934 Subscribers are created under the `src/subscribers` directory. So, create the file `src/subscribers/sanity-product-sync.ts` with the following content:
935
936 export const subscriberHighlights = [
937 ["10", "data", "The event's data payload."],
938 ["13", "sanitySyncProductsWorkflow", "Execute the workflow whenever a product is created or updated."],
939 ["21", "event", "The events that the subscriber is listening to."]
940 ]
941
942 ```ts title="src/subscribers/sanity-product-sync.ts" highlights={subscriberHighlights}
943 import type {
944 SubscriberArgs,
945 SubscriberConfig,
946 } from "@medusajs/medusa"
947 import {
948 sanitySyncProductsWorkflow,
949 } from "../workflows/sanity-sync-products"
950
951 export default async function upsertSanityProduct({
952 event: { data },
953 container,
954 }: SubscriberArgs<{ id: string }>) {
955 await sanitySyncProductsWorkflow(container).run({
956 input: {
957 product_ids: [data.id],
958 },
959 })
960 }
961
962 export const config: SubscriberConfig = {
963 event: ["product.created", "product.updated"],
964 }
965 ```
966
967 The subscriber function `upsertSanityProduct` accepts an object as a parameter that has the following properties:
968
969 - `event`: An object of the event's details. Its `data` property holds the data payload emitted with the event, which in this case is the ID of the product created or updated.
970 - `container`: An instance of the Medusa container to resolve resources.
971
972 In the subscriber, you execute the `sanitySyncProductsWorkflow` by invoking it, passing it the container, then invoking its `run` method. You pass the workflow's input in the `input` property of the `run`'s object parameter.
973
974 The subscriber file must also export a configuration object. It has an `event` property, which is the names of the events that the subscriber is listening to.
975
976 ### Test it Out
977
978 To test it out, run the Medusa application, then open the Medusa Admin in your browser at `http://localhost:9000/app`. Try creating or updating a product. You'll see the following message in the console:
979
980 ```bash
981 info: Processing product.created which has 1 subscribers
982 ```
983
984 This means that the `product.created` event was emitted and your subscriber was executed.
985
986 In the next step, you'll setup Sanity with Next.js, and you can then monitor the updates in Sanity's studio.
987
988 ---
989
990 ## Step 8: Setup Sanity with Next.js Starter Storefront
991
992 In this step, you'll install Sanity in the Next.js Starter and configure it. You'll then have a Sanity studio in your Next.js Starter Storefront, where you'll later view the product documents being synced from Medusa, and update their content that you'll display in the storefront on the product details page.
993
994 Sanity has a CLI tool that helps you with the setup. First, change to the Next.js Starter's directory (`apps/storefront`).
995
996 Then, run the following command:
997
998 ```bash badgeLabel="Storefront" badgeColor="blue"
999 npx sanity@latest init
1000 ```
1001
1002 You'll then be asked a few questions:
1003
1004 - For the project, select the Sanity project you created earlier in this guide.
1005 - For dataset, use `production` unless you changed it in the Sanity project.
1006 - Select yes for adding the Sanity configuration files to the Next.js folder.
1007 - Select yes for TypeScript.
1008 - Select yes for Sanity studio, and choose the `/studio` route.
1009 - Select clean project template.
1010 - Select yes for adding the project ID and dataset to `.env.local`.
1011
1012 Afterwards, the command will install the necessary dependencies for Sanity.
1013
1014 <Details summaryContent="Error during installation">
1015 If you run into an error during the installation of peer dependencies, try running the following command to install them:
1016
1017 ```bash
1018 yarn add next-sanity@9.8.15 @sanity/client@^6.22.4 @sanity/icons@^3.4.0 @sanity/types@^3.62.0 @sanity/ui@^2.8.10 next@^15.0.0 react@^19.0.0 react-dom@^19.0.0 sanity@^3.62.0 styled-components@^6.1
1019 ```
1020 </Details>
1021
1022 ### Update Middleware
1023
1024 The Next.js Starter storefront has a middleware that ensures all requests start with a country code (for example, `/us`).
1025
1026 Since the Sanity studio runs at `/studio`, the middleware should ignore requests to this path.
1027
1028 Open the file `src/middleware.ts` and find the following `if` condition:
1029
1030 ```ts title="src/middleware.ts" badgeLabel="Storefront" badgeColor="blue"
1031 if (
1032 urlHasCountryCode &&
1033 (!isOnboarding || onboardingCookie) &&
1034 (!cartId || cartIdCookie)
1035 ) {
1036 return NextResponse.next()
1037 }
1038 ```
1039
1040 Replace it with the following condition:
1041
1042 ```ts title="src/middleware.ts" badgeLabel="Storefront" badgeColor="blue"
1043 if (
1044 request.nextUrl.pathname.startsWith("/studio") ||
1045 urlHasCountryCode &&
1046 (!isOnboarding || onboardingCookie) &&
1047 (!cartId || cartIdCookie)
1048 ) {
1049 return NextResponse.next()
1050 }
1051 ```
1052
1053 If the path starts with `/studio`, the middleware will stop executing and the page will open.
1054
1055 ### Set CORS Settings
1056
1057 Every Sanity project has a configured set of CORS origins allowed, with the default being `http://localhost:3333`.
1058
1059 The Next.js Starter runs on the `8000` port, so you must add it to the allowed CORS origins.
1060
1061 In your Sanity project's dashboard:
1062
1063 1. Click on the API tab.
1064
1065 ![Find the API tab at the top of the dashboard.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732096643/Medusa%20Resources/Screenshot_2024-11-20_at_10.35.29_AM_ltj7cd.png)
1066
1067 2. Scroll down to CORS origins and click the "Add CORS origin" button.
1068
1069 ![Find the CORS origins section and click the Add CORS origin button at its top right.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732096997/Medusa%20Resources/Screenshot_2024-11-20_at_12.02.50_PM_ahsthb.png)
1070
1071 3. Enter `http://localhost:8000` in the Origin field.
1072 4. Enable the "Allow credentials" checkbox.
1073
1074 ![After filling out the Origin field, click on the Allow credentials checkbox to enable it.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732097074/Medusa%20Resources/Screenshot_2024-11-20_at_12.04.09_PM_nxdvwh.png)
1075
1076 5. Click the Save button.
1077
1078 ### Open Sanity Studio
1079
1080 To open the Sanity studio, start the Next.js Starter's development server:
1081
1082 ```bash npm2yarn
1083 npm run dev
1084 ```
1085
1086 Then, open `http://localhost:8000/studio` in your browser. The Sanity studio will open, but right now it's empty.
1087
1088 ---
1089
1090 ## Step 9: Add Product Schema Type in Sanity
1091
1092 In this step, you'll define the `product` schema type in Sanity. You' can then view the documents of that schema in the studio and update their content.
1093
1094 To create the schema type, create the file `src/sanity/schemaTypes/documents/product.ts` with the following content:
1095
1096 ```ts title="src/sanity/schemaTypes/documents/product.ts" badgeLabel="Storefront" badgeColor="blue"
1097 import { ComposeIcon } from "@sanity/icons"
1098 import { DocumentDefinition } from "sanity"
1099
1100 const productSchema: DocumentDefinition = {
1101 fields: [
1102 {
1103 name: "title",
1104 type: "string",
1105 },
1106 {
1107 group: "content",
1108 name: "specs",
1109 of: [
1110 {
1111 fields: [
1112 { name: "lang", title: "Language", type: "string" },
1113 { name: "title", title: "Title", type: "string" },
1114 {
1115 name: "content",
1116 rows: 3,
1117 title: "Content",
1118 type: "text",
1119 },
1120 ],
1121 name: "spec",
1122 type: "object",
1123 },
1124 ],
1125 type: "array",
1126 },
1127 {
1128 fields: [
1129 { name: "title", title: "Title", type: "string" },
1130 {
1131 name: "products",
1132 of: [{ to: [{ type: "product" }], type: "reference" }],
1133 title: "Addons",
1134 type: "array",
1135 validation: (Rule) => Rule.max(3),
1136 },
1137 ],
1138 name: "addons",
1139 type: "object",
1140 },
1141 ],
1142 name: "product",
1143 preview: {
1144 select: {
1145 title: "title",
1146 },
1147 },
1148 title: "Product Page",
1149 type: "document",
1150 groups: [{
1151 default: true,
1152 // @ts-ignore
1153 icon: ComposeIcon,
1154 name: "content",
1155 title: "Content",
1156 }],
1157 }
1158
1159 export default productSchema
1160 ```
1161
1162 This creates a schema that has the following fields:
1163
1164 - `title`: The title of a document, which is in this case the product's type.
1165 - `specs`: An array of product specs. Each object in the array has the following fields:
1166 - `lang`: This is useful if you want to have localized content.
1167 - `title`: The product's title.
1168 - `content`: Textual content, such as the product's description.
1169 - `addons`: An object of products related to this product.
1170
1171 When you sync the products from Medusa, you only sync the title. You manage the `specs` and `addons` fields within Sanity.
1172
1173 Next, replace the content of `src/sanity/schemaTypes/index.ts` with the following:
1174
1175 ```ts title="src/sanity/schemaTypes/index.ts" badgeLabel="Storefront" badgeColor="blue"
1176 import { SchemaPluginOptions } from "sanity"
1177 import productSchema from "./documents/product"
1178
1179 export const schema: SchemaPluginOptions = {
1180 types: [productSchema],
1181 templates: (templates) => templates.filter(
1182 (template) => template.schemaType !== "product"
1183 ),
1184 }
1185 ```
1186
1187 You add the product schema to the list of exported schemas, but also disable creating a new product. You can only create the products in Medusa.
1188
1189 ### Test it Out
1190
1191 To ensure that your schema is defined correctly and working, start the Next.js Starter Storefront's server, and open the Sanity studio again at `http://localhost:8000/studio`.
1192
1193 You'll find "Product Page" under Content. If you click on it, you'll find any product you've synced from Medusa.
1194
1195 If you haven't synced any products yet or you want to see the live update, try now creating or updating a product in Medusa. You'll find it added in the Sanity studio.
1196
1197 If you click on any product, you can edit its existing field under "Specs" or add new ones. In the next section, you'll learn how to show the content in the "Specs" field on the storefront's product details page.
1198
1199 ---
1200
1201 ## Step 10: Show Sanity Content in Next.js Starter Storefront
1202
1203 Now that you're managing a product's content in Sanity, you want to show that content on the storefront. In this step, you'll customize the Next.js Starter storefront to show a product's content as defined in Sanity.
1204
1205 A product's details are retrieved in the file `src/app/[countryCode]/(main)/products/[handle]/page.tsx`. So, replace the `ProductPage` function with the following:
1206
1207 export const sanityContentHighlights = [
1208 ["24", "sanity", "Get the product's content from Sanity."]
1209 ]
1210
1211 ```tsx title="src/app/[countryCode]/(main)/products/[handle]/page.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={sanityContentHighlights}
1212 // other imports...
1213 import { client } from "../../../../../sanity/lib/client"
1214
1215 // ...
1216
1217 export default async function ProductPage(props: Props) {
1218 const params = await props.params
1219 const region = await getRegion(params.countryCode)
1220
1221 if (!region) {
1222 notFound()
1223 }
1224
1225 const pricedProduct = await listProducts({
1226 countryCode: params.countryCode,
1227 queryParams: { handle: params.handle },
1228 }).then(({ response }) => response.products[0])
1229
1230 if (!pricedProduct) {
1231 notFound()
1232 }
1233
1234 // alternatively, you can filter the content by the language
1235 const sanity = (await client.getDocument(pricedProduct.id))?.specs[0]
1236
1237 return (
1238 <ProductTemplate
1239 product={pricedProduct}
1240 region={region}
1241 countryCode={params.countryCode}
1242 />
1243 )
1244 }
1245 ```
1246
1247 You import the Sanity client defined in `src/sanity/lib/client.ts` (this was generated by Sanity's CLI). Then, in the page's function, you retrieve the product's document by ID and pass its first step to the `ProductTemplate` component.
1248
1249 This is a simplified approach, but you can also have languages in your storefront and filter the spec based on the current language.
1250
1251 Next, you need to customize the `ProductTemplate` to accept the `sanity` prop. In the file `src/modules/products/templates/index.tsx` add the following to `ProductTemplateProps`:
1252
1253 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1254 type ProductTemplateProps = {
1255 // ...
1256 sanity?: {
1257 content: string
1258 }
1259 }
1260 ```
1261
1262 Then, add the `sanity` property to the expanded props of the component:
1263
1264 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1265 const ProductTemplate: React.FC<ProductTemplateProps> = ({
1266 // ...
1267 sanity,
1268 }) => {
1269 // ...
1270 }
1271 ```
1272
1273 Finally, pass the `sanity` prop to the `ProductInfo` component in the return statement:
1274
1275 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1276 <ProductInfo product={product} sanity={sanity} />
1277 ```
1278
1279 Next, you need to update the `ProductInfo` component to accept and use the `sanity` prop.
1280
1281 In `src/modules/products/templates/product-info/index.tsx`, update the `ProductInfoProps` to accept the `sanity` prop:
1282
1283 ```tsx title="src/modules/products/templates/product-info/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1284 type ProductInfoProps = {
1285 // ...
1286 sanity?: {
1287 content: string
1288 }
1289 }
1290 ```
1291
1292 Then, add the `sanity` property to the expanded props of the component:
1293
1294 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1295 const ProductInfo = ({
1296 // ...
1297 sanity,
1298 }: ProductInfoProps) => {
1299 // ...
1300 }
1301 ```
1302
1303 Next, find the following line in the return statement:
1304
1305 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1306 {product.description}
1307 ```
1308
1309 And replace it with the following:
1310
1311 ```tsx title="src/modules/products/templates/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1312 {sanity?.content || product.description}
1313 ```
1314
1315 Instead of showing the product's description on the product details page, this will show the content defined in Sanity if available.
1316
1317 ### Test it Out
1318
1319 To test this out, first, run both the Next.js Starter storefront and the Medusa application, and open the Sanity studio. Try editing the content of the first spec of a product.
1320
1321 Then, open the Next.js Starter storefront at `http://localhost:8000` and go to "Store" from the menu, then select the product you edited in Sanity.
1322
1323 In the product's page, you'll find under the product's name the content you put in Sanity.
1324
1325 You can now manage the product's content in Sanity, add more fields, and customize how you show them in the storefront. The Medusa application will also automatically create documents in Sanity for new products you add or update, ensuring your products are always synced across systems.
1326
1327 ---
1328
1329 ## Step 11: Customize Admin to Manually Sync Data
1330
1331 There are cases where you need to trigger the syncing of products manually, such as when an error occurs or you have products from before creating this integration.
1332
1333 The Medusa Admin dashboard is customizable, allowing you to either inject components, called [widgets](!docs!/learn/fundamentals/admin/widgets), into existing pages, or adding new pages, called [UI routes](!docs!/learn/fundamentals/admin/ui-routes). In these customizations, you can send requests to the Medusa application to perform custom operations.
1334
1335 In this step, you'll add a widget to the product's details page. In that page, you'll show whether a product is synced with Sanity, and allow the admin user to trigger syncing it manually.
1336
1337 ![The widget in the product details page.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732093722/Medusa%20Resources/Screenshot_2024-11-20_at_11.08.23_AM_wzftfv.png)
1338
1339 Before you do that, however, you need two new API routes in your Medusa application: one to retrieve a document from Sanity, and one to trigger syncing the product data.
1340
1341 <Note title="What is an API Route?">
1342
1343 An API route is a REST API endpoint that exposes commerce features to the admin dashboard or other frontend clients. Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes).
1344
1345 </Note>
1346
1347 ### Get Sanity Document API Route
1348
1349 In this section, you'll create the API route to retrieve a sanity document, and the URL to it in the Sanity studio.
1350
1351 To retrieve the URL to the Sanity studio, add the following method in the Sanity Module's service in `src/modules/sanity/service.ts`:
1352
1353 ```ts title="src/modules/sanity/service.ts"
1354 import { MedusaError } from "@medusajs/framework/utils"
1355
1356 class SanityModuleService {
1357 // ...
1358 async getStudioLink(
1359 type: string,
1360 id: string,
1361 config: { explicit_type?: boolean } = {}
1362 ) {
1363 const resolvedType = config.explicit_type ? type : this.typeMap[type]
1364 if (!this.studioUrl) {
1365 throw new MedusaError(
1366 MedusaError.Types.INVALID_ARGUMENT,
1367 "No studio URL provided"
1368 )
1369 }
1370 return `${this.studioUrl}/structure/${resolvedType};${id}`
1371 }
1372 }
1373 ```
1374
1375 The method uses the `studioUrl` property, which you set in the `constructor` using the `studio_url` module option, to get the studio link.
1376
1377 Then, to create the API route, create the file `src/api/admin/sanity/documents/[id]/route.ts` with the following content:
1378
1379 ```ts title="src/api/admin/sanity/documents/[id]/route.ts"
1380 import {
1381 MedusaRequest,
1382 MedusaResponse,
1383 } from "@medusajs/framework/http"
1384 import SanityModuleService from "src/modules/sanity/service"
1385 import { SANITY_MODULE } from "../../../../../modules/sanity"
1386
1387 export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
1388 const { id } = req.params
1389
1390 const sanityModule: SanityModuleService = req.scope.resolve(
1391 SANITY_MODULE
1392 )
1393 const sanityDocument = await sanityModule.retrieve(id)
1394
1395 const url = sanityDocument ?
1396 await sanityModule.getStudioLink(
1397 sanityDocument._type,
1398 sanityDocument._id,
1399 { explicit_type: true }
1400 )
1401 : ""
1402
1403 res.json({ sanity_document: sanityDocument, studio_url: url })
1404 }
1405 ```
1406
1407 This defines a `GET` API route at `/admin/sanity/documents/:id`, where `:id` is a dynamic path parameter indicating the ID of a document to retrieve.
1408
1409 In the `GET` route handler, you resolve the Sanity Module's service and use it to first retrieve the product's document, then the studio link of that document.
1410
1411 You return in the JSON response an object having the `sanity_document` and `studio_url` properties.
1412
1413 You'll test out this route in a later section.
1414
1415 <Note title="Tip">
1416
1417 Since the API route is added under the `/admin` prefix, only authenticated admin users can access it. Learn more about protected routes in [this documentation](!docs!/learn/fundamentals/api-routes/protected-routes).
1418
1419 </Note>
1420
1421 ### Trigger Sanity Sync API Route
1422
1423 In this section, you'll add the API route that manually triggers syncing a product to Sanity.
1424
1425 Since you already have the workflow to sync products, you only need to create an API route that executes it.
1426
1427 Create the file `src/api/admin/sanity/documents/[id]/sync/route.ts` with the following content:
1428
1429 ```ts title="src/api/admin/sanity/documents/[id]/sync/route.ts"
1430 import {
1431 MedusaRequest,
1432 MedusaResponse,
1433 } from "@medusajs/framework/http"
1434 import {
1435 sanitySyncProductsWorkflow,
1436 } from "../../../../../../workflows/sanity-sync-products"
1437
1438 export const POST = async (req: MedusaRequest, res: MedusaResponse) => {
1439 const { transaction } = await sanitySyncProductsWorkflow(req.scope)
1440 .run({
1441 input: { product_ids: [req.params.id] },
1442 })
1443
1444 res.json({ transaction_id: transaction.transactionId })
1445 }
1446 ```
1447
1448 You add a `POST` API route at `/admin/sanity/documents/:id/sync`, where `:id` is a dynamic path parameter that indicates the ID of a product to sync to Sanity.
1449
1450 In the `POST` API route handler, you execute the `sanitySyncProductsWorkflow`, passing it the ID of the product from the path parameter as an input.
1451
1452 In the next section, you'll customize the admin dashboard and send requests to the API route from there.
1453
1454 ### Sanity Product Widget
1455
1456 In this section, you'll add a widget in the product details page. The widget will show the Sanity document of the product and triggers syncing it to Sanity using the API routes you created.
1457
1458 To send requests from admin customizations to the Medusa server, you need to use Medusa's [JS SDK](../../../js-sdk/page.mdx). You'll also use [Tanstack Query](https://tanstack.com/query/latest) to benefit from features like data caching and invalidation.
1459
1460 <Note type="warning">
1461
1462 Do not install Tanstack Query as that will cause unexpected errors in your development. If you prefer installing it for better auto-completion in your code editor, make sure to install `v5.64.2` as a development dependency.
1463
1464 </Note>
1465
1466 To configure the JS SDK, create the file `src/admin/lib/sdk.ts` with the following content:
1467
1468 ```ts title="src/admin/lib/sdk.ts"
1469 import Medusa from "@medusajs/js-sdk"
1470
1471 export const sdk = new Medusa({
1472 baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
1473 debug: import.meta.env.DEV,
1474 auth: {
1475 type: "session",
1476 },
1477 })
1478 ```
1479
1480 You initialize the JS SDK and export it. You can learn more about configuring the JS SDK in [this guide](../../../js-sdk/page.mdx).
1481
1482 Next, you'll create hooks using Tanstack Query to send requests to the API routes you created earlier.
1483
1484 Create the file `src/admin/hooks/sanity.tsx` with the following content:
1485
1486 ```ts title="src/admin/hooks/sanity.tsx"
1487 import {
1488 useMutation,
1489 UseMutationOptions,
1490 useQueryClient,
1491 } from "@tanstack/react-query"
1492 import { sdk } from "../lib/sdk"
1493
1494 export const useTriggerSanityProductSync = (
1495 id: string,
1496 options?: UseMutationOptions
1497 ) => {
1498 const queryClient = useQueryClient()
1499
1500 return useMutation({
1501 mutationFn: () =>
1502 sdk.client.fetch(`/admin/sanity/documents/${id}/sync`, {
1503 method: "post",
1504 }),
1505 onSuccess: (data: any, variables: any, context: any) => {
1506 queryClient.invalidateQueries({
1507 queryKey: [`sanity_document`, `sanity_document_${id}`],
1508 })
1509
1510 options?.onSuccess?.(data, variables, context)
1511 },
1512 ...options,
1513 })
1514 }
1515 ```
1516
1517 You define the `useTriggerSanityProductSync` hook which creates a Tanstack Query mutation that, when executed, sends a request to the API route that triggers syncing the product to Sanity.
1518
1519 Add in the same file another hook:
1520
1521 ```ts title="src/admin/hooks/sanity.tsx"
1522 // other imports...
1523 import {
1524 // ...
1525 QueryKey,
1526 useQuery,
1527 UseQueryOptions,
1528 } from "@tanstack/react-query"
1529 import { FetchError } from "@medusajs/js-sdk"
1530
1531 // ...
1532
1533 export const useSanityDocument = (
1534 id: string,
1535 query?: Record<any, any>,
1536 options?: Omit<
1537 UseQueryOptions<
1538 Record<any, any>,
1539 FetchError,
1540 { sanity_document: Record<any, any>; studio_url: string },
1541 QueryKey
1542 >,
1543 "queryKey" | "queryFn"
1544 >
1545 ) => {
1546 const fetchSanityProductStatus = async (query?: Record<any, any>) => {
1547 return await sdk.client.fetch<Record<any, any>>(
1548 `/admin/sanity/documents/${id}`,
1549 {
1550 query,
1551 }
1552 )
1553 }
1554
1555 const { data, ...rest } = useQuery({
1556 queryFn: async () => fetchSanityProductStatus(query),
1557 queryKey: [`sanity_document_${id}`],
1558 ...options,
1559 })
1560
1561 return { ...data, ...rest }
1562 }
1563 ```
1564
1565 You define the hook `useSanityDocument` which retrieves the Sanity document of a product using Tankstack Query.
1566
1567 You can now create the widget injected in a product's details page. Widgets are react components created in a file under the `src/admin/widgets` directory.
1568
1569 So, create the file `src/admin/widgets/sanity-product.tsx` with the following content:
1570
1571 ```tsx title="src/admin/widgets/sanity-product.tsx"
1572 import { defineWidgetConfig } from "@medusajs/admin-sdk"
1573 import {
1574 AdminProduct,
1575 DetailWidgetProps,
1576 } from "@medusajs/types"
1577 import { ArrowUpRightOnBox } from "@medusajs/icons"
1578 import { Button, CodeBlock, Container, StatusBadge, toast } from "@medusajs/ui"
1579 import { useState } from "react"
1580 import {
1581 useSanityDocument,
1582 useTriggerSanityProductSync,
1583 } from "../hooks/sanity"
1584
1585 const ProductWidget = ({ data }: DetailWidgetProps<AdminProduct>) => {
1586 const { mutateAsync, isPending } = useTriggerSanityProductSync(data.id)
1587 const { sanity_document, studio_url, isLoading } = useSanityDocument(data.id)
1588 const [showCodeBlock, setShowCodeBlock] = useState(false)
1589
1590 const handleSync = async () => {
1591 try {
1592 await mutateAsync(undefined)
1593 toast.success(`Sync triggered.`)
1594 } catch (err) {
1595 toast.error(`Couldn't trigger sync: ${
1596 (err as Record<string, unknown>).message
1597 }`)
1598 }
1599 }
1600
1601 return (
1602 <Container>
1603 <div className="flex justify-between w-full items-center">
1604 <div className="flex gap-2 items-center">
1605 <h2>Sanity Status</h2>
1606 <div>
1607 {isLoading ? (
1608 "Loading..."
1609 ) : sanity_document?.title === data.title ? (
1610 <StatusBadge color="green">Synced</StatusBadge>
1611 ) : (
1612 <StatusBadge color="red">Not Synced</StatusBadge>
1613 )}
1614 </div>
1615 </div>
1616 <Button
1617 size="small"
1618 variant="secondary"
1619 onClick={handleSync}
1620 disabled={isPending}
1621 >
1622 Sync
1623 </Button>
1624 </div>
1625 <div className="mt-6">
1626 <div className="mb-4 flex gap-4">
1627 <Button
1628 size="small"
1629 variant="secondary"
1630 onClick={() => setShowCodeBlock(!showCodeBlock)}
1631 >
1632 {showCodeBlock ? "Hide" : "Show"} Sanity Document
1633 </Button>
1634 {studio_url && (
1635 <a href={studio_url} target="_blank" rel="noreferrer">
1636 <Button variant="transparent">
1637 <ArrowUpRightOnBox /> Sanity Studio
1638 </Button>
1639 </a>
1640 )}
1641 </div>
1642 {!isLoading && showCodeBlock && (
1643 <CodeBlock
1644 className="dark"
1645 snippets={[
1646 {
1647 language: "json",
1648 label: "Sanity Document",
1649 code: JSON.stringify(sanity_document, null, 2),
1650 },
1651 ]}
1652 >
1653 <CodeBlock.Body />
1654 </CodeBlock>
1655 )}
1656 </div>
1657 </Container>
1658 )
1659 }
1660
1661 // The widget's configurations
1662 export const config = defineWidgetConfig({
1663 zone: "product.details",
1664 })
1665
1666 export default ProductWidget
1667 ```
1668
1669 The file exports a `ProductWidget` component and a `config` object created with `defineWidgetConfig` from the Admin Extension SDK. In the `config` object, you specify the zone to inject the widget into in the `zone` property.
1670
1671 <Note title="Tip">
1672
1673 Find all widget injection zones in [this reference](../../../admin-widget-injection-zones/page.mdx).
1674
1675 </Note>
1676
1677 In the widget, you use the `useSanityDocument` to retrieve the product's document from Sanity by sending a request to the API route you created earlier. You show that document's details and a button to trigger syncing the data.
1678
1679 When the "Sync" button is clicked, you use the `useTriggerSanityProductSync` hook which sends a request to the API route you created earlier and executes the workflow that syncs the product to Sanity. The workflow will execute in the background, since you configured its step to be async.
1680
1681 To render a widget that matches the rest of the admin dashboard's design, you use components from the [Medusa UI package](!ui!), such as the `CodeBlock` or `Container` components.
1682
1683 <Note>
1684
1685 Refer to the [Admin Widgets](!docs!/learn/fundamentals/admin/widgets) documentation to learn more.
1686
1687 </Note>
1688
1689 ### Test it Out
1690
1691 To test these customizations out, start the Medusa application and open the admin dashboard. Then, choose a product and scroll down to the end of the page.
1692
1693 You'll find a new "Sanity Status" section showing you whether the product is synced to Sanity and its document's details. You can also click the Sync button, which will sync the product to Sanity.
1694
1695 ---
1696
1697 ## Step 12: Add Track Syncs Page to Medusa Admin
1698
1699 Earlier in this guide when introducing workflows, you learned that you can track the execution of a workflow. As a last step of this guide, you'll add a new page in the admin dashboard that shows the executions of the `sanitySyncProductsWorkflow` and their status. You'll also add the ability to sync all products to Sanity from that page.
1700
1701 ![A screenshot of the page to track and trigger syncs.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732095185/Medusa%20Resources/Screenshot_2024-11-20_at_11.09.42_AM_te8xic.png)
1702
1703 ### Retrieve Sync Executions API Route
1704
1705 Medusa has a [workflow engine](../../../infrastructure-modules/workflow-engine/page.mdx) that manages workflow executions, roll-backs, and other functionalities under the hood.
1706
1707 The workflow engine is an [Infrastructure Module](!docs!/learn/fundamentals/modules/infrastructure-modules), which can be replaced with a [Redis Workflow Engine](../../../infrastructure-modules/workflow-engine/redis/page.mdx), or a custom one of your choice, allowing you to take ownership of your application's tooling.
1708
1709 In your customizations, you can resolve the workflow engine from the container and manage executions of a workflow, such as retrieve them and check their progress.
1710
1711 In this section, you'll create an API route to retrieve the stored executions of the `sanitySyncProductsWorkflow` workflow, so that you can display them later on the dashboard.
1712
1713 <Note title="Tip">
1714
1715 When you defined the `sanitySyncProductsWorkflow`, you set its `retentionTime` option so that you can store the workflow execution's details temporarily. If a workflow doesn't have this option set, its execution won't be stored for tracking.
1716
1717 </Note>
1718
1719 Create the file `src/api/admin/sanity/syncs/route.ts` with the following content:
1720
1721 ```ts title="src/api/admin/sanity/syncs/route.ts"
1722 import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
1723 import { Modules } from "@medusajs/framework/utils"
1724 import {
1725 sanitySyncProductsWorkflow,
1726 } from "../../../../workflows/sanity-sync-products"
1727
1728 export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
1729 const workflowEngine = req.scope.resolve(
1730 Modules.WORKFLOW_ENGINE
1731 )
1732
1733 const [executions, count] = await workflowEngine
1734 .listAndCountWorkflowExecutions(
1735 {
1736 workflow_id: sanitySyncProductsWorkflow.getName(),
1737 },
1738 { order: { created_at: "DESC" } }
1739 )
1740
1741 res.json({ workflow_executions: executions, count })
1742 }
1743 ```
1744
1745 You add a `GET` API route at `/admin/sanity/syncs`. In the API route handler, you resolve the Workflow Engine Module's service from the Medusa container. You use the `listAndCountWorkflowExecutions` method to retrieve the executions of the `sanitySyncProductsWorkflow` workflow, filtering by its name.
1746
1747 You return the executions in the JSON response of the route.
1748
1749 ### Trigger Sync API Route
1750
1751 In this section, you'll add another API route that triggers syncing all products to Sanity.
1752
1753 In the same file `src/api/admin/sanity/syncs/route.ts`, add the following:
1754
1755 ```ts title="api/admin/sanity/syncs/route.ts"
1756 export const POST = async (req: MedusaRequest, res: MedusaResponse) => {
1757 const { transaction } = await sanitySyncProductsWorkflow(req.scope).run({
1758 input: {},
1759 })
1760
1761 res.json({ transaction_id: transaction.transactionId })
1762 }
1763 ```
1764
1765 This adds a `POST` API route at `/admin/sanity/syncs`. In the route handler, you execute the `sanitySyncProductsWorkflow` without passing it a `product_ids` input. The step in the workflow will retrieve all products, instead of filtering them by ID, and sync them to Sanity.
1766
1767 You return the transaction ID of the workflow, which you can use to track the execution's progress since the workflow will run in the background. This is not implemented in this guide, but Medusa has a [Get Execution API route](!api!/admin/workflows-executions/get-exection) that you can use to get the details of a workflow's execution.
1768
1769 ### Add Sanity UI Route
1770
1771 In this section, you'll add a UI route in the admin dashboard, which is a new page, that shows the list of `sanitySyncProductsWorkflow` executions and allows triggering sync of all products in Medusa.
1772
1773 A UI route is React component exported in a file under the `src/admin/routes` directory. Similar to a widget, a UI route can also send requests to the Medusa application to perform actions using your custom API routes.
1774
1775 Before creating the UI route, you'll create hooks using Tanstack Query that send requests to these UI routes. In the file `src/admin/hooks/sanity.tsx`, add the following two new hooks:
1776
1777 ```tsx title="src/admin/hooks/sanity.tsx"
1778 export const useTriggerSanitySync = (options?: UseMutationOptions) => {
1779 const queryClient = useQueryClient()
1780
1781 return useMutation({
1782 mutationFn: () =>
1783 sdk.client.fetch(`/admin/sanity/syncs`, {
1784 method: "post",
1785 }),
1786 onSuccess: (data: any, variables: any, context: any) => {
1787 queryClient.invalidateQueries({
1788 queryKey: [`sanity_sync`],
1789 })
1790
1791 options?.onSuccess?.(data, variables, context)
1792 },
1793 ...options,
1794 })
1795 }
1796
1797 export const useSanitySyncs = (
1798 query?: Record<any, any>,
1799 options?: Omit<
1800 UseQueryOptions<
1801 Record<any, any>,
1802 FetchError,
1803 { workflow_executions: Record<any, any>[] },
1804 QueryKey
1805 >,
1806 "queryKey" | "queryFn"
1807 >
1808 ) => {
1809 const fetchSanitySyncs = async (query?: Record<any, any>) => {
1810 return await sdk.client.fetch<Record<any, any>>(`/admin/sanity/syncs`, {
1811 query,
1812 })
1813 }
1814
1815 const { data, ...rest } = useQuery({
1816 queryFn: async () => fetchSanitySyncs(query),
1817 queryKey: [`sanity_sync`],
1818 ...options,
1819 })
1820
1821 return { ...data, ...rest }
1822 }
1823 ```
1824
1825 The `useTriggerSanitySync` hook creates a mutation that, when executed, sends a request to the trigger sync API route you created earlier to sync all products.
1826
1827 The `useSanitySyncs` hook sends a request to the retrieve sync executions API route that you created earlier to retrieve the workflow's executions.
1828
1829 Finally, to create the UI route, create the file `src/admin/routes/sanity/page.tsx` with the following content:
1830
1831 ```tsx title="src/admin/routes/sanity/page.tsx"
1832 import { defineRouteConfig } from "@medusajs/admin-sdk"
1833 import { Sanity } from "@medusajs/icons"
1834 import {
1835 Badge,
1836 Button,
1837 Container,
1838 Heading,
1839 Table,
1840 Toaster,
1841 toast,
1842 } from "@medusajs/ui"
1843 import { useSanitySyncs, useTriggerSanitySync } from "../../hooks/sanity"
1844
1845 const SanityRoute = () => {
1846 const { mutateAsync, isPending } = useTriggerSanitySync()
1847 const { workflow_executions, refetch } = useSanitySyncs()
1848
1849 const handleSync = async () => {
1850 try {
1851 await mutateAsync()
1852 toast.success(`Sync triggered.`)
1853 refetch()
1854 } catch (err) {
1855 toast.error(`Couldn't trigger sync: ${
1856 (err as Record<string, unknown>).message
1857 }`)
1858 }
1859 }
1860
1861 const getBadgeColor = (state: string) => {
1862 switch (state) {
1863 case "invoking":
1864 return "blue"
1865 case "done":
1866 return "green"
1867 case "failed":
1868 return "red"
1869 default:
1870 return "grey"
1871 }
1872 }
1873
1874 return (
1875 <>
1876 <Container className="flex flex-col p-0 overflow-hidden">
1877 <div className="p-6 flex justify-between">
1878 <Heading className="font-sans font-medium h1-core">
1879 Sanity Syncs
1880 </Heading>
1881 <Button
1882 variant="secondary"
1883 size="small"
1884 onClick={handleSync}
1885 disabled={isPending}
1886 >
1887 Trigger Sync
1888 </Button>
1889 </div>
1890 <Table>
1891 <Table.Header>
1892 <Table.Row>
1893 <Table.HeaderCell>Sync ID</Table.HeaderCell>
1894 <Table.HeaderCell>Status</Table.HeaderCell>
1895 <Table.HeaderCell>Created At</Table.HeaderCell>
1896 <Table.HeaderCell>Updated At</Table.HeaderCell>
1897 </Table.Row>
1898 </Table.Header>
1899
1900 <Table.Body>
1901 {(workflow_executions || []).map((execution) => (
1902 <Table.Row
1903 key={execution.id}
1904 className="cursor-pointer"
1905 onClick={() =>
1906 (window.location.href = `/app/sanity/${execution.id}`)
1907 }
1908 >
1909 <Table.Cell>{execution.id}</Table.Cell>
1910 <Table.Cell>
1911 <Badge
1912 rounded="full"
1913 size="2xsmall"
1914 color={getBadgeColor(execution.state)}
1915 >
1916 {execution.state}
1917 </Badge>
1918 </Table.Cell>
1919 <Table.Cell>{execution.created_at}</Table.Cell>
1920 <Table.Cell>{execution.updated_at}</Table.Cell>
1921 </Table.Row>
1922 ))}
1923 </Table.Body>
1924 </Table>
1925 </Container>
1926 <Toaster />
1927 </>
1928 )
1929 }
1930
1931 export const config = defineRouteConfig({
1932 label: "Sanity",
1933 icon: Sanity,
1934 })
1935
1936 export default SanityRoute
1937 ```
1938
1939 The file's path relative to the `src/admin/routes` directory indicates its path in the admin dashboard. So, this adds a new route at the path `http://localhost:9000/app/sanity`.
1940
1941 The file must export the UI route's component. Also, to add an item in the sidebar for the UI route, you export a configuration object, created with `defineRouteConfig` from the Admin Extension SDK. The function accepts the following properties:
1942
1943 - `label`: The sidebar item's label.
1944 - `icon`: The icon to the show in the sidebar.
1945
1946 In the UI route, you use the `useSanitySyncs` hook to retrieve the list of sync executions and display them with their status. You also show a "Trigger Sync" button that, when clicked, uses the mutation from the `useTriggerSanitySync` hook to send a request to the Medusa application and trigger the sync.
1947
1948 To display components that match the design of the Medusa Admin, you use components from the [Medusa UI package](!ui!).
1949
1950 <Note>
1951
1952 Learn more about UI routes in [this documentation](!docs!/learn/fundamentals/admin/ui-routes).
1953
1954 </Note>
1955
1956 ### Test it Out
1957
1958 To test it out, start the Medusa application and open the admin dashboard. After logging in, you'll find a new "Sanity" item in the sidebar.
1959
1960 If you click on it, you'll see a table of the latest syncs. You also trigger syncing by clicking the "Trigger Sync" button. After you click the button, you should see a new execution added to the table.
1961
1962 ---
1963
1964 ## Next Steps
1965
1966 You've now integrated Medusa with Sanity and can benefit from powerful commerce and CMS features.
1967
1968 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.
1969
1970 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).