Skip to main content
This quickstart guide will walk you through installing the Constructor.io JavaScript Client SDK and making your first search request.

Prerequisites

Before you begin, you’ll need:
  • A Constructor.io account with an API key (sign up here)
  • A modern browser or React Native environment
  • npm, yarn, or pnpm installed
You can find your API key in the Constructor.io dashboard.

Installation

1

Install the package

Install the Constructor.io JavaScript client via your preferred package manager:
npm install @constructor-io/constructorio-client-javascript
2

Import and initialize

Import the client and create an instance with your API key:
const ConstructorioClient = require('@constructor-io/constructorio-client-javascript');

const constructorio = new ConstructorioClient({
  apiKey: 'YOUR_API_KEY'
});
Never commit your API key to version control. Use environment variables in production.
3

Make your first search

Use the search module to retrieve results:
// Perform a search
constructorio.search.getSearchResults('laptop')
  .then(response => {
    console.log('Search results:', response);
    console.log('Total results:', response.response.total_num_results);
    console.log('Products:', response.response.results);
  })
  .catch(error => {
    console.error('Search error:', error);
  });

Complete Example

Here’s a complete working example that displays search results on a web page:
<!DOCTYPE html>
<html>
<head>
  <title>Constructor.io Search Demo</title>
  <style>
    body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
    #search-box { width: 100%; padding: 12px; font-size: 16px; border: 2px solid #1565fc; border-radius: 4px; }
    .result { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 4px; }
    .result:hover { background-color: #f5f5f5; cursor: pointer; }
    .result-title { font-weight: bold; color: #1565fc; margin-bottom: 5px; }
  </style>
</head>
<body>
  <h1>Product Search</h1>
  <input type="text" id="search-box" placeholder="Search for products..." />
  <div id="results"></div>

  <script src="https://unpkg.com/@constructor-io/constructorio-client-javascript@latest/dist/constructorio-client-javascript.min.js"></script>
  <script>
    // Initialize the client
    const constructorio = new ConstructorioClient({
      apiKey: 'YOUR_API_KEY'
    });

    const searchBox = document.getElementById('search-box');
    const resultsDiv = document.getElementById('results');

    // Debounce function to avoid too many requests
    let debounceTimer;
    function debounce(func, delay) {
      return function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => func.apply(this, arguments), delay);
      };
    }

    // Search function
    async function performSearch(query) {
      if (!query.trim()) {
        resultsDiv.innerHTML = '';
        return;
      }

      try {
        const response = await constructorio.search.getSearchResults(query);
        displayResults(response.response.results);
      } catch (error) {
        console.error('Search error:', error);
        resultsDiv.innerHTML = '<p>Error loading results. Please try again.</p>';
      }
    }

    // Display results
    function displayResults(results) {
      if (results.length === 0) {
        resultsDiv.innerHTML = '<p>No results found.</p>';
        return;
      }

      resultsDiv.innerHTML = results.map(item => `
        <div class="result" onclick="handleClick('${item.data.id}', '${item.value}')">
          <div class="result-title">${item.value}</div>
          <div>${item.data.description || ''}</div>
          <div style="color: #666; margin-top: 5px;">$${item.data.price || 'N/A'}</div>
        </div>
      `).join('');
    }

    // Handle result click
    function handleClick(itemId, itemName) {
      // Track the click event
      constructorio.tracker.trackSearchResultClick({
        itemName: itemName,
        customerId: itemId
      });
      
      console.log('Clicked:', itemName);
      // Navigate to product page or show details
    }

    // Add event listener with debounce
    searchBox.addEventListener('input', debounce((e) => {
      performSearch(e.target.value);
    }, 300));
  </script>
</body>
</html>

Using async/await

For cleaner code, use async/await syntax:
async function searchProducts(query) {
  try {
    const response = await constructorio.search.getSearchResults(query, {
      resultsPerPage: 20,
      page: 1
    });
    
    return response.response.results;
  } catch (error) {
    console.error('Search failed:', error);
    throw error;
  }
}

// Usage
searchProducts('laptop').then(results => {
  console.log(`Found ${results.length} products`);
});

Adding Filters and Sorting

Enhance your search with filters and sorting:
const response = await constructorio.search.getSearchResults('laptop', {
  filters: {
    brand: ['Apple', 'Dell'],
    price: { min: 500, max: 2000 }
  },
  sortBy: 'price',
  sortOrder: 'ascending',
  resultsPerPage: 24,
  page: 1
});

Tracking Events

Track user interactions to improve search results over time:
// Track when a user clicks a search result
constructorio.tracker.trackSearchResultClick({
  itemName: 'MacBook Pro 16"',
  customerId: 'product-123',
  resultId: response.result_id
});

// Track when a user adds to cart
constructorio.tracker.trackConversion({
  itemName: 'MacBook Pro 16"',
  customerId: 'product-123',
  revenue: 2499.99
});

// Track when a user completes a purchase
constructorio.tracker.trackPurchase({
  items: [
    { itemName: 'MacBook Pro 16"', customerId: 'product-123', price: 2499.99 }
  ],
  revenue: 2499.99,
  orderId: 'order-456'
});

Next Steps

Now that you have the basics working, explore more features:

Client Configuration

Learn about all available configuration options

Search Guide

Advanced search features and best practices

Autocomplete

Add real-time search suggestions

Tracking Events

Understand the full tracking system

Troubleshooting

CORS Errors

If you encounter CORS errors, ensure your domain is whitelisted in your Constructor.io dashboard.

Session Management

The client automatically manages session IDs via the @constructor-io/constructorio-id package. No manual cookie management is needed in browser environments.

React Native

For React Native apps, see the React Native guide for additional setup requirements.

Get Help

Build docs developers (and LLMs) love