Search by Algolia
Add InstantSearch and Autocomplete to your search experience in just 5 minutes
product

Add InstantSearch and Autocomplete to your search experience in just 5 minutes

A good starting point for building a comprehensive search experience is a straightforward app template. When crafting your application’s ...

Imogen Lovera

Senior Product Manager

Best practices of conversion-focused ecommerce website design
e-commerce

Best practices of conversion-focused ecommerce website design

The inviting ecommerce website template that balances bright colors with plenty of white space. The stylized fonts for the headers ...

Catherine Dee

Search and Discovery writer

Ecommerce product listing pages: what they are and how to optimize them for maximum conversion
e-commerce

Ecommerce product listing pages: what they are and how to optimize them for maximum conversion

Imagine an online shopping experience designed to reflect your unique consumer needs and preferences — a digital world shaped completely around ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

DevBit Recap: Winter 2023 — Community
engineering

DevBit Recap: Winter 2023 — Community

Winter is here for those in the northern hemisphere, with thoughts drifting toward cozy blankets and mulled wine. But before ...

Chuck Meyer

Sr. Developer Relations Engineer

How to create the highest-converting product detail pages (PDPs)
e-commerce

How to create the highest-converting product detail pages (PDPs)

What if there were a way to persuade shoppers who find your ecommerce site, ultimately making it to a product ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

Highlights from GopherCon Australia 2023
engineering

Highlights from GopherCon Australia 2023

This year a bunch of our engineers from our Sydney office attended GopherCon AU at University of Technology, Sydney, in ...

David Howden
James Kozianski

David Howden &

James Kozianski

Enhancing customer engagement: The role of conversational commerce
e-commerce

Enhancing customer engagement: The role of conversational commerce

Second only to personalization, conversational commerce has been a hot topic of conversation (pun intended) amongst retailers for the better ...

Michael Klein

Principal, Klein4Retail

Craft a unique discovery experience with AI-powered recommendations
product

Craft a unique discovery experience with AI-powered recommendations

Algolia’s Recommend complements site search and discovery. As customers browse or search your site, dynamic recommendations encourage customers to ...

Maria Lungu

Frontend Engineer

What are product detail pages and why are they critical for ecommerce success?
e-commerce

What are product detail pages and why are they critical for ecommerce success?

Winter is coming, along with a bunch of houseguests. You want to replace your battered old sofa — after all,  the ...

Catherine Dee

Search and Discovery writer

Why weights are often counterproductive in ranking
engineering

Why weights are often counterproductive in ranking

Search is a very complex problem Search is a complex problem that is hard to customize to a particular use ...

Julien Lemoine

Co-founder & former CTO at Algolia

How to increase your ecommerce conversion rate in 2024
e-commerce

How to increase your ecommerce conversion rate in 2024

2%. That’s the average conversion rate for an online store. Unless you’re performing at Amazon’s promoted products ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

How does a vector database work? A quick tutorial
ai

How does a vector database work? A quick tutorial

What’s a vector database? And how different is it than a regular-old traditional relational database? If you’re ...

Catherine Dee

Search and Discovery writer

Removing outliers for A/B search tests
engineering

Removing outliers for A/B search tests

How do you measure the success of a new feature? How do you test the impact? There are different ways ...

Christopher Hawke

Senior Software Engineer

Easily integrate Algolia into native apps with FlutterFlow
engineering

Easily integrate Algolia into native apps with FlutterFlow

Algolia's advanced search capabilities pair seamlessly with iOS or Android Apps when using FlutterFlow. App development and search design ...

Chuck Meyer

Sr. Developer Relations Engineer

Algolia's search propels 1,000s of retailers to Black Friday success
e-commerce

Algolia's search propels 1,000s of retailers to Black Friday success

In the midst of the Black Friday shopping frenzy, Algolia soared to new heights, setting new records and delivering an ...

Bernadette Nixon

