Integrate Algolia (Search) with Medusa
In this tutorial, you'll learn how to integrate Medusa with Algolia.
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.
Algolia 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.
You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
Summary#
By following this tutorial, you'll learn how to:
- Install and set up Medusa.
- Integrate Algolia into Medusa.
- Trigger Algolia reindexing when a product is created, updated, deleted, or when the admin manually triggers a reindex.
- Customize the Next.js Starter Storefront to allow searching for products through Algolia.
Step 1: Install a Medusa Application#
Start by installing the Medusa application on your machine with the following command:
You'll first be asked for the project's name. Then, when asked whether you want to install the Next.js starter storefront, choose "Yes."
Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name and the Next.js Starter Storefront in a separate directory named {project-name}-storefront
.
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.
Step 2: Create Algolia Module#
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.
In this step, you'll create a custom module that provides the necessary functionalities to integrate Algolia with Medusa.
Before building the module, you need to install Algolia's JavaScript client. Run the following command in your Medusa application's root directory:
Create Module Directory#
A module is created under the src/modules
directory of your Medusa application. So, create the directory src/modules/algolia
.
Create Service#
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.
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.
To create the Algolia Module's service, create the file src/modules/algolia/service.ts
with the following content:
1import { algoliasearch, SearchClient } from "algoliasearch"2 3type AlgoliaOptions = {4 apiKey: string;5 appId: string;6 productIndexName: string;7}8 9export type AlgoliaIndexType = "product"10 11export default class AlgoliaModuleService {12 private client: SearchClient13 private options: AlgoliaOptions14 15 constructor({}, options: AlgoliaOptions) {16 this.client = algoliasearch(options.appId, options.apiKey)17 this.options = options18 }19 20 // TODO add methods21}
You export a class that will be the Algolia Module's main service. In the service, you define two properties:
client
: An instance of the Algolia Search Client, which you'll use to perform actions with Algolia's API.options
: An object of options that the Module receives when it's registered, which you'll learn about later. The options contain:apiKey
: The Algolia API key.appId
: The Algolia App ID.productIndexName
: The name of the index where products are stored.
AlgoliaOptions
type.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.
Index Data Method
The first method you need to add to the servie is a method that receives an array of data to add or update in Algolia's index.
Add the following methods to the AlgoliaModuleService
class:
1export default class AlgoliaModuleService {2 // ...3 async getIndexName(type: AlgoliaIndexType) {4 switch (type) {5 case "product":6 return this.options.productIndexName7 default:8 throw new Error(`Invalid index type: ${type}`)9 }10 }11 12 async indexData(data: Record<string, unknown>[], type: AlgoliaIndexType = "product") {13 const indexName = await this.getIndexName(type)14 this.client.saveObjects({15 indexName,16 objects: data.map((item) => ({17 ...item,18 // set the object ID to allow updating later19 objectID: item.id,20 })),21 })22 }23}
You define two methods:
getIndexName
: A method that receives anAlgoliaIndexType
(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.- If you want to index other types of data, you can add more cases to the switch statement.
indexData
: A method that receives an array of data and anAlgoliaIndexType
. The method indexes the data in the Algolia index for the given type.- Notice that you set the
objectID
property of each object to the object'sid
. This ensures that you later update the object instead of creating a new one.
- Notice that you set the
Retrieve and Delete Methods
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.
Add the following methods to the AlgoliaModuleService
class:
1export default class AlgoliaModuleService {2 // ...3 4 async retrieveFromIndex(objectIDs: string[], type: AlgoliaIndexType = "product") {5 const indexName = await this.getIndexName(type)6 return await this.client.getObjects<Record<string, unknown>>({7 requests: objectIDs.map((objectID) => ({8 indexName,9 objectID,10 })),11 })12 }13 14 async deleteFromIndex(objectIDs: string[], type: AlgoliaIndexType = "product") {15 const indexName = await this.getIndexName(type)16 await this.client.deleteObjects({17 indexName,18 objectIDs,19 })20 }21}
You define two methods:
retrieveFromIndex
: A method that receives an array of object IDs and anAlgoliaIndexType
. The method retrieves the objects with the given IDs from the Algolia index.deleteFromIndex
: A method that receives an array of object IDs and anAlgoliaIndexType
. The method deletes the objects with the given IDs from the Algolia index.
Search Method
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 Storefront.
Add the following method to the AlgoliaModuleService
class:
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.
Export Module Definition#
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.
So, create the file src/modules/algolia/index.ts
with the following content:
You use the Module
function from the Modules SDK to create the module's definition. It accepts two parameters:
- The module's name, which is
algolia
. - An object with a required property
service
indicating the module's service.
You also export the module's name as ALGOLIA_MODULE
so you can reference it later.
Add Module to Medusa's Configurations#
Once you finish building the module, add it to Medusa's configurations to start using it.
In medusa-config.ts
, add a modules
property and pass an array with your custom module:
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.
You also pass an options
property with the module's options, including the Algolia App ID, API Key, and the product index name.
Add Environment Variables#
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.
Add the following environment variables to your .env
file:
Where:
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.
your-algolia-api-key
is your Algolia API Key. To retrieve it from the Algolia dashboard:- Click on Settings in the sidebar.
- Choose API Keys under "Team and Access".
- Copy the Admin API Key.
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.
Your module is now ready for use. You'll see how to use it in the next steps.
Step 3: Sync Products to Algolia Workflow#
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.
To implement the indexing functionality, you need to create a workflow. 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.
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.
The workflow has the following steps:
View step details
Medusa provides the useQueryGraphStep
in its @medusajs/medusa/core-flows
package. So, you only need to implement the second step.
syncProductsStep#
In the second step of the workflow, you create or update indexes in Algolia for the products retrieved in the first step.
To create the step, create the file src/workflows/steps/sync-products.ts
with the following content:
1import { ProductDTO } from "@medusajs/framework/types"2import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"3import { ALGOLIA_MODULE } from "../../modules/algolia"4import AlgoliaModuleService from "../../modules/algolia/service"5 6export type SyncProductsStepInput = {7 products: ProductDTO[]8}9 10export const syncProductsStep = createStep(11 "sync-products",12 async ({ products }: SyncProductsStepInput, { container }) => {13 const algoliaModuleService: AlgoliaModuleService = container.resolve(ALGOLIA_MODULE)14 15 const existingProducts = (await algoliaModuleService.retrieveFromIndex(16 products.map((product) => product.id),17 "product"18 )).results.filter(Boolean)19 const newProducts = products.filter(20 (product) => !existingProducts.some((p) => p.objectID === product.id)21 )22 await algoliaModuleService.indexData(23 products as unknown as Record<string, unknown>[], 24 "product"25 )26 27 return new StepResponse(undefined, {28 newProducts: newProducts.map((product) => product.id),29 existingProducts,30 })31 }32 // TODO add compensation33)
You create a step with createStep
from the Workflows SDK. It accepts two parameters:
- The step's unique name, which is
sync-products
. - An async function that receives two parameters:
- The step's input, which is in this case an object holding an array of products to sync into Algolia.
- An object that has properties including the Medusa container, which is a registry of framework and commerce tools that you can access in the step.
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.
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.
Finally, you pass the products you received in the input to Algolia to create or update its indices.
A step function must return a StepResponse
instance. The StepResponse
constructor accepts two parameters:
- The step's output, which is the review created.
- Data to pass to the step's compensation function.
Compensation Function
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.
To add a compensation function to a step, pass it as a third parameter to createStep
:
1export const syncProductsStep = createStep(2 // ...3 async (input, { container }) => {4 if (!input) {5 return6 }7 8 const algoliaModuleService: AlgoliaModuleService = container.resolve(ALGOLIA_MODULE)9 10 if (input.newProducts) {11 await algoliaModuleService.deleteFromIndex(12 input.newProducts,13 "product"14 )15 }16 17 if (input.existingProducts) {18 await algoliaModuleService.indexData(19 input.existingProducts,20 "product"21 )22 }23 }24)
The compensation function receives two parameters:
- The data you passed as a second parameter of
StepResponse
in the step function. - A context object similar to the step function that holds the Medusa container.
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.
Add Sync Products Workflow#
You can now create the worklow that syncs the products to Algolia.
To create the workflow, create the file src/workflows/sync-products.ts
with the following content:
1import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"2import { useQueryGraphStep } from "@medusajs/medusa/core-flows"3import { syncProductsStep, SyncProductsStepInput } from "./steps/sync-products"4 5type SyncProductsWorkflowInput = {6 filters?: Record<string, unknown>7 limit?: number8 offset?: number9}10 11export const syncProductsWorkflow = createWorkflow(12 "sync-products",13 ({ filters, limit, offset }: SyncProductsWorkflowInput) => {14 // @ts-ignore15 const { data, metadata } = useQueryGraphStep({16 entity: "product",17 fields: ["id", "title", "description", "handle", "thumbnail", "categories.*", "tags.*"],18 pagination: {19 take: limit,20 skip: offset,21 },22 filters: {23 // @ts-ignore24 status: "published",25 ...filters,26 },27 })28 29 syncProductsStep({30 products: data,31 } as SyncProductsStepInput)32 33 return new WorkflowResponse({34 products: data,35 metadata,36 })37 }38)
You create a workflow using createWorkflow
from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
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.
In the workflow's constructor function, you:
- Execute
useQueryGraphStep
to retrieve products from Medusa's database. This step uses Medusa's Query tool to retrieve data across modules. You pass it the pagination and filter parameters you received in the input. - Execute
syncProductsStep
to index the products in Algolia. You pass it the products you retrieved in the previous step.
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.
In the next step, you'll learn how to execute this workflow.
Step 4: Trigger Algolia Sync Manually#
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.
In this step, you'll add the functionality to trigger the syncProductsWorkflow
manually from the Medusa Admin dashboard. This requires:
- Creating a subscriber that listens to a custom
algolia.sync
event to trigger syncing products to Algolia. - Creating an API route that the Medusa Admin dashboard can call to emit the
algolia.sync
event, which triggers the subscriber. - Add a new page or UI route to the Medusa Admin dashboard to allow the admin to trigger the reindex.
Create Products Sync Subscriber#
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.
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/products-sync.ts
with the following content:
1import {2 SubscriberArgs,3 type SubscriberConfig,4} from "@medusajs/framework"5import { syncProductsWorkflow } from "../workflows/sync-products"6 7export default async function algoliaSyncHandler({ 8 container,9}: SubscriberArgs) {10 const logger = container.resolve("logger")11 12 let hasMore = true13 let offset = 014 const limit = 5015 let totalIndexed = 016 17 logger.info("Starting product indexing...")18 19 while (hasMore) {20 const { result: { products, metadata } } = await syncProductsWorkflow(container)21 .run({22 input: {23 limit,24 offset,25 },26 })27 28 hasMore = offset + limit < (metadata?.count ?? 0)29 offset += limit30 totalIndexed += products.length31 }32 33 logger.info(`Successfully indexed ${totalIndexed} products`)34}35 36export const config: SubscriberConfig = {37 event: "algolia.sync",38}
A subscriber file must export:
- An asynchronous function, which is the subscriber that is executed when the event is emitted.
- A configuration object that holds the name of the event the subscriber listens to, which is
algolia.sync
in this case.
The subscriber function receives an object as a parameter that has a container
property, which is the Medusa container.
In the subscriber function, you initialize variables to keep track of the pagination and the total number of products indexed.
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.
You'll learn how to emit the algolia.sync
event next.
Create API Route to Trigger Sync#
To allow the Medusa Admin dashboard to trigger the algolia.sync
event, you need to create an API route that emits the event.
An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts.
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
.
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:
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2import { Modules } from "@medusajs/framework/utils"3 4export async function POST(5 req: MedusaRequest,6 res: MedusaResponse7) {8 const eventModuleService = req.scope.resolve(Modules.EVENT_BUS)9 await eventModuleService.emit({10 name: "algolia.sync",11 data: {},12 })13 res.send({14 message: "Syncing data to Algolia",15 })16}
Since you export a POST
route handler function, you expose an API
route at /admin/algolia/sync
. The route handler function accepts two parameters:
- A request object with details and context on the request, such as body parameters or authenticated user details.
- A response object to manipulate and send the response.
In the route handler, you use the Medusa container that is available in the request object to resolve the Event Module. This module manages events and their subscribers.
Then, you emit the algolia.sync
event using the Event Module's emit
method, passing it the event name.
Finally, you send a response with a message indicating that data is being synced to Algolia.
Add Algolia Sync Page to Admin Dashboard#
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.
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.
Configure JS SDK
Before creating the UI route, you'll configure Medusa's JS SDK that you can use to send requests to the Medusa server from any client application, including your Medusa Admin customizations.
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:
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:
baseUrl
: The base URL of the Medusa server.debug
: A boolean indicating whether to log debug information into the console.auth
: An object specifying the authentication type. When using the JS SDK for admin customizations, you use thesession
authentication type.
Create UI Route
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.
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:
1import { Container, Heading, Button, toast } from "@medusajs/ui"2import { useMutation } from "@tanstack/react-query"3import { sdk } from "../../../lib/sdk"4import { defineRouteConfig } from "@medusajs/admin-sdk"5 6const AlgoliaPage = () => {7 const { mutate, isPending } = useMutation({8 mutationFn: () => 9 sdk.client.fetch("/admin/algolia/sync", {10 method: "POST",11 }),12 onSuccess: () => {13 toast.success("Successfully triggered data sync to Algolia") 14 },15 onError: (err) => {16 console.error(err)17 toast.error("Failed to sync data to Algolia") 18 },19 })20 21 const handleSync = () => {22 mutate()23 }24 25 return (26 <Container className="divide-y p-0">27 <div className="flex items-center justify-between px-6 py-4">28 <Heading level="h2">Algolia Sync</Heading>29 </div>30 <div className="px-6 py-8">31 <Button 32 variant="primary"33 onClick={handleSync}34 isLoading={isPending}35 >36 Sync Data to Algolia37 </Button>38 </div>39 </Container>40 )41}42 43export const config = defineRouteConfig({44 label: "Algolia",45})46 47export default AlgoliaPage
A UI route's file must export:
- A React component that defines the content of the page.
- 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.
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.
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.
Test it Out#
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.
Run the following command to start the Medusa application:
Then, open the Medusa Admin at http://localhost:9000/app
and log in with the credentials you set up in the first step.
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.
If you click on the button, the products will be synced to Algolia.
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:
These messages indicate that the algolia.sync
event was emitted, which triggered the subscriber you created to sync the products using the syncProductsWorkflow
.
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).
Step 5: Update Index on Product Changes#
You'll now automate the indexing of the products whenever a change occurs. That includes when a product is created, updated, or deleted.
Similar to before, you'll create subscribers to listen to these events.
Handle Create and Update Products#
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.
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:
1import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"2import { syncProductsWorkflow } from "../workflows/sync-products"3 4export default async function handleProductEvents({5 event: { data },6 container,7}: SubscriberArgs<{ id: string }>) {8 await syncProductsWorkflow(container)9 .run({10 input: {11 filters: {12 id: data.id,13 },14 },15 })16}17 18export const config: SubscriberConfig = {19 event: ["product.created", "product.updated"],20}
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.
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.
So, you pass the product's ID to the syncProductsWorkflow
as a filter to retrieve only the product that was created or updated.
Test it Out
To test it out, start the Medusa application:
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.
Handle Product Deletion#
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.
Create Delete Product Step
The workflow to delete a product from Algolia will have only one step that deletes products by their IDs from Algolia.
So, create the step at src/workflows/steps/delete-products-from-algolia.ts
with the following content:
1import {2 createStep,3 StepResponse,4} from "@medusajs/framework/workflows-sdk"5import { ALGOLIA_MODULE } from "../../modules/algolia"6 7export type DeleteProductsFromAlgoliaWorkflow = {8 ids: string[]9}10 11export const deleteProductsFromAlgoliaStep = createStep(12 "delete-products-from-algolia-step",13 async (14 { ids }: DeleteProductsFromAlgoliaWorkflow,15 { container }16 ) => {17 const algoliaModuleService = container.resolve(ALGOLIA_MODULE)18 19 const existingRecords = await algoliaModuleService.retrieveFromIndex(20 ids, 21 "product"22 )23 await algoliaModuleService.deleteFromIndex(24 ids,25 "product"26 )27 28 return new StepResponse(undefined, existingRecords)29 },30 async (existingRecords, { container }) => {31 if (!existingRecords) {32 return33 }34 const algoliaModuleService = container.resolve(ALGOLIA_MODULE)35 36 await algoliaModuleService.indexData(37 existingRecords as unknown as Record<string, unknown>[],38 "product"39 )40 }41)
The step receives the IDs of the products to delete as an input.
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.
Then, you delete the products from Algolia and pass the existing records to the compensation function.
In the compensation function, you reindex the existing records if an error occurs.
Create Delete Product Workflow
You can now create the workflow that deletes products from Algolia. Create the file src/workflows/delete-products-from-algolia.ts
with the following content:
1import { createWorkflow } from "@medusajs/framework/workflows-sdk"2import { deleteProductsFromAlgoliaStep } from "./steps/delete-products-from-algolia"3 4type DeleteProductsFromAlgoliaWorkflowInput = {5 ids: string[]6}7 8export const deleteProductsFromAlgoliaWorkflow = createWorkflow(9 "delete-products-from-algolia",10 (input: DeleteProductsFromAlgoliaWorkflowInput) => {11 deleteProductsFromAlgoliaStep(input)12 }13)
The workflow receives an object with the IDs of the products to delete. It then executes the deleteProductsFromAlgoliaStep
to delete the products from Algolia.
Create Delete Product Subscriber
Finally, you'll create the subscriber that listens to the product.deleted
event to trigger the above workflow.
Create the file src/subscribers/product-delete.ts
with the following content:
1import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"2import { deleteProductsFromAlgoliaWorkflow } from "../workflows/delete-products-from-algolia"3 4export default async function handleProductDeleted({5 event: { data },6 container,7}: SubscriberArgs<{ id: string }>) {8 await deleteProductsFromAlgoliaWorkflow(container)9 .run({10 input: {11 ids: [data.id],12 },13 })14}15 16export const config: SubscriberConfig = {17 event: "product.deleted",18}
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.
Test it Out
To test product deletion, start the Medusa application:
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.
Step 6: Add Search API Route#
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.
To implement the API Route, create the file src/api/store/products/search/route.ts
with the following content:
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2import { ALGOLIA_MODULE } from "../../../../modules/algolia"3import AlgoliaModuleService from "../../../../modules/algolia/service"4import { z } from "zod"5 6export const SearchSchema = z.object({7 query: z.string(),8})9 10type SearchRequest = z.infer<typeof SearchSchema>11 12export async function POST(13 req: MedusaRequest<SearchRequest>,14 res: MedusaResponse15) {16 const algoliaModuleService: AlgoliaModuleService = req.scope.resolve(ALGOLIA_MODULE)17 18 const { query } = req.validatedBody19 20 const results = await algoliaModuleService.search(21 query as string 22 )23 24 res.json(results)25}
You first define a schema with Zod, 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.
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.
Finally, you return the search results as it is in the response.
Add Validation Middleware#
To ensure that requests sent to the API route have the required request body parameters, you can use a middleware. A middleware is a function executed when a request is sent to an API Route. It's executed before the route handler.
Middlewares are created in the src/api/middlewares.ts
file. So create the file src/api/middlewares.ts
with the following content:
1import { 2 defineMiddlewares,3 validateAndTransformBody, 4} from "@medusajs/framework/http"5import { SearchSchema } from "./store/products/search/route"6 7export default defineMiddlewares({8 routes: [9 {10 matcher: "/store/products/search",11 method: ["POST"],12 middlewares: [13 validateAndTransformBody(SearchSchema),14 ],15 },16 ],17})
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:
matcher
: The path of the route the middleware applies to.method
: The HTTP methods the middleware applies to, which is in this casePOST
.middlewares
: An array of middleware functions to apply to the route. You apply thevalidateAndTransformBody
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.
You can use the search API route now. You'll see it in action as you customize the storefront in the next step.
Step 7: Search Products in Next.js Storefront#
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 along with the Medusa application.
In this step, you'll customize the Next.js Starter Storefront to add the search functionality.
The Next.js Starter Storefront was installed in a separate directory from Medusa. The directory's name is {your-project}-storefront
.
So, if your Medusa application's directory is medusa-search
, you can find the storefront by going back to the parent directory and changing to the medusa-search-storefront
directory:
Install Algolia Packages#
Before adding the implementation of the search functionality, you need to install the Algolia packages necessary to add the search functionality in your storefront.
Run the following command in the directory of your Next.js Starter Storefront:
This installs the Algolia Search JavaScript client and the React InstantSearch library, which you'll use to build the search functionality.
Add Search Client Configuration#
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.
In src/lib/config.ts
, add the following imports at the top of the file:
Then, add the following at the end of the file:
1export const searchClient: SearchClient = {2 ...(algoliasearch(3 process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || "", 4 process.env.NEXT_PUBLIC_ALGOLIA_API_KEY || ""5 )),6 search: async (params) => {7 const request = Array.isArray(params) ? params[0] : params8 const query = "params" in request ? request.params?.query : 9 "query" in request ? request.query : ""10 11 if (!query) {12 return {13 results: [14 {15 hits: [],16 nbHits: 0,17 nbPages: 0,18 page: 0,19 hitsPerPage: 0,20 processingTimeMS: 0,21 query: "",22 params: "",23 },24 ],25 }26 }27 28 return await sdk.client.fetch(`/store/products/search`, {29 method: "POST",30 body: {31 query,32 },33 })34 },35}
In the code above, you create a searchClient
object that initializes the Algolia client with your Algolia App ID and API Key.
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.
Set Environment Variables#
In the storefront's .env.local
file, add the following Algolia-related environment variables:
Where:
your_algolia_app_id
is your Algolia App ID, as explained in the Add Environment Variables section earlier.your_algolia_api_key
is your Algolia Search API key. You can retrieve it from the same API keys page on the Algolia dashboard that you retrieved the Admin API key from.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 earlier. You'll use this variable later.
Add Search Modal Component#
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.
Later, you'll add the search modal to the navigation bar, allowing customers to open the search modal from any page.
Create the file src/modules/search/components/modal/index.tsx
with the following content:
1"use client"2 3import React, { useEffect, useState } from "react"4import { Hits, InstantSearch, SearchBox } from "react-instantsearch"5import { searchClient } from "../../../../lib/config"6import Modal from "../../../common/components/modal"7import { Button } from "@medusajs/ui"8import Image from "next/image"9import Link from "next/link"10import { usePathname } from "next/navigation"11 12type Hit = {13 objectID: string;14 id: string;15 title: string;16 description: string;17 handle: string;18 thumbnail: string;19}20 21export default function SearchModal() {22 const [isOpen, setIsOpen] = useState(false)23 const pathname = usePathname()24 25 useEffect(() => {26 setIsOpen(false)27 }, [pathname])28 29 return (30 <>31 <div className="hidden small:flex items-center gap-x-6 h-full">32 <Button 33 onClick={() => setIsOpen(true)} 34 variant="transparent"35 className="hover:text-ui-fg-base text-small-regular px-0 hover:bg-transparent focus:!bg-transparent"36 >37 Search38 </Button>39 </div>40 <Modal isOpen={isOpen} close={() => setIsOpen(false)}>41 <InstantSearch 42 searchClient={searchClient} 43 indexName={process.env.NEXT_PUBLIC_ALGOLIA_PRODUCT_INDEX_NAME}44 >45 <SearchBox className="w-full [&_input]:w-[94%] [&_input]:outline-none [&_button]:w-[3%]" />46 <Hits hitComponent={Hit} />47 </InstantSearch>48 </Modal>49 </>50 )51}52 53const Hit = ({ hit }: { hit: Hit }) => {54 return (55 <div className="flex flex-row gap-x-2 mt-4 relative">56 <Image src={hit.thumbnail} alt={hit.title} width={100} height={100} />57 <div className="flex flex-col gap-y-1">58 <h3>{hit.title}</h3>59 <p className="text-sm text-gray-500">{hit.description}</p>60 </div>61 <Link href={`/products/${hit.handle}`} className="absolute right-0 top-0 w-full h-full" aria-label={`View Product: ${hit.title}`} />62 </div>63 )64}
You create a SearchModal
component that displays a search box and the search results using widgets from Algolia's react-instantsearch
library.
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.
Finally, you show the search modal when the customer clicks a "Search" button, which you'll add to the navigation bar next.
Add Search Button to Navigation Bar#
The last step is to show the search button in the navigation bar.
In src/modules/layout/templates/nav/index.tsx
, add the following imports at the top of the file:
Then, in the return statement of the Nav
component, add the SearchModal
component before the div
surrounding the "Account" link:
The search button will now appear in the navigation bar before the Account link.
Test it Out#
To test out the storefront changes and the search API route, start the Medusa application:
Then, start the Next.js Starter Storefront from its directory:
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.
Next Steps#
You've now integrated Algolia with Medusa and added search functionality to your storefront. You can expand on these features to:
- Add filters to the search results. You can do that using Algolia's widgets and customizing the search API route in Medusa to accept filter parameters.
- Support indexing other data types, such as product categories. You can create the subscribers and workflows for categories similar to products.
If you're new to Medusa, check out the main documentation, where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
To learn more about the commerce features that Medusa provides, check out Medusa's Commerce Modules.