Building a Node.js Application Integrated with Algolia

Building a Node.js Application Integrated with Algolia

Building a Node.js Application Integrated with Algolia

In this tutorial, we'll walk through the process of creating a Node.js application integrated with Algolia, a powerful search-as-a-service platform. We'll cover setting up an Algolia account, indexing data, and querying the Algolia index from our Node.js application.

Prerequisites:

Before we begin, make sure you have the following installed on your machine:

  • Node.js (with npm)
  • Algolia account (sign up at Algolia)

Step 1: Setting up Algolia

  1. Sign in to your Algolia account or create a new one.
  2. Create a new index by navigating to the "Indices" tab and clicking on "Add index."
  3. Define the index settings, including attributes for search and display.
  4. Note down your Algolia Application ID, Admin API Key, and Index Name, as we'll need them later.

Step 2: Installing Dependencies

Create a new directory for your Node.js project and initialize it with npm:

mkdir node-algolia
cd node-algolia
npm init -y

Install the algoliasearch package, which is the official Algolia API client for Node.js:

npm install algoliasearch

Step 3: Indexing Data

In this example, let's assume we have a dataset of products. Create a file named data.json and populate it with sample product data:

[
  { "objectID": "c3e12d45-2aa1-4a1e-b4c4-550b14a579b1", "name": "Product 1", "description": "Description of Product 1", "price": 10.99 },
  { "objectID": "7ff4fc52-ec8d-4e8c-b68c-afed9f218758", "name": "Product 2", "description": "Description of Product 2", "price": 19.99 },
  { "objectID": "3ae0f152-9be7-4b78-95b1-f0b35629b30c", "name": "Product 3", "description": "Description of Product 3", "price": 29.99 },
  { "objectID": "f8749e45-5f89-4d92-81a0-75b5b1e49854", "name": "Product 4", "description": "Description of Product 4", "price": 15.99 },
  { "objectID": "6c30c8b9-1a58-420a-b5d0-dc9e2e250215", "name": "Product 5", "description": "Description of Product 5", "price": 25.99 },
  { "objectID": "9c823ea7-2a38-4629-9a7b-8f5a0eacfd5a", "name": "Product 6", "description": "Description of Product 6", "price": 35.99 },
  { "objectID": "23b2b10f-7393-49ed-bf8b-49ac4a52502b", "name": "Product 7", "description": "Description of Product 7", "price": 45.99 },
  { "objectID": "8f7b9c68-6023-4ff3-9a1a-33c79a9d6b58", "name": "Product 8", "description": "Description of Product 8", "price": 55.99 },
  { "objectID": "b7aef85c-4df8-457d-b27f-9e1a48212378", "name": "Product 9", "description": "Description of Product 9", "price": 65.99 },
  { "objectID": "e229a034-1be2-4920-8180-03f8c8d87c94", "name": "Product 10", "description": "Description of Product 10", "price": 75.99 }
]

Each product has a unique objectID generated as a UUID which is required by Algolia. You can use this JSON file for testing purposes with your Node.js scripts for indexing data into Algolia and querying the index.

Next, let's write a Node.js script to index this data into Algolia. Create a file named index.js:

const algoliasearch = require('algoliasearch');
const fs = require('fs').promises;

async function loadData() {
  try {
    const data = await fs.readFile('./data.json', 'utf8');
    return JSON.parse(data);
  } catch (err) {
    console.error('Error loading data:', err);
    return [];
  }
}

async function indexData() {
  const client = algoliasearch('YOUR_APP_ID', 'YOUR_ADMIN_API_KEY');
  const index = client.initIndex('YOUR_INDEX_NAME');

  const data = await loadData();

  try {
    const { taskID } = await index.saveObjects(data);
    console.log('Data indexed successfully:', taskID);
  } catch (err) {
    console.error('Error indexing data:', err);
  }
}

indexData();

Replace 'YOUR_APP_ID', 'YOUR_ADMIN_API_KEY', and 'YOUR_INDEX_NAME' with your Algolia Application ID, Admin API Key, and Index Name, respectively.

Run the script to index the data:

node index.js

Step 4: Querying Algolia from Node.js

Now that we've indexed our data, let's write a Node.js script to query Algolia and retrieve search results. Create a file named search.js:

const algoliasearch = require('algoliasearch');

async function search() {
  const client = algoliasearch('YOUR_APP_ID', 'YOUR_SEARCH_API_KEY');
  const index = client.initIndex('YOUR_INDEX_NAME');

  try {
    const { hits } = await index.search('Product');
    console.log('Search results:');
    hits.forEach(hit => {
      console.log('Name:', hit.name);
      console.log('Description:', hit.description);
      console.log('Price:', hit.price);
      console.log('---');
    });
  } catch (err) {
    console.error('Error searching:', err);
  }
}

search();

This version uses async/await to handle the asynchronous index.search operation. The search function is marked as async, allowing us to use await to wait for the result of the search operation. Inside the try block, we await the search operation and then iterate over the hits array to print out the product data. If an error occurs during the search, it's caught in the catch block and logged to the console.

Make sure to replace 'YOUR_APP_ID', 'YOUR_SEARCH_API_KEY', and 'YOUR_INDEX_NAME' with your actual Algolia credentials and index name.

Run the script to perform a search for the term 'Product':

node search.js

You should see the search results logged to the console.

Note: API keys should not ever be hard coded in an application. This example is not intended to be used as production code. This is only a very basic example on how to connect a very simple node application to Algolia, load some test data into the Algolia index and subsequently query the added data. Please follow best practices if you wish to build a production ready app using node.js and Algolia.

Conclusion

Congratulations! You've successfully created a Node.js application integrated with Algolia, indexed sample data, and queried the Algolia index to retrieve search results. This example provides a foundation for building more sophisticated search experiences with Algolia in your Node.js applications. Explore Algolia's documentation for advanced features and customization options to further enhance your search functionality.

Did you find this article valuable?

Support Cloud Tuned by becoming a sponsor. Any amount is appreciated!