Chief Executive Officer and Board Member at Algolia

Generative AI’s impact on the ecommerce industry
ai

Generative AI’s impact on the ecommerce industry

When was your last online shopping trip, and how did it go? For consumers, it’s becoming arguably tougher to ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

What’s the average ecommerce conversion rate and how does yours compare?
e-commerce

What’s the average ecommerce conversion rate and how does yours compare?

Have you put your blood, sweat, and tears into perfecting your online store, only to see your conversion rates stuck ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

What are AI chatbots, how do they work, and how have they impacted ecommerce?
ai

What are AI chatbots, how do they work, and how have they impacted ecommerce?

“Hello, how can I help you today?”  This has to be the most tired, but nevertheless tried-and-true ...

Catherine Dee

Search and Discovery writer

Looking for something?

facebookfacebooklinkedinlinkedintwittertwittermailmail

In today’s highly competitive e-commerce landscape, providing customers with a seamless and efficient search experience can make all the difference in driving sales and revenue. A search bar that is fast, relevant, and easy to use can help customers quickly find the products they are looking for and make informed purchase decisions.

Building a performant search bar in Nuxt with Algolia and Storefront UI can greatly enhance the user experience on your e-commerce website. Algolia is a powerful search engine that uses advanced algorithms to deliver fast and relevant search results, while Storefront UI is a library of reusable UI components that make it easy to build and customize an e-commerce storefront.

In addition to providing a fast and relevant search experience, a performant search bar can also help you better understand your customers’ search behavior and preferences. By tracking search queries and click-through rates, you can gain valuable insights into which products are most popular and which search terms are most commonly used. This information can help you optimize your product listings and tailor your marketing efforts to better meet the needs of your customers.

If you would like to jump in directly into the code, check out the following Stackblitz link:

https://stackblitz.com/edit/github-epeint-haemy4?file=app.vue
https://stackblitz.com/edit/github-epeint-haemy4?embed=1&file=app.vue

stackblitz template

This content was originally presented at Algolia DevCon 2023

Getting started

To get started, you will need to sign up for a free Algolia account and create an index for your e-commerce products. This index will allow Algolia to quickly search and retrieve product information, making it easier for customers to find what they are looking for. Once you have created your index, you can use the vue-instantsearch library to integrate Algolia into your Nuxt app and display search results in real time.

To connect to Algolia from Nuxt, we will be using an official module that I have created for Nuxt.

nuxt get started

But it doesn’t stop there. Algolia also offers an instant search feature that displays search results as the user types. This means that your users can see search results in real-time, without having to wait for the page to reload. Additionally, Algolia’s pagination feature can be used to limit the number of search results displayed at once, improving page load times and further enhancing the user experience.

To register the module, let’s install it first:

yarn add @nuxtjs/algolia

Next, let’s add it to the modules array in nuxt.config.ts

export default defineNuxtConfig({
modules: ['@nuxtjs/algolia']
})

And finally, let’s add .env file with the required environment variables:

ALGOLIA_API_KEY="0fd1c4eba2d831788333e77c9d855f1d"
ALGOLIA_APPLICATION_ID="AGN9HEEKF3"

And that’s it! You can now start using the Algolia by using the composable like following:

<script setup lang="ts">
const { result, search } = useAlgoliaSearch('test_index')

onMounted(async () => {
await search({ query: 'Samsung' })
})
</script>

<template>
<div>{{ result }}</div>
</template>

Now, let’s take a look at the Storefront UI which will be used to create the customizable and accessible search bar.

Storefront UI

Storefront UI provides a comprehensive library of pre-built UI components that can be easily customized and integrated into your Nuxt project. This means that you can save time and money by not having to build every UI component from scratch. Storefront UI includes everything from buttons and forms to complex UI components like product carousels and checkout flows.

storefront ui

The main idea of the Storefront UI component library is to use it in e-commerce projects but the amount of pre-built components is so big that you can use it in several different projects as well!

