Skip to content
Darin Larimore
All posts

Building an Algolia search on a Statamic site

5 min read
On this page
  1. Scout is not the Statamic part
  2. The record I should not have built
  3. The front end is a script tag
  4. What the newer site taught me
  5. The short version

In November 2023 I built a small personal site for a library of tiling patterns: 190 entries, each one an image, a brand and a handful of tags. The whole point of the site was the search page. Type "wood" or "green", click a tag, get the grid. Statamic's local driver could have matched titles, but I wanted facets with counts and results that update without a page load, and that is what Algolia's InstantSearch does well.

Scout is not the Statamic part

The first thing I got wrong was reaching for laravel/scout. That is how I had seen Algolia done in Laravel, so it went into composer.json along with a config/scout.php. Scout indexes Eloquent models. Statamic entries are not Eloquent models, and Statamic has its own search system with an Algolia driver. The Scout config sat in that repo for a year without indexing anything. If your searchable content is entries, the whole job is one index in config/statamic/search.php:

'patterns' => [
    'driver' => 'algolia',
    'searchables' => 'collection:patterns',
    'fields' => ['title', 'tags', 'image', 'date', 'brand'],
    'transformers' => [
        'tags' => fn ($tags) => [
            'tags' => collect($tags)->map(fn ($tag) => ucwords($tag))->toArray(),
        ],
        'image' => function ($image) {
            // ...
        },
    ],
],

with the app id and admin key under drivers.algolia.credentials. A transformer takes the field value and returns an array that is merged into the record, so one field can become several attributes. tags went in title-cased because the facet list shows the raw value and the entries had lowercase tags. php please search:update patterns builds the index, and Statamic's UpdateItemIndexes listener keeps it current on every save. On this site every save in the control panel both updated Algolia and produced one of the 343 "Entry saved" commits that git automation made.

The record I should not have built

The image transformer did two things: the public URL for the grid, and a download link. The download link was a presigned S3 request with ResponseContentDisposition: attachment, good for seven days.

$request = $s3Client->createPresignedRequest($command, '+7 days');

return [
    'image' => env('AWS_URL').'/'.$image,
    'downloadUrl' => (string) $request->getUri(),
];

That signed URL is stored in the index. Nothing in the repo rebuilds the index on a schedule, so a week after any rebuild every download button on the site pointed at an expired link until I ran the update by hand. A search record should hold stable data. Sign the URL when someone clicks, in a route, not at index time.

The front end is a script tag

No build step. The block loads algoliasearch-lite and instantsearch.js from a CDN, then wires widgets to empty divs:

const search = instantsearch({
    indexName: 'patterns',
    searchClient,
    clickAnalytics: true,
    initialUiState: { patterns: { query: randomQuery() } },
});

search.addWidgets([
    instantsearch.widgets.searchBox({ container: '#searchbox', searchAsYouType: false }),
    instantsearch.widgets.configure({ hitsPerPage: 12 }),
    instantsearch.widgets.refinementList({ container: '#tags', attribute: 'tags', showMore: true }),
    instantsearch.widgets.hits({ container: '#hits', templates: { item: renderPattern } }),
    instantsearch.widgets.pagination({ container: '#pagination' }),
    instantsearch.widgets.stats({ container: '#stats' }),
    instantsearch.widgets.poweredBy({ container: '#powered-by' }),
]);

Two choices worth explaining. searchAsYouType: false because every keystroke is a search request and this is a hobby site on the free plan. The poweredBy widget and a "Search Powered By" mark in the footer because the free plan wants attribution; that footer change is its own commit from 9 November 2023. The hit template is Alpine: clicking a card sets the pattern as the page background and reveals the download link, and clicking a tag chip calls search.renderState.patterns.refinementList.tags.refine(tag) so the chips and the sidebar facet are the same filter.

The one thing the older site could not do was push index settings. The Algolia driver on that major inserts and removes documents and has no notion of settings, so the fact that tags is a facet attribute lives in the Algolia dashboard, not in the repo. The app id and search-only key were also typed straight into the Blade view. Safe, since a search key can only read, but wrong for anything with more than one environment.

What the newer site taught me

In November 2024 a colleague at the agency set up the same kind of search for a library of case-study projects, on the current major, and I joined the project in March. Three things in that config fixed problems I had on my own site.

The index is named env('APP_ENV').'_projects' and the template reads {{ config:app:env }}_projects, so local, staging and production never write to the same index. The credentials come out of config, {{ config:statamic:search:drivers:algolia:credentials:search_api_key }}, so nothing is hard-coded in a view. And the index carries its own settings:

'settings' => [
    'unretrievableAttributes' => ['blocks'],
    'attributesForFaceting' => ['timeline', 'length', 'industry', 'budget', 'type'],
],

The newer driver pushes that with setSettings() whenever the index updates. The blocks field goes in so the page-builder content is matched, and is marked unretrievable so it is never sent to the browser as part of a hit. The commit that added it is titled "Add blocks to search but don't show in payload", which is the whole idea in one commit title. The five facets are taxonomy fields, and each has a transformer that turns term slugs into term titles, so the refinement list shows "Healthcare" and not "healthcare". The featured image is a Glide-generated 1280 by 720 WebP URL. A stable URL, this time.

The short version

Statamic entries need Statamic's search config, not Scout. Keep transformers to stable values, never anything that expires. Name the index after the environment, read keys from config, and on the current major put the facet and retrievability settings in the index definition so they live in git with everything else.