DEV Community

Cover image for How to add Algolia to Nuxt
Jakub Andrzejewski
Jakub Andrzejewski

Posted on • Edited on

How to add Algolia to Nuxt

This article is a follow up to an article that I wrote some time ago (almost a year ago) about adding Algolia to Nuxt.

You can check the original article here.

Since then, a lot has change, both in how you can use Algolia in Nuxt and the Algolia itself (new logo, wohoo!). Because of that, I decided to come back to this topic, and also dive deeper into what the module that I have created can do for you in terms of Algolia integration.

What is Algolia?

Algolia is a Flexible Search & Discovery Hosted APIs that enables developers to build next generation apps with composable APIs, delivering relevant content in milliseconds.

Algolia landing page

In other words, Algolia is a very powerful search engine that works quite similar to Elasticsearch allowing for fast content delivery that matches current query.

You can read more about Algolia here

In this step I will just mention that at this point you should have an Algolia account and an index filled with some test data or your own data. When it will be done, make sure to save search api key and application ID from your Algolia settings as they will be used in the next section.

For the sake of this tutorial I have generated some dummy data in Algolia for Ecommerce so my Search dashboard looks like follows:

Algolia Dashboard

When generating a new index make sure to remember this name as it will be used in the next section.

Adding Algolia to Nuxt 3

Algolia provides a very good package that allow to integrate JavaScript project with Algolia API. However, in this project we will be using a Nuxt module instead that provides similar functionality by using handy composables like useAlgoliaSearch, useAlgoliaRef, etc.

https://github.com/nuxt-modules/algolia

First, let's install Algolia module in our Nuxt 3 project like so:



yarn add @nuxtjs/algolia # npm install @nuxtjs/algolia


Enter fullscreen mode Exit fullscreen mode

Next, add @nuxtjs/algolia to modules inside nuxt.config.ts:



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


Enter fullscreen mode Exit fullscreen mode

Create .env file and add following variables to it (the module will detect them automatically and serve them to algoliasearch package):



ALGOLIA_API_KEY="0fd1c4eba2d831788333e77c9d855f1d"
ALGOLIA_APPLICATION_ID="AGN9HEEKF3"


Enter fullscreen mode Exit fullscreen mode

By adding the module to modules, we can automatically import composables so that you can use them in your application without the need to import them.

After that, add following script setup section in your app.vue:



<script setup>
const { result, search } = useAlgoliaSearch('test_index') // pass your index as param

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


Enter fullscreen mode Exit fullscreen mode

Let's stop here for a second to discuss in more details what is going on here.

  1. We are calling a useAlgoliaSearch composable and we pass a name of the index created in the Algolia dashboard as a parameter.
  2. We are destructuring the result property and search method from this composable.
  3. search method will be used to call algoliasearch to search for the certain query.
  4. result is a reactive computed value containing the result of the search method.
  5. We are calling a search method inside onMounted lifecycle hook asynchronously and passing a query as a object property with a value of 'Samsung'

To display the result in the browser you can add result in your template to see the actual result of the search:



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


Enter fullscreen mode Exit fullscreen mode

As a result of this operation, you should see following result in your browser:

Algolia result in Browser

Wow, that's a lot of data and it was delivered in miliseconds. And that's it. You have now access to data delivered by Algolia that can be used to display some results to the users in a visually acceptable form (not in a raw data :D ).

Oh wait, there's more?!

Yes of course! This module can do much more for you. Let's say, that instead of calling the search method on onMounted lifecycle hook (or basically anywhere in the broweser), you would like to search for results on the server (SSR)? With the latest version, you can do so very easily:



<script setup lang="ts">
const { data } = await useAsyncAlgoliaSearch({ indexName: 'test_index', query: 'Samsung' })
</script>

<template>
  <div>{{ data }}</div>
</template>


Enter fullscreen mode Exit fullscreen mode

The structure of the data here is a bit different because useAsyncAlgoliaSearch is actually a wrapper around Nuxt useAsyncData composable so you have access to all properties returned by this composable with data fetching from Algolia (data, error, loading, etc).

Or maybe you would like to get the recommendations about the recent search? The module got you covered with a usage of algolia recommend feature:



<script setup>
const { result, get } = useAlgoliaRecommend()

onMounted(async () => {
  await get({ queries: [{ indexName: 'test_index', model: 'related-products', objectID: 'dca44dd5-aea6-4553-a3af-fcbda981a2ef' }] });
})
</script>


Enter fullscreen mode Exit fullscreen mode

Or maybe you would like to integrate Vue Instantsearch in your app? Here you go!

  1. Add necessary configuration to the module:


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


Enter fullscreen mode Exit fullscreen mode
  1. Add start using the Vue Instantsearch components in your app


<script setup lang="ts">
const indexName = 'test_index' 
const algolia = useAlgoliaRef()
import { AisInstantSearch, AisSearchBox, AisHits } from 'vue-instantsearch/vue3/es/index.js'
</script>

<template>
  <div>
    <ais-instant-search :index-name="indexName" :search-client="algolia">
      <ais-search-box />
      <ais-hits />
    </ais-instant-search>
  </div>
</template>


Enter fullscreen mode Exit fullscreen mode

And there is more! Check out all available options here

Bonus

I have added a new section to the module docs about content related to this module that you can check out here

Top comments (2)

Collapse
 
nozimjonjuraev profile image
Nozimjon Juraev

Hi, I try this library copy code example from docs: algolia.nuxtjs.org/advanced/vue-in... but get error: XMLHttpRequest is not defined. Any ideas what could be causing it?

Collapse
 
jacobandrewsky profile image
Jakub Andrzejewski

Hey,

this issue means that probably you are trying to call the client library on the server which does not have access to this package as it is browser only. But I cannot say more about it without additional details. Could you please report an issue in the GitHub? I will take a look at it then :)