In the previous article we talked about how to add search capabilities to a static site using Algolia, however the indexing process was done manually and it was not very efficient. In this article we will see how to automate the indexing process using the Algolia API.

Preparing credentials

Before we start using the API we need to gather three pieces of information:

  • APP_ID: The application ID of your Algolia account.
  • API_KEY: The API key of your Algolia account.
  • INDEX_NAME: The name of the index you want to use.

Unlike APP_ID and INDEX_NAME which can be used in your static HTML, the API_KEY should be kept secret and not be exposed to the public. Typically access keys are stored in environment variables, or in .env files. In this article we assume they are stored in environment variables.

export ALGOLIA_INDEX=xxxxxxxxxx
export ALGOLIA_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Installing the Algolia API client

The algoliasearch Node package provides a client for the Algolia API, let’s install it:

npm install algoliasearch

Indexing the data

Now that we have the credentials and the client installed, we can start indexing the data. The code is fairly simple, we just need to initialize the index and add the objects to it:

import algoliasearch from 'algoliasearch';

// Sample data
const indexData = [
		title: 'Lorem Ipsum',
		description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
		title: 'Dolor Sit Amet',
		description: 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
		title: 'Consectetur Adipiscing Elit',
		description: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.'
		title: 'Sed Do Eiusmod Tempor',
		description: 'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'

algoliasearch(process.env.ALGOLIA_APP_ID, process.env.ALGOLIA_KEY)
	.then((result) => {
		console.log('DONE!', result);

Running the script

Now that we have the script ready, we can run it and see the results in the Algolia dashboard:

node index.js

Next steps

The script can be easily adapted to index data from any data source such as a database or a CMS, in fact I made a standalone CLI tool that can be used to scan data from .md files which turned out to be very useful for indexing Astro content.