Integrate Algolia with Statamic

Arlind Musliu cofounder at Lucky Media
Arlind Musliu

April 1, 2024 · 2 min read

Integrate Algolia with Statamic

Algolia is a modern search platform that gives your Statamic site fast and relevant search results. With Algolia, your search results are smartly prioritized and displayed using a customizable ranking formula. Here’s how to add Algolia to your Statamic site.

Algolia Search Statamic Integration

Setting Up Algolia

Create an account with Algolia and get the Application ID and an Admin API Key. Keep these safe – you’ll need them in a moment.

Add your new Algolia credentials to your .env file in your Statamic project.

ALGOLIA_APP_ID=app-id
ALGOLIA_SECRET=admin-key

If you are using Vite as your module bundler, then your .env credentials would look like this:

VITE_ALGOLIA_APP_ID=app-id
VITE_ALGOLIA_SECRET=admin-key

If you are using Webpack as your module bundler (which we’ll be using in this example) then your .env credentials would look like this:

MIX_ALGOLIA_APP_ID=app-id
MIX_ALGOLIA_SECRET=admin-key

Next, we have to install the composer dependency.

composer require algolia/algoliasearch-client-php

Configure a new search driver

This code snippet tells Statamic to use the Algolia driver:

Setup a new search index

return [

    /*
    |--------------------------------------------------------------------------
    | Default search index
    |--------------------------------------------------------------------------
    |
    | This option controls the search index that gets queried when performing
    | search functions without explicitly selecting another index.
    |
    */

    'default' => env('STATAMIC_DEFAULT_SEARCH_INDEX', 'default'),

    /*
    |--------------------------------------------------------------------------
    | Search Indexes
    |--------------------------------------------------------------------------
    |
    | Here you can define all of the available search indexes.
    |
    */

    'indexes' => [

        'default' => [
            'driver' => 'local',
            'searchables' => 'all',
            'fields' => ['title', 'subtitle', 'teaser', 'article_content'],
        ],

	// Ensure you replace 'news' with the name of the index you configured in Algolia.
        'news' => [
            'driver' => 'algolia',
            'searchables' => 'collection:news',
            'fields' => ['title'],
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Driver Defaults
    |--------------------------------------------------------------------------
    |
    | Here you can specify default configuration to be applied to all indexes
    | that use the corresponding driver. For instance, if you have two
    | indexes that use the "local" driver, both of them can have the
    | same base configuration. You may override for each index.
    |
    */

    'drivers' => [

        'local' => [
            'path' => storage_path('statamic/search'),
        ],

// Replace MIX_ALGOLIA_APP_ID and MIX_ALGOLIA_SECRET with the module bundler you are using (Vite, Mix)
        'algolia' => [
            'credentials' => [
                'id' => env('MIX_ALGOLIA_APP_ID', ''),
                'secret' => env('MIX_ALGOLIA_SECRET', ''),
            ],
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Search Defaults
    |--------------------------------------------------------------------------
    |
    | Here you can specify default configuration to be applied to all indexes
    | regardless of the driver. You can override these per driver or per index.
    |
    */

    'defaults' => [
        'fields' => ['title'],
    ],

];

This instructs Statamic to use Algolia for all searchable content. We are only searching for the title.

Kicking Off Index Creation

Let’s start the index creation process:

php please search:update

Working with JavaScript and Algolia

To make things super speedy, you can talk to Algolia directly from the front end of your site using JavaScript. This way, you bypass the server for search requests and searching becomes even faster.

Algolia has a JavaScript API client that helps you with this. It’s designed to work smoothly with Algolia and comes with benefits like automatic retries and batching for fewer API calls.

Frontend Searching with Alpine.js

Algolia’s JavaScript client works in both the browser and on the server with Node.js. You can install it using npm by running:

npm install algoliasearch

npm install @alpinejs/focus

Their documentation can be found here.

import algoliasearch from "algoliasearch";
import Alpine from "alpinejs";

window.Alpine = Alpine;
Alpine.plugin(focus);

Alpine.data("search", () => ({
    isOpen: false,
    results: [],
    query: "",
    index: null,

// Replace MIX_ALGOLIA_APP_ID and MIX_ALGOLIA_SECRET with the module bundler you are using (Vite, Mix)
    init() {
        const client = algoliasearch(
            process.env.MIX_ALGOLIA_APP_ID,
            process.env.MIX_ALGOLIA_SECRET
        );
        this.index = client.initIndex("news"); // Ensure you replace 'news' with the name of the index you configured in Algolia.

    },

    search() {
        this.$watch("query", async () => {
            this.results = await this.index.search(this.query, {
                hitsPerPage: 10,
            });
        });
    },

    clear() {
        this.query = "";
        this.results = [];
        this.isOpen = false;
    },
}));

Alpine.start();

Template code:

<div x-data="search">
    <input type="text" placeholder="Search for news" name="search" x-model="query" @input="search"
        @click.outside="clear()">
    <template x-if="query">
        <div>
            <template x-cloak x-show="results.nbHits > 0" x-for="(hit, index) in results.hits">
                <div class="group">
                    <a x-bind:href="hit.url">
                        <h2 x-text="hit.title"></h2>
                    </a>
                </div>
            </template>
        </div>
    </template>
</div>

Now do a simple search and hopefully get a search result back.

Next Steps

Now that you’re ready, you can dive deeper into Algolia and check advanced features to fine-tune your search. Whether it’s managing typo tolerance, setting up facets, or making ranking rules, Algolia has many options to enhance your search.


Bring Your Ideas to Life 🚀

Kickstart Your Statamic Project with the #1 Statamic Agency

Are you planning a new Statamic project or thinking about migrating your WordPress site to Statamic? Learn more about our expertise as a renowned Statamic development agency.

Technologies

Statamic
Arlind Musliu cofounder at Lucky Media
Arlind Musliu

Cofounder and CFO of Lucky Media

Stay up-to-date

Be updated with all news, products and tips we share!

Let’s chat

We partner with a limited number of brands each quarter to ensure senior-level attention on every project.

lokman and arlind headshots
Teamwork

Related posts

February 16, 2024

Statamic Searching Techniques
Statamic