Check out the official documentation https://docs.storefrontui.io/v2/

Installation of Storefront UI in Nuxt application is pretty straightforward. First, let’s install the required packages:

yarn add -D @nuxtjs/tailwindcss @storefront-ui/vue

Next, let’s add @nuxtjs/tailwindcss to the modules array in the nuxt.config.ts file:

// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxtjs/tailwindcss']
})

Add / Create tailwind.config.ts with the following structure:

// tailwind.config.ts
import type { Config } from 'tailwindcss';
import { tailwindConfig } from '@storefront-ui/vue/tailwind-config';

export default <Config>{
presets: [tailwindConfig],
content: ['./**/*.vue', './node_modules/@storefront-ui/vue/**/*.{js,mjs}'],
};

And that’s it! You can start using the components like following:

<template>
<SfButton type="button" class="w-full"> Hello </SfButton>
</template>

<script lang="ts" setup>
import { SfButton } from '@storefront-ui/vue';
</script>

Storefront UI comes with many pre-built component for you and you can check them all out by visiting the documentation and the playground:

storefront default card

All components are designed in a preview/code way which means that you can easily copy the source code of the elements that you like directly into your project!

Using it all in your next (nuxt) project

Creating the SearchBar with Storefront UI is very simple as there is already a component template that we can just copy:

vue search

By clicking the Code tab, you can easily see all the code that is required to make the search bar work. Let’s copy it and adjust to work with Algolia.

In the code snippet below, I have marked places that was changed from the copied code from Storefront UI

<template>
<form
    ref="referenceRef"
    role="search"
    class="relative"
    @submit.prevent="submit"
  >
    <SfInput
      ref="inputRef"
      v-model="inputModel"
      aria-label="Search"
      placeholder="Search 'MacBook' or 'iPhone'..."
      @focus="open"
      @keydown="handleInputKeyDown"
    >
      <template #prefix > <SfIconSearch /></template>
       <template #suffix >
         <button
          v-if="inputModel"
          type="button"
          aria-label="Reset search"
          class="
            flex
            rounded-md
            focus-visible:outline focus-visible:outline-offset
          "
          @click="reset"
         >
           <SfIconCancel / > </button
       > </template >
     </SfInput >
     <div v-if="isOpen" ref="floatingRef" :style="style" class="left-0 right-0" >
       <div
        v-if="isLoadingSnippets"
        class="
          flex
          items-center
          justify-center
          w-full
          h-20
          py-2
          bg-white
          border border-solid
          rounded-md
          border-neutral-100
          drop-shadow-md
        "
       >
         <SfLoaderCircular / >
       </div >
       <ul
        v-else-if="result?.hits.length  > 0" // HERE
        ref="dropdownListRef"
        class="
          py-2
          bg-white
          border border-solid
          rounded-md
          border-neutral-100
          drop-shadow-md
        "
       >
         <li v-for="{ name, objectID } in result?.hits" :key="objectID" > // HERE
           <SfListItem
            tag="button"
            type="button"
            class="flex justify-start"
            @click="() = > selectValue(name)"
            @keydown.enter.space.prevent="selectValue(name)"
           >
             <p class="text-left" >
               <span >{{ name }} </span >
             </p >
           </SfListItem >
         </li >
       </ul >
     </div >
   </form >
 </template >

 <script lang="ts" setup >
import { type Ref, ref, watch } from 'vue';
import { offset } from '@floating-ui/vue';
import { watchDebounced } from '@vueuse/shared';
import { unrefElement } from '@vueuse/core';
import {
  SfIconCancel,
  SfIconSearch,
  SfInput,
  SfListItem,
  SfLoaderCircular,
  useDisclosure,
  useDropdown,
  useTrapFocus,
} from '@storefront-ui/vue';

const { result, search } = useAlgoliaSearch('test_index'); // HERE

