Skip to main content
The QueryRules connector provides the logic to build a custom widget that displays custom data returned by Query Rules.

Usage

import { connectQueryRules } from 'instantsearch.js/es/connectors';

const customQueryRules = connectQueryRules(
  (renderOptions, isFirstRender) => {
    const { items, widgetParams } = renderOptions;
    const { container } = widgetParams;
    
    if (items.length === 0) {
      container.innerHTML = '';
      return;
    }
    
    container.innerHTML = `
      <div class="query-rules">
        ${items.map(item => `
          <div class="rule-item">
            ${item.banner ? `
              <img src="${item.banner}" alt="Banner" />
            ` : ''}
            ${item.title ? `<h3>${item.title}</h3>` : ''}
            ${item.content ? `<p>${item.content}</p>` : ''}
          </div>
        `).join('')}
      </div>
    `;
  }
);

search.addWidgets([
  customQueryRules({
    container: document.querySelector('#query-rules'),
  }),
]);

Connector Options

trackedFilters
object
An object mapping facet names to filter tracking functions. This is used to automatically apply rule contexts based on active filters.Each function receives an array of active filter values and should return which values to track.
trackedFilters: {
  brand: (facetValues) => facetValues,
  category: (facetValues) => {
    // Only track specific categories
    return facetValues.filter(value => 
      ['electronics', 'clothing'].includes(value)
    );
  },
}
This will automatically add rule contexts in the format ais-{facetName}-{facetValue} (e.g., ais-brand-apple).
transformRuleContexts
(ruleContexts: string[]) => string[]
Function to transform the rule contexts before they are sent to Algolia.
transformRuleContexts(ruleContexts) {
  // Limit to the most important contexts
  return ruleContexts.slice(0, 5);
}
Algolia supports a maximum of 10 rule contexts per query. If you exceed this limit, they will be automatically sliced.
transformItems
(items: object[]) => object[]
Function to transform the items returned by Query Rules.
transformItems(items) {
  return items.map(item => ({
    ...item,
    title: item.title.toUpperCase(),
  }));
}

Render Options

items
Array<object>
The custom data returned by Query Rules (userData in the Algolia response).The structure depends on what you configure in your Query Rules in the Algolia dashboard.
// Example items from a promotional rule
[
  {
    title: 'Summer Sale',
    banner: 'https://example.com/banner.jpg',
    link: '/summer-sale',
  }
]
widgetParams
object
The options passed to the connector.