#3 Building Headless Commerce - Adding Search Engine with Algolia
Tags: javascript, typescript, programming, vue
Published: 2022-07-04 07:30:44

When I first heard about Algolia, I was a bit sceptical about it. Why would I need a search engine in my web application? I can search through my own database myself, right? Of course, that is correct. But Algolia is just super fast in terms of delivering search results to your website. And this is exactly what you want to deliver to your customers and users, speed!

Make sure to check out Algolia module for Nuxt as we recently released a 1.0.0 version of it -> https://algolia.nuxtjs.org/

I have written already some articles about Algolia but this time, I decided to record a video about it!

{% youtube GGyp0Rqsxb8 %}

In this video we will be adding a Search Engine Algolia to our Headless Commerce application we have created in our previous video. If you have not seen this video yet (here is the link -> https://www.youtube.com/watch?v=QK6wPHFiRyM), I highly encourage you to do that as it explains really well the concepts of e-commerce and its development. 

We will dynamically fetch search results from Algolia to our Nuxt 3 application.

If you get lost at some point here is the github repo -> https://github.com/Baroshem/nuxt-shopify-tailwind and branch `feat/algolia`.

## Code

In order to integrate Algolia with your Nuxt application, I would highly recommend to try out the offical Nuxt module. I am also a core maintainer of it :)

First, let's install the module:

```bash
yarn add @nuxtjs/algolia # npm install --save @nuxtjs/algolia
```

Next, let's register it in the modules array in our `nuxt.config.ts` file and add required configuration, in this case `apiKey` and `applicationId`:

```ts
  modules: ["@nuxtjs/tailwindcss", "nuxt-graphql-client", "@nuxtjs/algolia"], // <- here

  algolia: {
    apiKey: process.env.ALGOLIA_SEARCH_API_KEY,
    applicationId: process.env.ALGOLIA_APPLICATION_ID,
  },
```

And this point, also remember to add the environment variables to the `.env` file:

```bash
ALGOLIA_SEARCH_API_KEY=<YOUR_ALGOLIA_SEARCH_API_KEY>
ALGOLIA_APPLICATION_ID=<YOUR_ALGOLIA_APPLICATION_ID>
```

Furthermore, in our `TheHeader.vue` component let's add a script tag where we will call the `useAlgoliaSearch` composable. Please keep in mind that in the video, I have used the deprecated `useSearch` composable but the proper one is the one below.

```vue
<script lang="ts" setup>
const { result, search } = useAlgoliaSearch("headless_commerce");
const hits = ref([]);
const fetchSearchResults = async (e) => {
  await search({ query: e.target.value });
  hits.value = result.value.hits;
};
</script>
```

Let's stop for a second here. In the script tag, we have called a `useAlgoliaSearch` and passed an index name as a parameter. Under the hood, this composable will call the init index method to initialize the Algolia index.

Next, we have registered a ref with an empty array that is called `hits`. This array will be populated with a result from Algolia.

Finally, we have registered a method that will be triggered after input change to fetch the search results based on the query provided by the user. Under the hood this method will call the search method from the `useAlgoliaSearch` composable and assign the result to the hits. In the production application, please remember to implement some debouncing mechanism to not generate too much traffic to Algolia.

Going further into the `TheHeader.vue` component improvements, we have also created an input that will react to the query change, and also the search results in a form of a list.

```html
<div class="px-6 flex items-center">
      <NuxtLink to="/">
        <img class="h-20 w-20 mr-16" src="/logo.svg" alt="Store logo" />
      </NuxtLink>
      <div class="flex justify-center relative">
        <div class="mb-3 w-96">
          <input
            type="search"
            class="block w-full px-3 py-1 bg-white bg-clip-padding border border-solid border-gray-300 rounded"
            id="search"
            placeholder="Search for products"
            @input="fetchSearchResults"
          />
        </div>
        <div
          v-if="hits.length"
          class="flex justify-center absolute top-10 z-10"
        >
          <ul class="bg-white border border-gray-200 w-96 text-gray-900">
            <li
              v-for="hit in hits"
              :key="hit.objectID"
              class="px-6 py-2 border-b border-gray-200 w-full"
              @click="hits = []"
            >
              <NuxtLink
                :to="`/products/${hit.Handle}`"
                class="flex items-center"
              >
                <img class="w-20" :src="hit['Image Src']" />
                <p class="ml-4">{{ hit.Title }}</p>
              </NuxtLink>
            </li>
          </ul>
        </div>
      </div>
```

There is a lot of code here but the general idea is the input that triggers fetching the search results, and a list of results displayed after fetching.

And that's it!

## Summary

Well done! You have just added Algolia Search Engine to your Headless Commerce application. Keep in mind that this is just the beginning of the searching capabilities so for more, I highly encourage you to visit both https://www.algolia.com/ and https://algolia.nuxtjs.org/.