How to Optimize Strapi With On-Site Search
Tags: search, strapi, webdev, meilisearch
Published: 2022-11-07 09:45:08

**Author: Luna Bell**

A headless content management system ([CMS](https://www.contentful.com/r/knowledgebase/what-is-headless-cms/)) is one of the best solutions for creating an omnichannel experience and providing streamlined content delivery. That is because a headless CMS works as a back-end **content repository** that serves digital content via an application programming interface ([**API**](https://www.techtarget.com/searchapparchitecture/definition/application-program-interface-API)).

As a result, it is easier to deliver content on multiple devices, platforms, and applications than with traditional CMS systems. However, you’ll need to optimize the headless CMS to make your content more easily accessible. 

One of the easiest ways to do this is using an **on-site search**, which helps users browse large amounts of content quickly. Not only does this improve the navigational interface, but it also results in a better overall user experience.

This article will explore the benefits of [using a headless CMS](https://strapi.io/blog/10-reasons-headless-cms) and what on-site search is. We’ll also provide suggestions for on-site search options for headless CMS solutions and explain how to use one in a web application.

## Why Use a Headless CMS?

A headless CMS architecture offers a backend content management system where the content repository is separated from the presentation layer, known as the “head.” In contrast, a traditional CMS architecture provides a single system for creating, managing, and presenting content. 

You may want to scale content and operations regularly as your business grows. For that reason, using a headless CMS might be a good option. It enables developers to focus on building the front-end while the marketing team focuses on optimizing content and omnichannel marketing. 

[Strapi is the leading open-source customizable headless CMS platform](https://strapi.io) that offers flexibility in creating APIs. It gives developers the freedom to choose their own frameworks and quickens the development process. 

With a headless CMS like Strapi, users can easily manage and deploy the same content across mobile apps, websites, internet of things ([IoT](https://www.zdnet.com/article/what-is-the-internet-of-things-everything-you-need-to-know-about-the-iot-right-now/)) devices, and other digital platforms. That way, you can deliver personalized content while maintaining consistent branding.

![Strapi Website Homepage](https://lh4.googleusercontent.com/mIJU7AniLVWvTBgfloC2EK1RqCocrdF-1DgejQPaihLFQfmbV44pFb2G7EN9WsaomrItxZBQOFuqS0KWg466aTclDr1C9B0EMLtnh-KX4P6hC_9CGhgK97sVKr3CnwD6yotXEhVcNkOCvOy6Vr6jFLp5UvLqjiiyJ3YBDPB8SLwPZDPKt4wzo_cyHhe-OzpE-AZNrA)

Strapi has many features that can help you build an engaging digital experience, such as an intuitive interface, a content builder, and a customizable API. In addition, its [authentication and authorization](https://strapi.io/blog/a-beginners-guide-to-authentication-and-authorization-in-strapi) feature can secure API endpoints by giving access based on different user roles.

Furthermore, the Strapi headless content management system can be integrated with many popular tools and frameworks, including **Meilisearch, Angular, React, Hugo**, and **Gatsby**. For example, using the [Meilisearch Strapi plugin](https://market.strapi.io/plugins/strapi-plugin-meilisearch), you can add your Strapi content types into Meilisearch instances. This will make your data more accessible and easy to navigate directly from the database. 


## What is On-Site Search?
On-site search, also known as **internal search,** allows users to find website content by typing queries into a search bar. It helps users navigate a website and retrieve relevant information easier than if they were to search manually. 

Dynamic and more complex websites such as **web applications**, **web forums**, and **media sites** may require on-site search. That’s because these sites have a lot of content that can be difficult to find. Without an on-site search function, users’ time is wasted and they may even exit your website in frustration. 

For example, online stores that offer a wide range of products should have an on-site search tool. It will streamline the customer journey as users can find a product based on specific criteria. As a result, it enhances the customer experience and can boost conversions.

**To create an effective on-site search functionality, check the factors below:**

- **Search bar:** place it in a visible area, such as on the website header or sidebar.
- **Search filters or faceted navigation:** enable this function so users can sort search results faster based on their preferences.
- **Synonyms, misspellings, or abbreviations:** avoid returning empty results by accommodating any type of user input.
- **Semantic search:** display relevant and accurate results for users by understanding their intent.
- **Predictive search:** show result suggestions according to the first few words users type.


## On-Site Search Solutions for a Headless CMS
Since on-site search brings various benefits to your website, from enhancing the user experience and SEO to optimizing site performance, let’s review some on-site search options suitable for headless CMS platforms. 


### 1. Meilisearch
![Meilisearch Website Homepage](https://lh3.googleusercontent.com/6zgk5KcbCqeyINfZp9EL3Vg77qPbDS60lVFPIWSLoKvdOyKtia9NDfdhZpyvdr8cQljNJ2ZWDkeBsiVePNkuOf5GdaCB9P__hhf31u7LHKnsIUnZCMsfgnrz0eZKxZlLPdch0qBsng6UBYKGqAjXr6SOD4cZZs-v3xTh0DFH8olpFN6kyOUaI4AGNPWOWF9h3EEqmQ)


[Meilisearch is an open-source search engine that offers various integrations to websites and applications.](https://www.meilisearch.com/) It focuses on the users’ needs by creating a fast and relevant search experience with typo tolerance, filters, and custom rankings.

Currently, Meilisearch is available with many popular web frameworks, front-end tools, and platforms. You can also install the [Meilisearch WordPress plugin](https://github.com/meilisearch/meilisearch-wordpress) when it becomes available. However, ensure that your site uses reliable hosting to provide smooth performance and integration. 

For this, opt for managed WordPress hosting instead of standard shared hosting. The former offers servers optimized for WordPress and often includes auto-updates. We recommend [Hostinger.com](https://www.hostinger.com/wordpress-hosting) as their WordPress hosting plans support Multisite and have unlimited bandwidth. 

**Pros**:

- It’s easy to set up.
- It’s highly customizable.
- It offers excellent permission management using API keys.
- It provides a fast search experience that returns search results within **<50** milliseconds.
- It supports search previews to ensure the search settings work properly.

**Cons**:

- It only supports a single-node setup.
- Comprehensive search analytics is not available.
- It does not offer A/B testing.


### 2. Algolia
![Algolia Website Homepage](https://lh4.googleusercontent.com/Spk3-ej2n-j52tMSbFf8uYVOYJhNb0h4W4ZYC64VvFB-dKSzMHtHNN9eAWr_PdbSW3TL6dXhjVOMevZIuXSff31kQjgrP-u0nLsn0Xg0vJbD4kgd-iZrVroBhmatQ47RMHeuHrmWJTmJP4d6A2xt7cAkN2gVjQzQCr9s5XqSzo9R762W9lMPQeWCcYB2DCtwoNNJzQ)

[Algolia is one of the most popular on-site search engines that comes with a powerful API.](https://www.algolia.com/products/search-and-discovery/hosted-search-api/) It lets you add internal search to any web application seamlessly and quickly. Moreover, Algolia has built-in search analytics, which can give you valuable insights into your website and audience, from popular searches and click positions to conversion rates. This can help you to improve your search performance.

Since this tool can integrate with eCommerce platforms and product information management (PIM) software, many popular retail companies use Algolia as their search engine tools, such as **Lacoste, Dior**, and **L'Occitane**.

**Pros**:
- It provides search analytics.
- There’s a personalized search experience.
- It offers optimized search performance with AI search technology.
- Excellent customer support is available via email and chat.

**Cons**:
- Some parts of the documentation are incomplete.
- Premium solutions can be costly for small businesses, starting at **$1/month** per **1,000** search requests.


### 3. Elasticsearch
![Elasticsearch Website Homepage](https://lh5.googleusercontent.com/Ngm9PfcSjx7FPaJ5p8uKFo1G656-YtWKE6Ih-PCgKGCWzrHUxVWJxTsi_NcKALxpW4h8DhWPmTTGGRYdc1BOVP8pCJUFwjoDS1uvx_UYFAvjK4UDSi06qQyDSRhTf_DYG28_JNtEeo8Yg6ob-1MWWnoDAyPWuUwpYnTzppnGViWTOeSGdfRU9yVlMqh0zqXZMVV38g)

[Elasticsearch is a search solution](https://www.elastic.co/enterprise-search) built on [Apache Lucene](https://techmonitor.ai/technology/hardware/apache-lucene) that offers powerful features, such as a native web crawler, extensible APIs, and machine learning. With advanced tools like text classification and vector search, you can analyze search performance and set personalizations. 

This search solution also enables you to detect anomalies and organize datasets. Additionally, Elasticsearch can be used as an alternative to **MongoDB** and **RavenDB** as it supports the JavaScript Object Notation ([JSON](https://www.json.org/)) format to store data.

**Pros**:
- It’s optimized for real-life searches.
- It handles complex searches efficiently.
- Its high scalability enables you to manage large amounts of data on multiple servers.
- It’s schema-free and doesn’t require definitions like index and field types before the indexing process.

**Cons**:
- It only supports the JSON format to process requests and responses.
- There’s no free plan available.
- It’s quite expensive; plan prices start from **$95/month** to **$175/month**.


### 4. Typesense

[Typesense is an open-source search engine](https://typesense.org/) built using the [C++ language](https://cplusplus.com/doc/tutorial/). Through its dynamic sorting and typo tolerance features, you can deliver an instant search-as-you-type experience for site visitors.

Aside from that, this tool is easy to deploy as it offers an intuitive **RESTful API** and integrates with various frameworks. As a result, developers can increase their productivity to build an excellent search experience. 

Other key features of Typesense are its various search parameters, such as grouping, faceting, and pagination. You can also download the tool as a WordPress plugin.

**Pros**:
- It offers a unique search experience.
- It automatically corrects typos.
- It protects user privacy by not gathering personal information.
- It integrates with popular programming languages, such as **Ruby** and **JavaScript**.

**Cons**:
- It’s unable to handle synonyms without a manual setup.
- It does not offer personalization and server-based search analytics.

## Use Case: Meilisearch for Strapi 
After discussing the benefits of using an on-site search solution with a headless CMS, let’s explore how to set up **Meilisearch** on **Strapi** for your web application project. In this example, we will demonstrate the steps for a movie web application.

### 1. Frontend Setup
Frontend refers to the presentation layer of an application that focuses on **user interface** elements such as buttons, checkboxes, and search fields. It enables web visitors to see and interact with content on your web application. Remember that creating a front-end system requires technical web development skills like **HTML**, **CSS**, and **JavaScript**.  

To set up your frontend on **Strapi**, find the code from the GitHub repository. For example, use the [front-end Strapi code](https://github.com/Victory-ET/Movies-meilisearch-frontend) or the [Strapi starter code](https://github.com/Victory-ET/Moviesapp-Strapi) for your movie web application. Then, use `npm run develop` to run the development server.

### 2. Strapi Setup
Before running **Strapi** with the command-line interface (CLI) installation script, ensure to [install Node.js and npm or yarn](https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/installation/cli.html) on your computer. Then, create a new project in Strapi using the following command:
`npx create-strapi-app@latest my-project --quickstart`

The quickstart installation uses an SQL database like [PostgreSQL](https://strapi.io/blog/postgre-sql-and-strapi-setup). Alternatively, you can choose a custom installation with your preferred database. 

### 3. Installing the Meilisearch Plugin
To use **Meilisearch** locally, you’ll need to first [set up and run](https://docs.meilisearch.com/learn/getting_started/quick_start.html) it. Next, install the plugin by downloading it with **npm** or **yarn**. For example, to download a package with **npm**, add the following code:
`npm install strapi-plugin-meilisearch`

Next, rebuild your **Strapi** before developing your project by running the code npm run develop. In this case, your Strapi should be running on the localhost URL in your browser, where you will see a login page.

Once you are directed to the Strapi dashboard, click on **Meilisearch** -> **Settings**. Then, enter the URL for the Meilisearch instance. Now, you can add your movie collection to Meilisearch in the **Collection** tab.

### 4. Integrating Search Functionality in the Web Application

To integrate the search functionality, pass the search input data from the **Nav** component to the **Movies** component and add it to the `**fetchData**` function. In **Movie.js**, create a function that returns the search field value:
```js
 const [input, setInput] = useState("");
    // use effect block
    const pull_data =(dat)=>{
      setInput(dat)
    }
```
    
Then, pass the **pull_data** function to the **Nav** component:
`<Nav func={pull_data}/>`

Next, pass the value from the input field to this prop in **Nav.js**: 

```js    
    const Nav = ({func}) => {

      const [input, setInput] = useState("");
      func(input)
        const handleInputChange = (e) => {
            setInput(e.target.value);
          };
    //....
```
    
Finally, add **input** to the **fetchData** function in **Movie.js**:

```js    
    const index = await client.getIndex('moviesapp');

          const movies = await index.search(input);
          setCollection(movies.hits);
        };
        fetchData();
      }, [input]);
```

Now, you can type a movie title in the search field and receive the relevant information in your web application.

## Conclusion
With a headless CMS like **Strapi**, you can create a seamless digital experience across multiple platforms, such as websites and mobile apps. That’s because a headless system supports omnichannel marketing and speedy content delivery, which is excellent for fast-growing web applications.

A headless CMS enables developers to build a front-end system with their chosen frameworks and easily integrate many tools to improve the user experience. To get the most out of your headless CMS, consider adding on-site search to optimize it.

We hope this article has helped you to understand the benefits of using a headless CMS and how to optimize it with on-site search. Good luck!