1 ---
2 products:
3 - product
4 ---
5
6 import { Card, Note, Prerequisites, Details, WorkflowDiagram } from "docs-ui"
7 import { Github, PlaySolid } from "@medusajs/icons"
8
9 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1743097088/Medusa%20Resources/integrations-algolia_qwpguu.jpg"
10
11 export const metadata = {
12 title: `Integrate Algolia (Search) with Medusa`,
13 openGraph: {
14 images: [
15 {
16 url: ogImage,
17 width: 1600,
18 height: 900,
19 type: "image/jpeg"
20 }
21 ],
22 },
23 twitter: {
24 images: [
25 {
26 url: ogImage,
27 width: 1600,
28 height: 900,
29 type: "image/jpeg"
30 }
31 ]
32 }
33 }
34
35 # {metadata.title}
36
37 In this tutorial, you'll learn how to integrate Medusa with Algolia.
38
39 <Note title="Deprecated" type="warning">
40
41 This guide is deprecated as of Medusa v2.21.1, which introduced the [Search Module](/infrastructure-modules/search). Rather than the custom module this guide builds, consider one of the following instead:
42
43 - [Medusa Search](!cloud!/search), the managed search service for [Cloud](!cloud!) projects. Refer to [Medusa Search vs Algolia](!cloud!/search/algolia) for a comparison.
44 - A [Search Module Provider](/references/search/provider) for Algolia, which keeps Algolia behind the Search Module's index definitions and `query.search`.
45
46 If you already followed this guide, refer to [Migrate from Algolia to Medusa Search](!cloud!/search/migrate-from-algolia) for the migration steps.
47
48 </Note>
49
50 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa's architecture supports integrating third-party services, such as a search engine, allowing you to build your unique requirements around core commerce flows.
51
52 [Algolia](https://www.algolia.com/doc/) is a search engine that enables you to build and manage an intuitive search experience for your customers. By integrating Algolia with Medusa, you can index e-commerce data, such as products, and allow clients to search through them.
53
54 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
55
56 ## Summary
57
58 By following this tutorial, you'll learn how to:
59
60 - Install and set up Medusa.
61 - Integrate Algolia into Medusa.
62 - Trigger Algolia reindexing when a product is created, updated, deleted, or when the admin manually triggers a reindex.
63 - Customize the Next.js Starter Storefront to allow searching for products through Algolia.
64
65 ![Diagram illustrating the integration of Algolia with Medusa](https://res.cloudinary.com/dza7lstvk/image/upload/v1742889842/Medusa%20Resources/algolia-summary_lhegrr.jpg)
66
67 <CardList items={[
68 {
69 href: "https://github.com/medusajs/examples/tree/main/algolia-integration",
70 title: "Algolia Integration Repository",
71 text: "Find the full code for this guide in this repository.",
72 icon: Github,
73 },
74 {
75 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1742829748/OpenApi/Algolia-Search_t1zlkd.yaml",
76 title: "OpenApi Specs for Postman",
77 text: "Import this OpenApi Specs file into tools like Postman.",
78 icon: PlaySolid,
79 },
80 ]} />
81
82 ---
83
84 ## Step 1: Install a Medusa Application
85
86 <Prerequisites items={[
87 {
88 text: "Node.js v20.19.0+ or v22.12.0+",
89 link: "https://nodejs.org/en/download"
90 },
91 {
92 text: "Git CLI tool",
93 link: "https://git-scm.com/downloads"
94 },
95 {
96 text: "PostgreSQL",
97 link: "https://www.postgresql.org/download/"
98 }
99 ]} />
100
101 Start by installing the Medusa application on your machine with the following command:
102
103 ```bash
104 npx create-medusa-app@latest
105 ```
106
107 You'll first be asked for the project's name. Then, when asked whether you want to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
108
109 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.
110
111 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.
112
113 <Note title="Ran into Errors">
114
115 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
116
117 </Note>
118
119 <Note>
120
121 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
122
123 </Note>
124
125 ---
126
127 ## Step 2: Create Algolia Module
128
129 To integrate third-party services into Medusa, you create a custom module. A module is a reusable 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.
130
131 In this step, you'll create a custom module that provides the necessary functionalities to integrate Algolia with Medusa.
132
133 <Note>
134
135 Refer to the [Modules documentation](!docs!/learn/fundamentals/modules) to learn more.
136
137 </Note>
138
139 Before building the module, you need to install Algolia's JavaScript client. Run the following command in your Medusa application's root directory:
140
141 ```bash npm2yarn
142 npm install algoliasearch
143 ```
144
145 ### Create Module Directory
146
147 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/algolia`.
148
149 ### Create Service
150
151 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.
152
153 In this section, you'll create the Algolia Module's service and the methods necessary to manage indexed products in Algolia and search through them.
154
155 To create the Algolia Module's service, create the file `src/modules/algolia/service.ts` with the following content:
156
157 ```ts title="src/modules/algolia/service.ts"
158 import { algoliasearch, SearchClient } from "algoliasearch"
159
160 type AlgoliaOptions = {
161 apiKey: string;
162 appId: string;
163 productIndexName: string;
164 }
165
166 export type AlgoliaIndexType = "product"
167
168 export default class AlgoliaModuleService {
169 private client: SearchClient
170 private options: AlgoliaOptions
171
172 constructor({}, options: AlgoliaOptions) {
173 this.client = algoliasearch(options.appId, options.apiKey)
174 this.options = options
175 }
176
177 // TODO add methods
178 }
179 ```
180
181 You export a class that will be the Algolia Module's main service. In the service, you define two properties:
182
183 - `client`: An instance of the Algolia Search Client, which you'll use to perform actions with Algolia's API.
184 - `options`: An object of options that the Module receives when it's registered, which you'll learn about later. The options contain:
185 - `apiKey`: The Algolia API key.
186 - `appId`: The Algolia App ID.
187 - `productIndexName`: The name of the index where products are stored.
188
189 <Note title="Tip">
190
191 If you want to index other types of data, such as product categories, you can add new properties for their index names in the `AlgoliaOptions` type.
192
193 </Note>
194
195 A module's service receives the module's options as a second parameter in its constructor. In the constructor, you initialize the Algolia client using the module's options.
196
197 <Note title="What is the first constructor parameter?">
198
199 A module has a container that holds all resources registered in that module, and you can access those resources in the first parameter of the constructor. Learn more about it in the [Module Container documentation](!docs!/learn/fundamentals/modules/container).
200
201 </Note>
202
203 #### Index Data Method
204
205 The first method you need to add to the service is a method that receives an array of data to add or update in Algolia's index.
206
207 Add the following methods to the `AlgoliaModuleService` class:
208
209 ```ts title="src/modules/algolia/service.ts"
210 import { MedusaError } from "@medusajs/framework/utils"
211
212 export default class AlgoliaModuleService {
213 // ...
214 async getIndexName(type: AlgoliaIndexType) {
215 switch (type) {
216 case "product":
217 return this.options.productIndexName
218 default:
219 throw new MedusaError(
220 MedusaError.Types.INVALID_DATA,
221 `Invalid index type: ${type}`
222 )
223 }
224 }
225
226 async indexData(data: Record<string, unknown>[], type: AlgoliaIndexType = "product") {
227 const indexName = await this.getIndexName(type)
228 this.client.saveObjects({
229 indexName,
230 objects: data.map((item) => ({
231 ...item,
232 // set the object ID to allow updating later
233 objectID: item.id,
234 })),
235 })
236 }
237 }
238 ```
239
240 You define two methods:
241
242 1. `getIndexName`: A method that receives an `AlgoliaIndexType` (defined in the previous snippt) and returns the index name for that type. In this case, you only have one type, `product`, so you return the product index name.
243 - If you want to index other types of data, you can add more cases to the switch statement.
244 2. `indexData`: A method that receives an array of data and an `AlgoliaIndexType`. The method indexes the data in the Algolia index for the given type.
245 - Notice that you set the `objectID` property of each object to the object's `id`. This ensures that you later update the object instead of creating a new one.
246
247 #### Retrieve and Delete Methods
248
249 The next methods you'll add to the service are methods to retrieve and delete data from the Algolia index. You'll see their use later as you keep the Algolia index in sync with Medusa.
250
251 Add the following methods to the `AlgoliaModuleService` class:
252
253 ```ts title="src/modules/algolia/service.ts"
254 export default class AlgoliaModuleService {
255 // ...
256
257 async retrieveFromIndex(objectIDs: string[], type: AlgoliaIndexType = "product") {
258 const indexName = await this.getIndexName(type)
259 return await this.client.getObjects<Record<string, unknown>>({
260 requests: objectIDs.map((objectID) => ({
261 indexName,
262 objectID,
263 })),
264 })
265 }
266
267 async deleteFromIndex(objectIDs: string[], type: AlgoliaIndexType = "product") {
268 const indexName = await this.getIndexName(type)
269 await this.client.deleteObjects({
270 indexName,
271 objectIDs,
272 })
273 }
274 }
275 ```
276
277 You define two methods:
278
279 1. `retrieveFromIndex`: A method that receives an array of object IDs and an `AlgoliaIndexType`. The method retrieves the objects with the given IDs from the Algolia index.
280 2. `deleteFromIndex`: A method that receives an array of object IDs and an `AlgoliaIndexType`. The method deletes the objects with the given IDs from the Algolia index.
281
282 #### Search Method
283
284 The last method you'll implement is a method to search through the Algolia index. You'll later use this method to expose the search functionality to clients, such as the Next.js Starter Storefront.
285
286 Add the following method to the `AlgoliaModuleService` class:
287
288 ```ts title="src/modules/algolia/service.ts"
289 export default class AlgoliaModuleService {
290 // ...
291
292 async search(query: string, type: AlgoliaIndexType = "product") {
293 const indexName = await this.getIndexName(type)
294 return await this.client.search({
295 requests: [
296 {
297 indexName,
298 query,
299 },
300 ],
301 })
302 }
303 }
304 ```
305
306 The `search` method receives a query string and an `AlgoliaIndexType`. The method searches through the Algolia index for the given type, such as products, and returns the results.
307
308 ### Export Module Definition
309
310 The final piece to a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
311
312 So, create the file `src/modules/algolia/index.ts` with the following content:
313
314 ```ts title="src/modules/algolia/index.ts"
315 import { Module } from "@medusajs/framework/utils"
316 import AlgoliaModuleService from "./service"
317
318 export const ALGOLIA_MODULE = "algolia"
319
320 export default Module(ALGOLIA_MODULE, {
321 service: AlgoliaModuleService,
322 })
323 ```
324
325 You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
326
327 1. The module's name, which is `algolia`.
328 2. An object with a required property `service` indicating the module's service.
329
330 You also export the module's name as `ALGOLIA_MODULE` so you can reference it later.
331
332 ### Add Module to Medusa's Configurations
333
334 Once you finish building the module, add it to Medusa's configurations to start using it.
335
336 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
337
338 ```ts title="medusa-config.ts"
339 module.exports = defineConfig({
340 // ...
341 modules: [
342 {
343 resolve: "./src/modules/algolia",
344 options: {
345 appId: process.env.ALGOLIA_APP_ID!,
346 apiKey: process.env.ALGOLIA_API_KEY!,
347 productIndexName: process.env.ALGOLIA_PRODUCT_INDEX_NAME!,
348 },
349 },
350 ],
351 })
352 ```
353
354 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.
355
356 You also pass an `options` property with the module's options, including the Algolia App ID, API Key, and the product index name.
357
358 ### Add Environment Variables
359
360 Before you can start using the Algolia Module, you need to set the environment variables for the Algolia App ID, API Key, and the product index name.
361
362 Add the following environment variables to your `.env` file:
363
364 ```env
365 ALGOLIA_APP_ID=your-algolia-app-id
366 ALGOLIA_API_KEY=your-algolia-api-key
367 ALGOLIA_PRODUCT_INDEX_NAME=your-product-index-name
368 ```
369
370 Where:
371
372 - `your-algolia-app-id` is your Algolia App ID. You can retrieve it from the Algolia dashboard by clicking at the application ID at the top left next to the sidebar. The pop up will show the application ID below the application's name.
373
374 ![Find the Algolia App ID by clicking on the application name in the Algolia dashboard, then copying the ID below the name in the pop-up](https://res.cloudinary.com/dza7lstvk/image/upload/v1742815360/Medusa%20Resources/Screenshot_2025-03-24_at_1.19.30_PM_kdp3y5.png)
375
376 - `your-algolia-api-key` is your Algolia API Key. To retrieve it from the Algolia dashboard:
377 1. Click on Settings in the sidebar.
378 2. Choose API Keys under "Team and Access".
379
380 ![In the settings page, find the Team and Access section at the right of the page and choose API Keys](https://res.cloudinary.com/dza7lstvk/image/upload/v1742815534/Medusa%20Resources/Screenshot_2025-03-24_at_1.25.09_PM_hwsiba.png)
381
382 3. Copy the Admin API Key.
383
384 - `your-product-index-name` is the name of the index where you'll store products. You can find it by going to Search -> Index, and copying the index name at the top of the page.
385
386 ![In the Algolia dashboard, go to Search -> Index and copy the index name at the top of the page](https://res.cloudinary.com/dza7lstvk/image/upload/v1742815790/Medusa%20Resources/Screenshot_2025-03-24_at_1.28.58_PM_yq10sf.png)
387
388 Your module is now ready for use. You'll see how to use it in the next steps.
389
390 ---
391
392 ## Step 3: Sync Products to Algolia Workflow
393
394 To keep the Algolia index in sync with Medusa, you need to trigger indexing when products are created, updated, or deleted in Medusa. You can also allow the admin to manually trigger a reindex.
395
396 To implement the indexing functionality, you need to create a [workflow](!docs!/learn/fundamentals/workflows). A workflow 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.
397
398 <Note>
399
400 Learn more about workflows in the [Workflows documentation](!docs!/learn/fundamentals/workflows).
401
402 </Note>
403
404 In this step, you'll create a workflow that indexes products in Algolia. In the next steps, you'll learn how to use the workflow when products are created, updated, or deleted, or when the admin manually triggers a reindex.
405
406 The workflow has the following steps:
407
408 <WorkflowDiagram
409 workflow={{
410 name: "syncProductsWorkflow",
411 steps: [
412 {
413 type: "step",
414 name: "useQueryGraphStep",
415 description: "Retrieve products matching specified filters and pagination parameters.",
416 link: "/references/helper-steps/useQueryGraphStep",
417 depth: 1
418 },
419 {
420 type: "step",
421 name: "syncProductsStep",
422 description: "Index published products in Algolia.",
423 depth: 2
424 },
425 {
426 type: "step",
427 name: "deleteProductsFromAlgoliaStep",
428 description: "Delete unpublished products from Algolia.",
429 depth: 3
430 }
431 ]
432 }}
433 hideLegend
434 />
435
436 Medusa provides the `useQueryGraphStep` in its `@medusajs/medusa/core-flows` package. So, you only need to implement the other steps.
437
438 ### syncProductsStep
439
440 In the second step of the workflow, you create or update indexes in Algolia for the products retrieved in the first step.
441
442 To create the step, create the file `src/workflows/steps/sync-products.ts` with the following content:
443
444 <Note>
445
446 If you get a type error on resolving the Algolia 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).
447
448 </Note>
449
450 ```ts title="src/workflows/steps/sync-products.ts"
451 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
452 import { ALGOLIA_MODULE } from "../../modules/algolia"
453 import AlgoliaModuleService from "../../modules/algolia/service"
454
455 export type SyncProductsStepInput = {
456 products: {
457 id: string
458 title: string
459 description?: string
460 handle: string
461 thumbnail?: string
462 categories: {
463 id: string
464 name: string
465 handle: string
466 }[]
467 tags: {
468 id: string
469 value: string
470 }[]
471 }[]
472 }
473
474 export const syncProductsStep = createStep(
475 "sync-products",
476 async ({ products }: SyncProductsStepInput, { container }) => {
477 const algoliaModuleService: AlgoliaModuleService = container.resolve(ALGOLIA_MODULE)
478
479 const existingProducts = (await algoliaModuleService.retrieveFromIndex(
480 products.map((product) => product.id),
481 "product"
482 )).results.filter(Boolean)
483 const newProducts = products.filter(
484 (product) => !existingProducts.some((p) => p.objectID === product.id)
485 )
486 await algoliaModuleService.indexData(
487 products as unknown as Record<string, unknown>[],
488 "product"
489 )
490
491 return new StepResponse(undefined, {
492 newProducts: newProducts.map((product) => product.id),
493 existingProducts,
494 })
495 }
496 // TODO add compensation
497 )
498 ```
499
500 You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
501
502 1. The step's unique name, which is `sync-products`.
503 2. An async function that receives two parameters:
504 - The step's input, which is in this case an object holding an array of products to sync into Algolia.
505 - 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.
506
507 In the step function, you resolve the Algolia Module's service from the Medusa container using the name you exported in the module definition's file.
508
509 Then, you retrieve the products that are already indexed in Algolia and determine which products are new. You'll learn why this is useful in a bit.
510
511 Finally, you pass the products you received in the input to Algolia to create or update its indices.
512
513 A step function must return a `StepResponse` instance. The `StepResponse` constructor accepts two parameters:
514
515 1. The step's output, which in this case is `undefined`.
516 2. Data to pass to the step's compensation function.
517
518 #### Compensation Function
519
520 The compensation function undoes the actions performed in a step. Then, if an error occurs during the workflow's execution, the compensation functions of executed steps are called to roll back the changes. This mechanism ensures data consistency in your application, especially as you integrate external systems.
521
522 To add a compensation function to a step, pass it as a third parameter to `createStep`:
523
524 ```ts title="src/workflows/steps/sync-products.ts"
525 export const syncProductsStep = createStep(
526 // ...
527 async (input, { container }) => {
528 if (!input) {
529 return
530 }
531
532 const algoliaModuleService: AlgoliaModuleService = container.resolve(ALGOLIA_MODULE)
533
534 if (input.newProducts) {
535 await algoliaModuleService.deleteFromIndex(
536 input.newProducts,
537 "product"
538 )
539 }
540
541 if (input.existingProducts) {
542 await algoliaModuleService.indexData(
543 input.existingProducts,
544 "product"
545 )
546 }
547 }
548 )
549 ```
550
551 The compensation function receives two parameters:
552
553 1. The data you passed as a second parameter of `StepResponse` in the step function.
554 2. A context object similar to the step function that holds the Medusa container.
555
556 In the compensation function, you resolve the Algolia Module's service from the container. Then, you delete from Algolia the products that were newly indexed, and revert the existing products to their original data.
557
558 #### deleteProductsFromAlgoliaStep
559
560 The `deleteProductsFromAlgoliaStep` step deletes products from Algolia by their IDs.
561
562 Create the step at `src/workflows/steps/delete-products-from-algolia.ts` with the following content:
563
564 ```ts title="src/workflows/steps/delete-products-from-algolia.ts"
565 import {
566 createStep,
567 StepResponse,
568 } from "@medusajs/framework/workflows-sdk"
569 import { ALGOLIA_MODULE } from "../../modules/algolia"
570
571 export type DeleteProductsFromAlgoliaWorkflow = {
572 ids: string[]
573 }
574
575 export const deleteProductsFromAlgoliaStep = createStep(
576 "delete-products-from-algolia-step",
577 async (
578 { ids }: DeleteProductsFromAlgoliaWorkflow,
579 { container }
580 ) => {
581 const algoliaModuleService = container.resolve(ALGOLIA_MODULE)
582
583 const existingRecords = await algoliaModuleService.retrieveFromIndex(
584 ids,
585 "product"
586 )
587 await algoliaModuleService.deleteFromIndex(
588 ids,
589 "product"
590 )
591
592 return new StepResponse(undefined, existingRecords)
593 },
594 async (existingRecords, { container }) => {
595 if (!existingRecords) {
596 return
597 }
598 const algoliaModuleService = container.resolve(ALGOLIA_MODULE)
599
600 await algoliaModuleService.indexData(
601 existingRecords as unknown as Record<string, unknown>[],
602 "product"
603 )
604 }
605 )
606 ```
607
608 The step receives the IDs of the products to delete as an input.
609
610 In the step, you resolve the Algolia Module's service and retrieve the existing records from Algolia. This is useful to revert the deletion if an error occurs.
611
612 Then, you delete the products from Algolia and pass the existing records to the compensation function.
613
614 In the compensation function, you reindex the existing records if an error occurs.
615
616 ### Add Sync Products Workflow
617
618 You can now create the workflow that syncs the products to Algolia.
619
620 To create the workflow, create the file `src/workflows/sync-products.ts` with the following content:
621
622 ```ts title="src/workflows/sync-products.ts"
623 import {
624 createWorkflow,
625 transform,
626 WorkflowResponse,
627 } from "@medusajs/framework/workflows-sdk"
628 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
629 import { syncProductsStep, SyncProductsStepInput } from "./steps/sync-products"
630 import { deleteProductsFromAlgoliaStep } from "./steps/delete-products-from-algolia"
631
632 type SyncProductsWorkflowInput = {
633 filters?: Record<string, unknown>
634 limit?: number
635 offset?: number
636 }
637
638 export const syncProductsWorkflow = createWorkflow(
639 "sync-products",
640 ({ filters, limit, offset }: SyncProductsWorkflowInput) => {
641 const { data: products, metadata } = useQueryGraphStep({
642 entity: "product",
643 fields: [
644 "id",
645 "title",
646 "description",
647 "handle",
648 "thumbnail",
649 "categories.id",
650 "categories.name",
651 "categories.handle",
652 "tags.id",
653 "tags.value",
654 "status",
655 ],
656 pagination: {
657 take: limit,
658 skip: offset,
659 },
660 filters,
661 })
662
663 const {
664 publishedProducts,
665 unpublishedProductsToDelete,
666 } = transform({
667 products,
668 }, (data) => {
669 const publishedProducts: SyncProductsStepInput["products"] = []
670 const unpublishedProductsToDelete: string[] = []
671
672 data.products.forEach((product) => {
673 if (product.status === "published") {
674 const { status, ...rest } = product
675 publishedProducts.push(rest as SyncProductsStepInput["products"][0])
676 } else {
677 unpublishedProductsToDelete.push(product.id)
678 }
679 })
680
681 return {
682 publishedProducts,
683 unpublishedProductsToDelete,
684 }
685 })
686
687 syncProductsStep({
688 products: publishedProducts,
689 })
690
691 deleteProductsFromAlgoliaStep({
692 ids: unpublishedProductsToDelete,
693 })
694
695 return new WorkflowResponse({
696 products,
697 metadata,
698 })
699 }
700 )
701 ```
702
703 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
704
705 It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case is pagination and filter parameters for the products to retrieve.
706
707 In the workflow's constructor function, you:
708
709 1. Execute `useQueryGraphStep` to retrieve products from Medusa's database. This step uses Medusa's [Query](!docs!/learn/fundamentals/query) tool to retrieve data across modules. You pass it the pagination and filter parameters you received in the input.
710 2. Use [transform](!docs!/learn/fundamentals/workflows/variable-manipulation) to prepare two lists: one for published products to index in Algolia and another for unpublished products to delete from Algolia.
711 2. Execute `syncProductsStep` to index the published products in Algolia.
712 3. Execute `deleteProductsFromAlgoliaStep` to delete unpublished products from Algolia.
713
714 A workflow must return an instance of `WorkflowResponse`. The `WorkflowResponse` constructor accepts the workflow's output as a parameter, which is an object holding the retrieved products and their pagination details.
715
716 In the next step, you'll learn how to execute this workflow.
717
718 ---
719
720 ## Step 4: Trigger Algolia Sync Manually
721
722 As mentioned earlier, you'll trigger the Algolia sync automatically when product events occur, but you also want to allow the admin to manually trigger a reindex.
723
724 In this step, you'll add the functionality to trigger the `syncProductsWorkflow` manually from the Medusa Admin dashboard. This requires:
725
726 1. Creating a subscriber that listens to a custom `algolia.sync` event to trigger syncing products to Algolia.
727 2. Creating an API route that the Medusa Admin dashboard can call to emit the `algolia.sync` event, which triggers the subscriber.
728 3. Add a new page or UI route to the Medusa Admin dashboard to allow the admin to trigger the reindex.
729
730 ### Create Products Sync Subscriber
731
732 A subscriber 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.
733
734 <Note>
735
736 Learn more about subscribers in the [Events and Subscribers documentation](!docs!/learn/fundamentals/events-and-subscribers).
737
738 </Note>
739
740 You create a subscriber in a TypeScript or JavaScript file under the `src/subscribers` directory. So, to create the subscriber that listens to the `algolia.sync` event, create the file `src/subscribers/algolia-sync.ts` with the following content:
741
742 ```ts title="src/subscribers/algolia-sync.ts"
743 import {
744 SubscriberArgs,
745 type SubscriberConfig,
746 } from "@medusajs/framework"
747 import { syncProductsWorkflow } from "../workflows/sync-products"
748 import {
749 ContainerRegistrationKeys,
750 } from "@medusajs/framework/utils"
751
752 export default async function algoliaSyncHandler({
753 container,
754 }: SubscriberArgs) {
755 const logger = container.resolve(
756 ContainerRegistrationKeys.LOGGER
757 )
758
759 let hasMore = true
760 let offset = 0
761 const limit = 50
762 let totalIndexed = 0
763
764 logger.info("Starting product indexing...")
765
766 while (hasMore) {
767 const { result: { products, metadata } } = await syncProductsWorkflow(container)
768 .run({
769 input: {
770 limit,
771 offset,
772 },
773 })
774
775 hasMore = offset + limit < (metadata?.count ?? 0)
776 offset += limit
777 totalIndexed += products.length
778 }
779
780 logger.info(`Successfully indexed ${totalIndexed} products`)
781 }
782
783 export const config: SubscriberConfig = {
784 event: "algolia.sync",
785 }
786 ```
787
788 A subscriber file must export:
789
790 1. An asynchronous function, which is the subscriber that is executed when the event is emitted.
791 2. A configuration object that holds the name of the event the subscriber listens to, which is `algolia.sync` in this case.
792
793 The subscriber function receives an object as a parameter that has a `container` property, which is the Medusa container.
794
795 In the subscriber function, you initialize variables to keep track of the pagination and the total number of products indexed.
796
797 Then, you start a loop that retrieves products in batches of 50 and indexes them in Algolia using the `syncProductsWorkflow`. Finally, you log the total number of products indexed.
798
799 You'll learn how to emit the `algolia.sync` event next.
800
801 <Note title="Tip">
802
803 If you want to sync other data types, you can do it in this subscriber as well.
804
805 </Note>
806
807 ### Create API Route to Trigger Sync
808
809 To allow the Medusa Admin dashboard to trigger the `algolia.sync` event, you need to create an API route that emits the event.
810
811 An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts.
812
813 <Note>
814
815 Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes).
816
817 </Note>
818
819 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`.
820
821 So, to create an API route at the path `/admin/algolia/sync`, create the file `src/api/admin/algolia/sync/route.ts` with the following content:
822
823 ```ts title="src/api/admin/algolia/sync/route.ts"
824 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
825 import { Modules } from "@medusajs/framework/utils"
826
827 export async function POST(
828 req: MedusaRequest,
829 res: MedusaResponse
830 ) {
831 const eventModuleService = req.scope.resolve(Modules.EVENT_BUS)
832 await eventModuleService.emit({
833 name: "algolia.sync",
834 data: {},
835 })
836 res.send({
837 message: "Syncing data to Algolia",
838 })
839 }
840 ```
841
842 Since you export a `POST` route handler function, you expose a `POST` API route at `/admin/algolia/sync`. The route handler function accepts two parameters:
843
844 1. A request object with details and context on the request, such as body parameters or authenticated user details.
845 2. A response object to manipulate and send the response.
846
847 In the route handler, you use the Medusa container that is available in the request object to resolve the [Event Module](../../../infrastructure-modules/event/page.mdx). This module manages events and their subscribers.
848
849 Then, you emit the `algolia.sync` event using the Event Module's `emit` method, passing it the event name.
850
851 Finally, you send a response with a message indicating that data is being synced to Algolia.
852
853 ### Add Algolia Sync Page to Admin Dashboard
854
855 The last step is to add a new page to the admin dashboard that allows the admin to trigger the reindex. You add a new page using a [UI Route](!docs!/learn/fundamentals/admin/ui-routes).
856
857 A UI route is a React component that specifies the content to be shown in a new page in the Medusa Admin dashboard. You'll create a UI route to display a button that triggers the reindex when clicked.
858
859 <Note>
860
861 Learn more about UI routes in the [UI Routes documentation](!docs!/learn/fundamentals/admin/ui-routes).
862
863 </Note>
864
865 #### Configure JS SDK
866
867 Before creating the UI route, you'll configure Medusa's [JS SDK](../../../js-sdk/page.mdx) that you can use to send requests to the Medusa server from any client application, including your Medusa Admin customizations.
868
869 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:
870
871 ```ts title="src/admin/lib/sdk.ts"
872 import Medusa from "@medusajs/js-sdk"
873
874 export const sdk = new Medusa({
875 baseUrl: "http://localhost:9000",
876 debug: import.meta.env.NODE_ENV === "development",
877 auth: {
878 type: "session",
879 },
880 })
881 ```
882
883 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:
884
885 - `baseUrl`: The base URL of the Medusa server.
886 - `debug`: A boolean indicating whether to log debug information into the console.
887 - `auth`: An object specifying the authentication type. When using the JS SDK for admin customizations, you use the `session` authentication type.
888
889 #### Create UI Route
890
891 You'll now create the UI route that displays a button to trigger the reindex. You create a UI route 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.
892
893 So, to create a new page under the Settings section of the Medusa Admin, create the file `src/admin/routes/settings/algolia/page.tsx` with the following content:
894
895 ```tsx title="src/admin/routes/settings/algolia/page.tsx"
896 import { Container, Heading, Button, toast } from "@medusajs/ui"
897 import { useMutation } from "@tanstack/react-query"
898 import { sdk } from "../../../lib/sdk"
899 import { defineRouteConfig } from "@medusajs/admin-sdk"
900
901 const AlgoliaPage = () => {
902 const { mutate, isPending } = useMutation({
903 mutationFn: () =>
904 sdk.client.fetch("/admin/algolia/sync", {
905 method: "POST",
906 }),
907 onSuccess: () => {
908 toast.success("Successfully triggered data sync to Algolia")
909 },
910 onError: (err) => {
911 console.error(err)
912 toast.error("Failed to sync data to Algolia")
913 },
914 })
915
916 const handleSync = () => {
917 mutate()
918 }
919
920 return (
921 <Container className="divide-y p-0">
922 <div className="flex items-center justify-between px-6 py-4">
923 <Heading level="h2">Algolia Sync</Heading>
924 </div>
925 <div className="px-6 py-8">
926 <Button
927 variant="primary"
928 onClick={handleSync}
929 isLoading={isPending}
930 >
931 Sync Data to Algolia
932 </Button>
933 </div>
934 </Container>
935 )
936 }
937
938 export const config = defineRouteConfig({
939 label: "Algolia",
940 })
941
942 export default AlgoliaPage
943 ```
944
945 A UI route's file must export:
946
947 1. A React component that defines the content of the page.
948 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.
949
950 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.
951
952 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.
953
954 ### Test it Out
955
956 You'll now test out the entire flow, starting from triggering the reindex manually from the Medusa Admin dashboard, to checking the Algolia dashboard for the indexed products.
957
958 Run the following command to start the Medusa application:
959
960 ```bash npm2yarn
961 npm run dev
962 ```
963
964 Then, open the Medusa Admin at `http://localhost:9000/app` and log in with the credentials you set up in the first step.
965
966 <Note>
967
968 Can't remember the credentials? Learn how to create a user in the [Medusa CLI reference](../../../medusa-cli/commands/user/page.mdx).
969
970 </Note>
971
972 After you log in, go to Settings from the sidebar. You'll find in the Settings' sidebar a new "Algolia" item. If you click on it, you'll find the page you created with the button to sync products to Algolia.
973
974 If you click on the button, the products will be synced to Algolia.
975
976 ![The Algolia Sync page in the Medusa Admin dashboard with a button to sync products to Algolia](https://res.cloudinary.com/dza7lstvk/image/upload/v1742820813/Medusa%20Resources/Screenshot_2025-03-24_at_2.52.31_PM_eiegzb.png)
977
978 You can check that the sync ran and was completed by checking the Medusa logs in the terminal where you started the Medusa application. You should find the following messages:
979
980 ```bash
981 info: Processing algolia.sync which has 1 subscribers
982 info: Starting product indexing...
983 info: Successfully indexed 4 products
984 ```
985
986 These messages indicate that the `algolia.sync` event was emitted, which triggered the subscriber you created to sync the products using the `syncProductsWorkflow`.
987
988 Finally, you can check the Algolia dashboard to see the indexed products. Go to Search -> Index, and check the records of the index you set up in the Algolia Module's options (`products`, for example).
989
990 ![The Algolia dashboard showing the indexed products](https://res.cloudinary.com/dza7lstvk/image/upload/v1742821034/Medusa%20Resources/Screenshot_2025-03-24_at_2.56.38_PM_mtojrv.png)
991
992 ---
993
994 ## Step 5: Update Index on Product Changes
995
996 You'll now automate the indexing of the products whenever a change occurs. That includes when a product is created, updated, or deleted.
997
998 Similar to before, you'll create subscribers to listen to these events.
999
1000 ### Handle Create and Update Products
1001
1002 The action to perform when a product is created or updated is the same. You'll use the `syncProductsWorkflow` to sync the product to Algolia.
1003
1004 So, you only need one subscriber to handle these two events. To create the subscriber, create the file `src/subscribers/product-sync.ts` with the following content:
1005
1006 ```ts title="src/subscribers/product-sync.ts"
1007 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1008 import { syncProductsWorkflow } from "../workflows/sync-products"
1009
1010 export default async function handleProductEvents({
1011 event: { data },
1012 container,
1013 }: SubscriberArgs<{ id: string }>) {
1014 await syncProductsWorkflow(container)
1015 .run({
1016 input: {
1017 filters: {
1018 id: data.id,
1019 },
1020 },
1021 })
1022 }
1023
1024 export const config: SubscriberConfig = {
1025 event: ["product.created", "product.updated"],
1026 }
1027 ```
1028
1029 The subscriber listens to the `product.created` and `product.updated` events. When either of these events is emitted, the subscriber triggers the `syncProductsWorkflow` to sync the product to Algolia.
1030
1031 When the `product.created` and `product.updated` events are emitted, the product's ID is passed in the event data payload, which you can access in the `event.data` property of the subscriber function's parameter.
1032
1033 So, you pass the product's ID to the `syncProductsWorkflow` as a filter to retrieve only the product that was created or updated.
1034
1035 #### Test it Out
1036
1037 To test it out, start the Medusa application:
1038
1039 ```bash npm2yarn
1040 npm run dev
1041 ```
1042
1043 Then, either create a product or update an existing one using the Medusa Admin dashboard. If you check the Algolia dashboard, you'll find that the product was created or updated.
1044
1045 ### Handle Product Deletion
1046
1047 When a product is deleted, you need to remove it from the Algolia index. As this requires a different action than creating or updating a product, you'll create a new workflow that deletes the product from Algolia, then create a subscriber that listens to the `product.deleted` event to trigger the workflow.
1048
1049 #### Create Delete Product Workflow
1050
1051 You've already created the `deleteProductsFromAlgoliaStep` that deletes products from Algolia by their IDs. So, you can create the workflow that uses this step.
1052
1053 Create the file `src/workflows/delete-products-from-algolia.ts` with the following content:
1054
1055 ```ts title="src/workflows/delete-products-from-algolia.ts"
1056 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
1057 import { deleteProductsFromAlgoliaStep } from "./steps/delete-products-from-algolia"
1058
1059 type DeleteProductsFromAlgoliaWorkflowInput = {
1060 ids: string[]
1061 }
1062
1063 export const deleteProductsFromAlgoliaWorkflow = createWorkflow(
1064 "delete-products-from-algolia",
1065 (input: DeleteProductsFromAlgoliaWorkflowInput) => {
1066 deleteProductsFromAlgoliaStep(input)
1067 }
1068 )
1069 ```
1070
1071 The workflow receives an object with the IDs of the products to delete. It then executes the `deleteProductsFromAlgoliaStep` to delete the products from Algolia.
1072
1073 #### Create Delete Product Subscriber
1074
1075 Finally, you'll create the subscriber that listens to the `product.deleted` event to trigger the above workflow.
1076
1077 Create the file `src/subscribers/product-delete.ts` with the following content:
1078
1079 ```ts title="src/subscribers/product-delete.ts"
1080 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1081 import { deleteProductsFromAlgoliaWorkflow } from "../workflows/delete-products-from-algolia"
1082
1083 export default async function handleProductDeleted({
1084 event: { data },
1085 container,
1086 }: SubscriberArgs<{ id: string }>) {
1087 await deleteProductsFromAlgoliaWorkflow(container)
1088 .run({
1089 input: {
1090 ids: [data.id],
1091 },
1092 })
1093 }
1094
1095 export const config: SubscriberConfig = {
1096 event: "product.deleted",
1097 }
1098 ```
1099
1100 The subscriber listens to the `product.deleted` event. When the event is emitted, the subscriber triggers the `deleteProductsFromAlgoliaWorkflow`, passing it the ID of the product to delete.
1101
1102 #### Test it Out
1103
1104 To test product deletion, start the Medusa application:
1105
1106 ```bash npm2yarn
1107 npm run dev
1108 ```
1109
1110 Then, delete a product from the Medusa Admin dashboard. If you check the Algolia dashboard, you'll find that the product was deleted there as well.
1111
1112 ---
1113
1114 ## Step 6: Add Search API Route
1115
1116 Before customizing the storefront to show the search UI, you'll create an API route in your Medusa application that allows storefronts to search products in Algolia.
1117
1118 <Note title="Tip">
1119
1120 While you can implement the search functionality directly in the storefront to interact with Algolia, this approach centralizes your search integration in Medusa, allowing you to change or modify the integration as necessary. You can also rely on the same behavior and results across different storefronts.
1121
1122 </Note>
1123
1124 To implement the API Route, create the file `src/api/store/products/search/route.ts` with the following content:
1125
1126 <Note>
1127
1128 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
1129
1130 </Note>
1131
1132 ```ts title="src/api/store/products/search/route.ts"
1133 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
1134 import { ALGOLIA_MODULE } from "../../../../modules/algolia"
1135 import AlgoliaModuleService from "../../../../modules/algolia/service"
1136 import { z } from "@medusajs/framework/zod"
1137
1138 export const SearchSchema = z.object({
1139 query: z.string(),
1140 })
1141
1142 type SearchRequest = z.infer<typeof SearchSchema>
1143
1144 export async function POST(
1145 req: MedusaRequest<SearchRequest>,
1146 res: MedusaResponse
1147 ) {
1148 const algoliaModuleService: AlgoliaModuleService = req.scope.resolve(ALGOLIA_MODULE)
1149
1150 const { query } = req.validatedBody
1151
1152 const results = await algoliaModuleService.search(
1153 query as string
1154 )
1155
1156 res.json(results)
1157 }
1158 ```
1159
1160 You first define a schema with [Zod](https://zod.dev/), a library to define validation schemas. The schema defines the structure of the request body, which in this case is an object with a `query` property of type `string`. Later, you'll use the schema to enforce request body validation.
1161
1162 Then, you expose a `POST` API Route at `/store/search` that searches Algolia using the `search` method you implemented in the Algolia Module's service. You pass to it the query string from the request body.
1163
1164 Finally, you return the search results as it is in the response.
1165
1166 ### Add Validation Middleware
1167
1168 To ensure that requests sent to the API route have the required request body parameters, you can use a [middleware](!docs!/learn/fundamentals/api-routes/middlewares). A middleware is a function executed when a request is sent to an API Route. It's executed before the route handler.
1169
1170 <Note>
1171
1172 Learn more about middleware in the [Middlewares documentation](!docs!/learn/fundamentals/api-routes/middlewares).
1173
1174 </Note>
1175
1176 Middlewares are created in the `src/api/middlewares.ts` file. So create the file `src/api/middlewares.ts` with the following content:
1177
1178 ```ts title="src/api/middlewares.ts"
1179 import {
1180 defineMiddlewares,
1181 validateAndTransformBody,
1182 } from "@medusajs/framework/http"
1183 import { SearchSchema } from "./store/products/search/route"
1184
1185 export default defineMiddlewares({
1186 routes: [
1187 {
1188 matcher: "/store/products/search",
1189 method: ["POST"],
1190 middlewares: [
1191 validateAndTransformBody(SearchSchema),
1192 ],
1193 },
1194 ],
1195 })
1196 ```
1197
1198 To export the middlewares, you use the `defineMiddlewares` function. It accepts an object having a `routes` property, whose value is an array of middleware route objects. Each middleware route object has the following properties:
1199
1200 - `matcher`: The path of the route the middleware applies to.
1201 - `method`: The HTTP methods the middleware applies to, which is in this case `POST`.
1202 - `middlewares`: An array of middleware functions to apply to the route. You apply the `validateAndTransformBody` middleware which ensures that a request's body has the required parameters. You pass it the schema you defined earlier in the API route's file.
1203
1204 You can use the search API route now. You'll see it in action as you customize the storefront in the next step.
1205
1206 ---
1207
1208 ## Step 7: Search Products in Next.js Starter Storefront
1209
1210 The last step is to provide the search functionalities to customers on your storefront. In the first step, you installed the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) along with the Medusa application.
1211
1212 In this step, you'll customize the Next.js Starter Storefront to add the search functionality.
1213
1214 <Note title="Reminder" forceMultiline>
1215
1216 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
1217
1218 ```bash
1219 cd apps/storefront
1220 ```
1221
1222 </Note>
1223
1224 ### Install Algolia Packages
1225
1226 Before adding the implementation of the search functionality, you need to install the Algolia packages necessary to add the search functionality in your storefront.
1227
1228 Run the following command in the directory of your Next.js Starter Storefront:
1229
1230 ```bash npm2yarn
1231 npm install algoliasearch react-instantsearch
1232 ```
1233
1234 This installs the Algolia Search JavaScript client and the React InstantSearch library, which you'll use to build the search functionality.
1235
1236 ### Add Search Client Configuration
1237
1238 Next, you need to configure the search client. Not only do you need to initialize Algolia, but you also need to change the searching mechanism to use your custom API route in the Medusa application instead of Algolia's API directly.
1239
1240 In `src/lib/config.ts`, add the following imports at the top of the file:
1241
1242 ```ts title="src/lib/config.ts" badgeLabel="Storefront" badgeColor="blue"
1243 import {
1244 liteClient as algoliasearch,
1245 LiteClient as SearchClient,
1246 } from "algoliasearch/lite"
1247 ```
1248
1249 Then, add the following at the end of the file:
1250
1251 ```ts title="src/lib/config.ts" badgeLabel="Storefront" badgeColor="blue"
1252 export const searchClient: SearchClient = {
1253 ...(algoliasearch(
1254 process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || "",
1255 process.env.NEXT_PUBLIC_ALGOLIA_API_KEY || ""
1256 )),
1257 search: async (params) => {
1258 const request = Array.isArray(params) ? params[0] : params
1259 const query = "params" in request ? request.params?.query :
1260 "query" in request ? request.query : ""
1261
1262 if (!query) {
1263 return {
1264 results: [
1265 {
1266 hits: [],
1267 nbHits: 0,
1268 nbPages: 0,
1269 page: 0,
1270 hitsPerPage: 0,
1271 processingTimeMS: 0,
1272 query: "",
1273 params: "",
1274 },
1275 ],
1276 }
1277 }
1278
1279 return await sdk.client.fetch(`/store/products/search`, {
1280 method: "POST",
1281 body: {
1282 query,
1283 },
1284 })
1285 },
1286 }
1287 ```
1288
1289 In the code above, you create a `searchClient` object that initializes the Algolia client with your Algolia App ID and API Key.
1290
1291 You also define a `search` method that sends a `POST` request to the search API route you created in the Medusa application. You use the JS SDK (which is initialized in this same file) to send the request.
1292
1293 ### Set Environment Variables
1294
1295 In the storefront's `.env.local` file, add the following Algolia-related environment variables:
1296
1297 ```plain badgeLabel="Storefront" badgeColor="blue"
1298 NEXT_PUBLIC_ALGOLIA_APP_ID=your_algolia_app_id
1299 NEXT_PUBLIC_ALGOLIA_API_KEY=your_algolia_api_key
1300 NEXT_PUBLIC_ALGOLIA_PRODUCT_INDEX_NAME=your-products-index-name
1301 ```
1302
1303 Where:
1304
1305 - `your_algolia_app_id` is your Algolia App ID, as explained in the [Add Environment Variables section](#add-environment-variables) earlier.
1306 - `your_algolia_api_key` is your Algolia Search API key. You can retrieve it from the [same API keys page on the Algolia dashboard](#add-environment-variables) that you retrieved the Admin API key from.
1307 - `your-products-index-name` is the name of the index you created in Algolia to store the products, which you can retrieve as explained in the [Add Environment Variables section](#add-environment-variables) earlier. You'll use this variable later.
1308
1309 <Note type="warning">
1310
1311 Do not expose your Admin API key in the storefront. The Admin API key should only be used in the Medusa application to interact with Algolia, as it has full access to your Algolia account.
1312
1313 </Note>
1314
1315 ### Add Search Modal Component
1316
1317 You'll now add a search modal component that customers can use to search for products. The search modal will display the search results in real-time as the customer types in the search query.
1318
1319 Later, you'll add the search modal to the navigation bar, allowing customers to open the search modal from any page.
1320
1321 Create the file `src/modules/search/components/modal/index.tsx` with the following content:
1322
1323 ```tsx title="src/modules/search/components/modal/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1324 "use client"
1325
1326 import React, { useEffect, useState } from "react"
1327 import { Hits, InstantSearch, SearchBox } from "react-instantsearch"
1328 import { searchClient } from "../../../../lib/config"
1329 import Modal from "../../../common/components/modal"
1330 import { Button } from "@medusajs/ui"
1331 import Image from "next/image"
1332 import Link from "next/link"
1333 import { usePathname } from "next/navigation"
1334
1335 type Hit = {
1336 objectID: string;
1337 id: string;
1338 title: string;
1339 description: string;
1340 handle: string;
1341 thumbnail: string;
1342 }
1343
1344 export default function SearchModal() {
1345 const [isOpen, setIsOpen] = useState(false)
1346 const pathname = usePathname()
1347
1348 useEffect(() => {
1349 setIsOpen(false)
1350 }, [pathname])
1351
1352 return (
1353 <>
1354 <div className="hidden small:flex items-center gap-x-6 h-full">
1355 <Button
1356 onClick={() => setIsOpen(true)}
1357 variant="transparent"
1358 className="hover:text-ui-fg-base text-small-regular px-0 hover:bg-transparent focus:!bg-transparent"
1359 >
1360 Search
1361 </Button>
1362 </div>
1363 <Modal isOpen={isOpen} close={() => setIsOpen(false)}>
1364 <InstantSearch
1365 searchClient={searchClient}
1366 indexName={process.env.NEXT_PUBLIC_ALGOLIA_PRODUCT_INDEX_NAME}
1367 >
1368 <SearchBox className="w-full [&_input]:w-[94%] [&_input]:outline-none [&_button]:w-[3%]" />
1369 <Hits hitComponent={Hit} />
1370 </InstantSearch>
1371 </Modal>
1372 </>
1373 )
1374 }
1375
1376 const Hit = ({ hit }: { hit: Hit }) => {
1377 return (
1378 <div className="flex flex-row gap-x-2 mt-4 relative">
1379 <Image src={hit.thumbnail} alt={hit.title} width={100} height={100} />
1380 <div className="flex flex-col gap-y-1">
1381 <h3>{hit.title}</h3>
1382 <p className="text-sm text-gray-500">{hit.description}</p>
1383 </div>
1384 <Link href={`/products/${hit.handle}`} className="absolute right-0 top-0 w-full h-full" aria-label={`View Product: ${hit.title}`} />
1385 </div>
1386 )
1387 }
1388 ```
1389
1390 You create a `SearchModal` component that displays a search box and the search results using widgets from Algolia's `react-instantsearch` library.
1391
1392 To display each result item (or hit), you create a `Hit` component that displays the product's title, description, and thumbnail. You also add a link to the product's page.
1393
1394 Finally, you show the search modal when the customer clicks a "Search" button, which you'll add to the navigation bar next.
1395
1396 ### Add Search Button to Navigation Bar
1397
1398 The last step is to show the search button in the navigation bar.
1399
1400 In `src/modules/layout/templates/nav/index.tsx`, add the following imports at the top of the file:
1401
1402 ```tsx title="src/modules/layout/templates/nav/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1403 import SearchModal from "@modules/search/components/modal"
1404 ```
1405
1406 Then, in the return statement of the `Nav` component, add the `SearchModal` component before the `div` surrounding the "Account" link:
1407
1408 ```tsx title="src/modules/layout/templates/nav/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1409 <SearchModal />
1410 ```
1411
1412 The search button will now appear in the navigation bar before the Account link.
1413
1414 ### Test it Out
1415
1416 To test out the storefront changes and the search API route, start the Medusa application:
1417
1418 ```bash npm2yarn
1419 npm run dev
1420 ```
1421
1422 Then, start the Next.js Starter Storefront from its directory:
1423
1424 ```bash npm2yarn
1425 npm run dev
1426 ```
1427
1428 Next, go to `localhost:8000`. You'll find a Search button at the top right of the navigation bar. If you click on it, you can search through your products. You can also click on a product to view its page.
1429
1430 ![The Next.js Starter Storefront showing the search modal with search results](https://res.cloudinary.com/dza7lstvk/image/upload/v1742827777/Medusa%20Resources/Screenshot_2025-03-24_at_4.49.23_PM_kzhldx.png)
1431
1432 ---
1433
1434 ## Next Steps
1435
1436 You've now integrated Algolia with Medusa and added search functionality to your storefront. You can expand on these features to:
1437
1438 - Add filters to the search results. You can do that using Algolia's [widgets](https://www.algolia.com/doc/guides/building-search-ui/widgets/showcase/react/) and customizing the search API route in Medusa to accept filter parameters.
1439 - Support indexing other data types, such as product categories. You can create the subscribers and workflows for categories similar to products.
1440
1441 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.
1442
1443 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).