Jekyll and Algolia search integration

Sunday, 16 August 2020.

Algolia

Recently I decided to add search functionality to my BeatleTech site (indeed, the one you are visiting right now). Not because I needed my readers to filter through the overwhelming number of articles I have written here (which I have not), but simply because I thought it would be a cool feature that would bring some nice interactivity to the site and to spark my ambition to write more blog posts going forward.

In this article I will explain why I picked Algolia Search and how it was integrated with this Jekyll generated static site, including some interesting improvements.

While tinkering a bit with the design and layout of this site during a rainy day at a Dutch campsite, I was looking for an easy Jekyll plugin to bring search to my website. Although I have a lot of experience in working directly with Elasticsearch, I didn’t want to go down a route of building and deploying everything from scratch. While certainly a nice exercise, this would definitely take too much time and maintenance down the line, which wouldn’t be worth it (yet) looking at the traffic statistics. So, like I said, looking for something easy and quick to get up and running within a day.

After some Google search queries, I quickly stumbled upon some people recommending Algolia at the Jekyll talk discussion board.

Digging into Algolia, I found the following compelling reasons to integrate with Algolia Search:

  • Known brand. It turns out I was already quite familiar (and satisfied) with Algolia Search as a consumer of Hacker News Search which is powered by Algolia.
  • Free tier. They recently (July 1st) introduced more customer-friendly pricing with a starting free tier as long as you would show the “Search by Algolia” next to your search results. Also with reasonable pricing when I need to scale up.
  • Great documentation. Their Getting started is clear, complete and up-to-date.
  • Open source. Jekykll Algolia Plugin for indexing Jekyll posts
  • UI Template. Template with UI component using instantsearch.js
  • Example project. Github project jekyll-algolia-example

How to integrate Algolia and Jekyll?

To integrate with Jeyll we first need to install and run the jekyll-algolia-plugin to push the content of our Jekyll website to our Algolia index. Secondly we need to update our HTML with templating and Instantsearch.js.

1. Pushing content to your Algolia index

This is a simple three step process, as lined out in the README of the jekyll-algolia-plugin repository. First add the jekyll-algolia gem to your Gemfile, after which you run bundle install to fetch all the dependencies:

1
2
3
4
5
  # Gemfile

  group :jekyll_plugins do
    gem 'jekyll-algolia', '~> 1.0'
  end

Next, add your application_id, index_name and search_only_api_key to the Jekyll _.config.yml file:

1
2
3
4
5
6
  # _.config.yaml

  algolia:
    application_id: 'your_application_id'
    index_name: 'your_indexname'
    search_only_api_key: '2b61f303d605176b556cb377d5ef3acd'

Finally, get your private Algolia admin key (which you can find in your Algolia dashboard) and run the following to execute the indexing:

  ALGOLIA_API_KEY='your_admin_api_key' bundle exec jekyll algolia

2. Adding instantsearch.js to the front-end

For the front-end part I followed the excellent Algolia community tutorial. Instead of repeating all the documented steps here, I’ll only highlight the relative changes I made.

The integration consists of two parts:

  • A search-hits-wrapper div element where we load the search results. These results are located front and center under the navigation bar (pushing the rest of the content down).
  • The instantsearch.js dependency, template configuration and styling. All of which is located in the _includes/algolia.html file, which can be viewed in full in the source code of this site.

I made the following changes compared to the community tutorial:

  • Hide Search results by default (style=”display:none”) and don’t fire off an empty query that returns all articles. The default empty query returns all articles and to mitigate this I added a searchFunction to the instantsearch options:
1
2
3
4
5
6
7
8
9
10
11
12
13
  const search = instantsearch({
    appId: "K4MUG7LHCA",
    apiKey: "2b61f303d605176b556cb377d5ef3acd", // public read-only key
    indexName: "prod_beatletech",
    searchFunction: function (helper) {
      var searchResults = document.getElementById("search-hits-wrapper");
      if (helper.state.query === "" && searchResults.style.display === "none") {
        return;
      }
      searchResults.style.display = helper.state.query ? "block" : "none";
      helper.search();
    },
  });
  • Don’t fire off a query on every keystroke. While the default of triggering a search query with every keystroke is great in terms of responsiveness, it will also help you burn quickly through your free 10k search requests. In order to trade off query responsiveness for less api requests, I added the following queryHook with a 500ms delay:
1
2
3
4
5
6
7
8
9
10
11
12
13
  search.addWidget(
    instantsearch.widgets.searchBox({
      container: "#search-searchbar",
      placeholder: "Search into posts...",
      poweredBy: false,
      autofocus: false,
      showLoadingIndicator: true,
      queryHook(query, refine) {
        clearTimeout(timerId);
        timerId = setTimeout(() => refine(query), 500);
      },
    })
  );
  • Show “Search by Algolia” badge. If you want to make use of the free plan, they ask you in exchange that you display a “Search by Algolia” logo next to your search results. You can use the Instantsearch searchBox options Boolean flag poweredBy or if you want more flexibility, as I did, you can find different versions of their logo here and add it to the search-hits-wrapper div.
  • Turn off autofocus. Add and set the searchBox option autofocus to false if you don’t want the input search to autofocus. While I at first liked the autofocus, because the user can immediately type their search query, it turns out on mobile devices you automatically zoom in on the search input field. So I recommend turning it off.

Experience so far

I really liked the whole integration process, which was really smooth and not much work. I mean, I even went as far as to write all about it here. 🙂

One additional benefit of Algolia, which I haven’t listed yet, is gaining statistics on your site’s search queries with weekly email updates and an interactive dashboard. Helping you figure out what your readers and followers are looking for.

I am using the slightly older v2 of instantsearch.js, so at some point I will want to update to the latest version, which will decrease to javascript library size. Running PageSpeed Insights is still get a very comfortable 96/100 score, so there is no immediate need, but less is more when it comes to JS dependencies.

If my search query volume increases above the free 10k a month, then I’m happy to pay for this service. I do have one feature request for the Algolia team for the paid service, which is adding a monthly payment limit with alerting, to make sure you won’t get any surprise overcharge bill.

Anyway, so far a big thumbs up for Algolia. 👍

HN Discussion


If you like what you are reading here, consider hitting Subscribe!

Possibly related posts