Search by Algolia
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

Algolia named a leader in IDC MarketScape
algolia

Algolia named a leader in IDC MarketScape

We are proud to announce that Algolia was named a leader in the IDC Marketscape in the Worldwide General-Purpose ...

John Stewart

VP Corporate Marketing

Mastering the channel shift: How leading distributors provide excellent online buying experiences
e-commerce

Mastering the channel shift: How leading distributors provide excellent online buying experiences

Twice a year, B2B Online brings together America’s leading manufacturers and distributors to uncover learnings and industry trends. This ...

Jack Moberger

Director, Sales Enablement & B2B Practice Leader

Large language models (LLMs) vs generative AI: what’s the difference?
ai

Large language models (LLMs) vs generative AI: what’s the difference?

Generative AI and large language models (LLMs). These two cutting-edge AI technologies sound like totally different, incomparable things. One ...

Catherine Dee

Search and Discovery writer

What is generative AI and how does it work?
ai

What is generative AI and how does it work?

ChatGPT, Bing, Bard, YouChat, DALL-E, Jasper…chances are good you’re leveraging some version of generative artificial intelligence on ...

Catherine Dee

Search and Discovery writer

Feature Spotlight: Query Suggestions
product

Feature Spotlight: Query Suggestions

Your users are spoiled. They’re used to Google’s refined and convenient search interface, so they have high expectations ...

Jaden Baptista

Technical Writer

What does it take to build and train a large language model? An introduction
ai

What does it take to build and train a large language model? An introduction

Imagine if, as your final exam for a computer science class, you had to create a real-world large language ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

The pros and cons of AI language models
ai

The pros and cons of AI language models

What do you think of the OpenAI ChatGPT app and AI language models? There’s lots going on: GPT-3 ...

Catherine Dee

Search and Discovery writer

How AI is transforming merchandising from reactive to proactive
e-commerce

How AI is transforming merchandising from reactive to proactive

In the fast-paced and dynamic realm of digital merchandising, being reactive to customer trends has been the norm. In ...

Lorna Rivera

Staff User Researcher

Top examples of some of the best large language models out there
ai

Top examples of some of the best large language models out there

You’re at a dinner party when the conversation takes a computer-science-y turn. Have you tried ChatGPT? What ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What are large language models?
ai

What are large language models?

It’s the era of Big Data, and super-sized language models are the latest stars. When it comes to ...

Catherine Dee

Search and Discovery writer

Mobile search done right: Common pitfalls and best practices
ux

Mobile search done right: Common pitfalls and best practices

Did you know that 86% of the global population uses a smartphone? The 7 billion devices connected to the Internet ...

Alexandre Collin

Staff SME Business & Optimization - UI/UX

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

Creating an omnibar with Autocomplete
engineering

Bryan Robinson

Senior Developer Relations Specialist

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

Julia Seidman

Developer Educator