const inputModel = ref('');
const inputRef = ref();
const dropdownListRef = ref();
const isLoadingSnippets = ref(false);
const { isOpen, close, open } = useDisclosure();
const { referenceRef, floatingRef, style } = useDropdown({
  isOpen,
  onClose: close,
  placement: 'bottom-start',
  middleware: [offset(4)],
});
const { focusables: focusableElements } = useTrapFocus(dropdownListRef as Ref <HTMLElement >, {
  trapTabs: false,
  arrowKeysUpDown: true,
  activeState: isOpen,
  initialFocus: false,
});

const submit = () = > {
  close();
  alert(`Search for phrase: ${inputModel.value}`);
};

const focusInput = () = > {
  const inputEl = unrefElement(inputRef)?.querySelector('input');
  inputEl?.focus();
};

const reset = () = > {
  inputModel.value = '';
  result.value = []
  close();
  focusInput();
};

const selectValue = (phrase: string) = > {
  inputModel.value = phrase;
  close();
  focusInput();
};

const handleInputKeyDown = (event: KeyboardEvent) = > {
  if (event.key === 'Escape') reset();
  if (event.key === 'ArrowUp') {
    open();
    if (isOpen && focusableElements.value.length  > 0) {
      focusableElements.value[focusableElements.value.length - 1].focus();
    }
  }
  if (event.key === 'ArrowDown') {
    open();
    if (isOpen && focusableElements.value.length  > 0) {
      focusableElements.value[0].focus();
    }
  }
};

watch(inputModel, () = > {
  if (inputModel.value === '') {
    reset();
  }
});

watchDebounced(
  inputModel,
  () = > {
    if (inputModel.value) {
      const getSnippets = async () = > {
        open();
        isLoadingSnippets.value = true;
        try {
          // HERE
          await search({
            query: inputModel.value,
          });
        } catch (error) {
          close();
          console.error(error);
        }
        isLoadingSnippets.value = false;
      };

      getSnippets();
    }
  },
  { debounce: 500 },
);
 </script >

Let’s stop for a second here to explain what has changed (places marked with // HERE)

  1. const { result, search } = useAlgoliaSearch('test_index') → We are calling a useAlgoliaSearch composable and we are passing an index name as a parameter. As a response we get an object that we destructure to get the result reactive property and search method that will be responsible for populating the result property with the hits from Algolia.
  2. v-for="{ name, objectID } in result?.hits" :key="objectID → We are looping over the hits that are returned from Algolia and destructure the name and objectID properties that are then used in the template (for dynamic keys and displaying the name of the search result.
  3. await search({ query: inputModel.value }) → Instead of the mocked search method, we are using an actual method from the Algolia module to search through the index and populate the result property

This is quite a usual thing you will do when working with @nuxtjs/algolia module.

The result of this change can be easily observed in the Stackblitz and in the screenshot below:

stackblitz change

As you can see, we have easily created a really nice-looking, performant, and accessible search bar in a matter of minutes!

Summary

Overall, building a performant search bar in Nuxt with Algolia and Storefront UI is a great way to improve the user experience on your e-commerce website. By providing fast and relevant search results, you can help customers quickly find the products they are looking for and make informed purchase decisions. And by using the insights gained from tracking search behavior, you can optimize your product listings and better meet the needs of your customers. So why not give it a try and see how it can help drive sales and revenue for your e-commerce business?

About the author
Jakub Andrzejewski

Senior Developer and Dev Advocate at Vue Storefront

githublinkedintwitter

Recommended Articles

Powered byAlgolia Algolia Recommend

Part 4: Supercharging search for ecommerce solutions with Algolia and MongoDB — Frontend implementation and conclusion
engineering

Soma Osvay

Full Stack Engineer, Starschema

Build a React app with fast indexing and instant inventory updates
engineering

Julia Seidman

Developer Educator

Creating an omnibar with Autocomplete
engineering

Bryan Robinson

Senior Developer Relations Specialist