Claude
Skills
Sign in
Back

headless-intelligent-search

Included with Lifetime
$97 forever

Apply when implementing search functionality, faceted navigation, or autocomplete in a headless VTEX storefront. Covers product_search, autocomplete_suggestions, facets, banners, correction_search, and top_searches endpoints, plus analytics event collection. Use for any custom frontend that integrates VTEX Intelligent Search API for product discovery and search result rendering.

Web Dev

What this skill does


# Intelligent Search API Integration

## When this skill applies

Use this skill when implementing product search, category browsing, autocomplete, or faceted filtering in a headless VTEX storefront.

- Building a search results page with product listings
- Implementing faceted navigation (category, brand, price, color filters)
- Adding autocomplete suggestions to a search input
- Wiring up search analytics events for Intelligent Search ranking

Do not use this skill for:
- BFF architecture and API routing decisions (use [`headless-bff-architecture`](../headless-bff-architecture/SKILL.md))
- Checkout or cart API integration (use [`headless-checkout-proxy`](../headless-checkout-proxy/SKILL.md))
- Caching strategy and TTL configuration (use [`headless-caching-strategy`](../headless-caching-strategy/SKILL.md))

## Decision rules

- Call Intelligent Search **directly from the frontend** — it is the ONE exception to the "everything through BFF" rule. It is fully public and requires no authentication.
- Do NOT proxy Intelligent Search through the BFF unless you have a specific need (e.g., server-side rendering). Proxying adds latency on a high-frequency operation.
- Always use the API's `sort` parameter and facet paths for filtering and sorting — never re-sort or re-filter results client-side.
- Always include `page` and `locale` parameters in every search request.
- When paginating beyond the first page, always reuse the `operator` and `fuzzy` values returned by the API from the first page — the API decides these values dynamically based on the search query.
- Always send analytics events to the Intelligent Search Events API — without them, search ranking degrades over time.

Search endpoints overview:

| Endpoint | Method | Purpose |
|---|---|---|
| `/product_search/{facets}` | GET | Search products by query and/or facets |
| `/facets/{facets}` | GET | Get available filters for a query |
| `/autocomplete_suggestions` | GET | Get term and product suggestions while typing |
| `/top_searches` | GET | Get the 10 most popular search terms |
| `/correction_search` | GET | Get spelling correction for a misspelled term |
| `/search_suggestions` | GET | Get suggested terms similar to the search term |
| `/banners/{facets}` | GET | Get banners configured for a query |

Facet combination rules:
- **Same facet type → OR (union)**: Selecting "Red" and "Blue" for color returns products matching either color
- **Different facet types → AND (intersection)**: Selecting "Red" color and "Nike" brand returns only red Nike products

## Hard constraints

### Constraint: MUST send analytics events to Intelligent Search Events API

Every headless search implementation MUST send analytics events to the Intelligent Search Events API - Headless. At minimum, send search impression events when results are displayed and click events when a product is selected from search results.

**Why this matters**

Intelligent Search uses machine learning to rank results based on user behavior. Without analytics events, the search engine has no behavioral data and cannot personalize or optimize results. Over time, search quality degrades compared to stores that send events. Additionally, VTEX Admin search analytics dashboards will show no data.

**Detection**

If a search implementation renders results from Intelligent Search but has no calls to `sp.vtex.com/event-api` or the Intelligent Search Events API → STOP immediately. Analytics events must be implemented alongside search.

**Correct**

```typescript
// search-analytics.ts — sends events to Intelligent Search Events API
const ACCOUNT_NAME = "mystore";
const EVENTS_URL = `https://sp.vtex.com/event-api/v1/${ACCOUNT_NAME}/event`;

interface SearchEvent {
  type: "search.query" | "search.click" | "search.add_to_cart";
  text: string;
  misspelled: boolean;
  match: number;
  operator: string;
  locale: string;
  agent: string;
  url: string;
  products?: Array<{ productId: string; position: number }>;
}

export async function sendSearchEvent(event: SearchEvent): Promise<void> {
  try {
    await fetch(EVENTS_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(event),
      keepalive: true, // ensures event is sent even during navigation
    });
  } catch (error) {
    // Analytics failures should not break the UI
    console.warn("Failed to send search event:", error);
  }
}

// Usage: call after rendering search results
function onSearchResultsRendered(query: string, products: Product[]): void {
  sendSearchEvent({
    type: "search.query",
    text: query,
    misspelled: false,
    match: products.length,
    operator: "and",
    locale: "en-US",
    agent: "my-headless-store",
    url: window.location.href,
    products: products.map((p, i) => ({
      productId: p.productId,
      position: i + 1,
    })),
  });
}
```

**Wrong**

```typescript
// Search works but NO analytics events are sent — search ranking degrades
async function searchProducts(query: string): Promise<Product[]> {
  const response = await fetch(
    `https://mystore.vtexcommercestable.com.br/api/io/_v/api/intelligent-search/product_search/?query=${query}&locale=en-US`
  );
  const data = await response.json();
  return data.products;
  // Missing: no call to sendSearchEvent() — Intelligent Search cannot learn
}
```

---

### Constraint: MUST persist operator and fuzzy values across pagination

When paginating search results beyond the first page, you MUST reuse the `operator` and `fuzzy` values returned by the API in the first page response. The first request should send these as `null`, but subsequent pages must use the values from the initial response.

**Why this matters**

The Intelligent Search API dynamically determines the best `operator` and `fuzzy` values based on the query and available results. Using fixed values (like always `operator: "or"` or `fuzzy: "0"`) or forgetting to pass them on subsequent pages causes inconsistent results — page 2 may show products that don't match the criteria from page 1, or may miss valid results. This is a common source of poor search experience but is not well-documented by VTEX.

**Detection**

If pagination implementation does not store and reuse `operator`/`fuzzy` from the first page response → STOP immediately. Subsequent pages will return inconsistent results.

**Correct**

```typescript
// Properly manages operator/fuzzy across pagination
interface SearchState {
  query: string;
  page: number;
  count: number;
  locale: string;
  facets?: string;
  operator: string | null; // null for first page, then persisted
  fuzzy: string | null;    // null for first page, then persisted
}

async function searchProducts(state: SearchState): Promise<SearchResponse> {
  const { query, page, count, locale, facets = "", operator, fuzzy } = state;

  const params = new URLSearchParams({
    query,
    locale,
    page: String(page),
    count: String(count),
  });

  // Only add operator/fuzzy if this is not the first page
  if (operator !== null) params.set("operator", operator);
  if (fuzzy !== null) params.set("fuzzy", fuzzy);

  const baseUrl = `https://${ACCOUNT}.vtexcommercestable.com.br`;
  const facetPath = facets ? `/${facets}` : "";
  const url = `${baseUrl}/api/io/_v/api/intelligent-search/product_search${facetPath}?${params}`;

  const response = await fetch(url);
  const data = await response.json();

  // Store operator/fuzzy from response for next page
  if (page === 0) {
    state.operator = data.operator;
    state.fuzzy = data.fuzzy;
  }

  return data;
}

// Usage: first page
const state: SearchState = {
  query: "running shoes",
  page: 0,
  count: 24,
  locale: "en-US",
  operator: null, // API will decide
  fuzzy: null,    // API will decide
};

const firstPage = await searchProducts(state);

// Usage: subsequent pages
state.page = 1;
const secondPage = await searchProducts(state); // reuses operator/fuzzy
```

**Wrong**

```typescript
// Using fixed oper

Related in Web Dev