Integrate Algolia with Statamic

Arlind Musliu Portrait
Arlind Musliu

April 1, 2024 · 3 min read · 98 views

Statamic and Algolia logos

Algolia Search Statamic Integration

Algolia is a cutting-edge search platform that gives your Statamic site lightning-fast, relevant search results in a blink of an eye. With Algolia, your search results are smartly prioritized and displayed using a customizable ranking formula. Ready to get started? Here's your guide to integrating Algolia with Statamic.

Setting Up Algolia

First up, you'll need to create an account with Algolia. Once you've got your account, you'll be given an Application ID and an Admin API Key. Keep these safe – you'll need them in a moment.

Next, you're going to 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 snippet tells Statamic to use the Algolia driver:

Setup a New Search Index

<?php

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 snippet tells Statamic to use Algolia for all searchable content. We are only searching for the title.

Kicking Off Index Creation

Your next step is to tell Statamic to start the index creation process. You can do this by running:

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, which can make your search as fast as flipping a light switch.

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 all set up, you can dive deeper into Algolia and its settings to tweak your search experience. Whether it's adjusting typo tolerance, setting up faceting, or defining ranking rules, Algolia offers a robust set of options to make your search feature powerful and user-friendly.


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.

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Statamic
Heading Pattern

Related Posts

Stay up to date

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