### Run Development Environment
Source: https://github.com/vtex-apps/search/blob/master/README.md
Use this command to install dependencies and set up the development environment for the VTEX Search app.
```sh
make dev # yarn install (root + react) + vtex setup
```
--------------------------------
### Example Usage of AdvertisementOptions
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/3-types.md
Demonstrates how to pass AdvertisementOptions to the suggestionProducts method for controlling sponsored content.
```typescript
const result = await biggyClient.suggestionProducts(
'laptop',
undefined,
undefined,
false,
'default',
false,
undefined,
5,
undefined,
{
showSponsored: true,
sponsoredCount: 2,
advertisementPlacement: 'autocomplete'
}
)
```
--------------------------------
### ProductListContext Provider Setup
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Import and use the ProductListProvider from vtex.product-list-context to wrap product-list sections and provide context to descendant components.
```typescript
import { ProductListContext } from 'vtex.product-list-context'
const { ProductListProvider } = ProductListContext
```
--------------------------------
### Search App Configuration Example
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/0-overview.md
Shows a sample configuration for the 'search-bar' block within a Store Framework `manifest.json` file, including properties like `maxTopSearches` and `customBreakpoints`.
```json
{
"search-bar": {
"blocks": ["autocomplete-result-list.v2"],
"props": {
"maxTopSearches": 10,
"maxHistory": 5,
"maxSuggestedProducts": 3,
"productLayout": "HORIZONTAL",
"customBreakpoints": {
"md": { "width": 768, "maxSuggestedProducts": 2 }
}
}
}
}
```
--------------------------------
### ISearchProduct Usage Example
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/3-types.md
Demonstrates how to use the ISearchProduct interface with BiggyClient to fetch and process product suggestions. Logs product names, prices, and image URLs.
```typescript
const result = await biggyClient.suggestionProducts('laptop', undefined, undefined)
const products: ISearchProduct[] = result.data.productSuggestions.products
products.forEach(product => {
console.log(`${product.name} - ${product.priceText}`)
product.images.forEach(img => console.log(img.value))
})
```
--------------------------------
### Configure Desktop Search Result Layout
Source: https://github.com/vtex-apps/search/blob/master/docs/README.md
Set up the desktop search result layout, including the order of child blocks and pagination behavior. This example defines rows for 'did-you-mean', 'search-suggestions', and 'search-banner'.
```json
{
"search-result-layout.desktop": {
"children": [
"flex-layout.row#did-you-mean",
"flex-layout.row#suggestion",
"flex-layout.row#banner-one",
"flex-layout.row#result"
],
"props": {
"pagination": "show-more",
"preventRouteChange": true,
"mobileLayout": {
"mode1": "small",
"mode2": "normal"
}
}
},
"flex-layout.row#did-you-mean": {
"children": ["did-you-mean"]
},
"flex-layout.row#suggestion": {
"children": ["search-suggestions"]
},
"flex-layout.row#banner-one": {
"children": ["search-banner#one"]
},
"search-banner#one": {
"props": {
"area": "one",
"blockClass": "myBanner",
"horizontalAlignment": "center"
}
}
}
```
--------------------------------
### CSS Handles Integration Example
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
This TypeScript code shows how to integrate with VTEX's CSS Handles. It defines an array of CSS handles, uses the 'useCssHandles' hook to get the mapped class names, and applies one of them to an element.
```typescript
const CSS_HANDLES = ['myClass', 'myOtherClass']
const handles = useCssHandles(CSS_HANDLES)
className={handles.myClass}
```
--------------------------------
### Configure Autocomplete Result List
Source: https://github.com/vtex-apps/search/blob/master/docs/README.md
Declare a theme block to be rendered among autocomplete features. This example shows how to include the 'product-summary' block.
```json
{
"autocomplete-result-list.v2": {
"blocks": ["product-summary"]
}
}
```
--------------------------------
### Example Usage of Item Interface
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/3-types.md
Illustrates creating an Item object for use in autocomplete suggestion lists, including a label, value, link, and an optional icon.
```typescript
const item: Item = {
label: 'shoes',
value: 'shoes',
link: '/shoes?map=ft',
icon:
}
```
--------------------------------
### Item Data Structure Example
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/INDEX.md
Illustrates the structure of an 'Item' object used for rendering list items in the autocomplete dropdown. Includes an example of nested 'attributes'.
```typescript
const item: Item = {
label: 'shoes',
value: 'shoes',
link: '/shoes?map=ft',
attributes: [
{
groupValue: 'shoes',
value: 'red',
label: 'Red',
link: '/shoes/red?map=ft,color',
key: 'color'
}
]
}
```
--------------------------------
### Import AutocompleteSearchSuggestions GraphQL Query
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Import the QueryAutocompleteSearchSuggestions GraphQL query from vtex.store-resources. This query is used to get search suggestions.
```typescript
import suggestionSearches from 'vtex.store-resources/QueryAutocompleteSearchSuggestions'
```
--------------------------------
### Utility Functions Reference
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/INDEX.md
Comprehensive guide to all utility functions used by the search app, useful for integrating the search app or working with search utilities.
```APIDOC
## Utility Functions Reference
### Description
This reference details the utility functions provided by the VTEX Search app. These functions cover various aspects like search history management, cookie operations, term encoding, string manipulation, price formatting, pixel tracking, session management, logging, and compatibility layer functions.
### Categories
**Search History Utilities:**
- `readSearchHistory()`: Reads search history from a cookie.
- `prependSearchHistory()`: Adds or updates a search history entry.
**DOM Utilities:**
- `getCookie()`, `setCookie()`: For managing browser cookies.
- `hasClass()`, `isDescendant()`, `hasSomeParentTheClass()`: For DOM element queries.
**Term Encoding:**
- `encodeSearchTerm()`: Encodes search terms to be URL-safe.
**String Utilities:**
- `removeBaseUrl()`, `decodeUrlString()`, `encodeUrlString()`: For URL string manipulation.
**Number Utilities:**
- `formatPrice()`: Formats prices according to store preferences.
**Pixel Tracking:**
- `handleProductClick()`, `handleItemClick()`, `handleSeeAllClick()`, `handleAutocompleteSearch()`: Emits analytics events.
**Session Utilities:**
- `getSession()`: Fetches shipping options from the server.
**Logging:**
- `logError()`: Sends errors to a remote logging service.
**Compatibility Layer:**
- `makeFetchMore()`, `makeRefetch()`
- `fromAttributesToFacets()`
- `convertOrderBy()`
- `convertURLToAttributePath()`: For integration with `store-components`.
```
--------------------------------
### Search History Cookie Example
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/0-overview.md
Illustrates the format and an example of the 'biggy-search-history' cookie, which stores user search history as comma-separated, percent-encoded terms.
```string
- Format: Comma-separated, percent-encoded search terms
- Limit: Default 5 entries (configurable)
- Scope: Root path (/"), session cookie
- Example: `shoes%2Fsneakers%2Cboots%2Cwinter%20coats`
Decoded: `['shoes/sneakers', 'boots', 'winter coats']`
```
--------------------------------
### IProductSku Interface
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/3-types.md
Defines the structure for SKU (variant) data associated with a product. Includes pricing, installment, and seller information.
```typescript
interface IProductSku {
id: string
references: string
price: number
oldPrice: number
installment: {
count: number
value: number
}
sellers: Array<{
id: string
price: number
oldPrice: number
installment: {
count: number
value: number
}
}>
}
```
--------------------------------
### Term Encoding Example
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/0-overview.md
Demonstrates the use of the `encodeSearchTerm()` function to ensure search terms are URL-safe, making history items and typed searches produce consistent URLs.
```typescript
encodeSearchTerm('shoes/sneakers') // 'shoes%2Fsneakers'
encodeSearchTerm('shoes%2Fsneakers') // 'shoes%2Fsneakers' (idempotent)
```
--------------------------------
### Autocomplete Result List v2 Theme Manifest Configuration
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/2-blocks.md
Configure the Autocomplete Result List v2 component within your theme's manifest. This example sets various props including max items, visibility of titles, history prioritization, and custom breakpoints for different screen sizes.
```json
{
"search-bar": {
"blocks": ["autocomplete-result-list.v2"],
"props": {
"openAutocompleteOnFocus": true,
"maxTopSearches": 8,
"maxHistory": 5,
"maxSuggestedProducts": 4,
"hideTitles": false,
"historyFirst": false,
"customBreakpoints": {
"md": {
"width": 768,
"maxSuggestedProducts": 2
},
"lg": {
"width": 1024,
"maxSuggestedProducts": 3
}
}
}
}
}
```
--------------------------------
### IElasticProductInstallment Interface Definition
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/3-types.md
Defines the structure for installment payment information. Includes count, value, interest status, and formatted value text. Part of the ISearchProduct interface.
```typescript
export interface IElasticProductInstallment {
count: number
value: number
interest: boolean
valueText: string
}
```
--------------------------------
### Biggy Search History Cookie Example
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
The 'biggy-search-history' cookie stores a comma-separated list of percent-encoded search terms. This example shows how search terms like 'shoes/sneakers', 'boots', and 'winter coats' are stored.
```text
biggy-search-history=shoes%2Fsneakers%2Cboots%2Cwinter%20coats
```
--------------------------------
### BiggyClient API Usage
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/INDEX.md
Demonstrates how to initialize and use the BiggyClient for various search queries, including top searches, suggestions, and product searches. Also shows how to manage search history.
```typescript
const client = new BiggyClient(apolloClient)
const topSearches = await client.topSearches()
const suggestions = await client.suggestionSearches('shoes')
const products = await client.suggestionProducts('shoes', undefined, undefined, false, 'default', false, 'price:asc', 5)
const history = client.searchHistory()
client.prependSearchHistory('winter coats')
```
--------------------------------
### Instantiate BiggyClient
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/1-biggy-client.md
Shows how to create an instance of BiggyClient using an Apollo Client. This is useful for host apps that need direct access to search functionalities.
```typescript
import ApolloClient from 'apollo-client'
import BiggyClient from 'vtex.search/BiggyClient'
const apolloClient = new ApolloClient({ /* config */ })
const biggyClient = new BiggyClient(apolloClient)
const topSearches = await biggyClient.topSearches()
```
--------------------------------
### Importing BiggyClient in Host Apps
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/0-overview.md
Demonstrates how to import and use the BiggyClient in a host application. Requires an Apollo Client instance for initialization.
```typescript
import { BiggyClient } from 'vtex.search'
const client = new BiggyClient(apolloClient)
const topSearches = await client.topSearches()
```
--------------------------------
### Get Cookie Value
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Reads a specific cookie's value from the browser. Returns the decoded value or null if the cookie is not found.
```typescript
export function getCookie(name: string): string | null
const variant = getCookie('sp-variant')
const sessionId = getCookie('my_session')
```
--------------------------------
### ProductListContext
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Manages product list state and pagination.
```APIDOC
## ProductListContext
### Description
Manages product list state and pagination.
### Usage
Wrap product-list sections to provide context to descendant product components.
```
--------------------------------
### makeRefetch
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Wraps Apollo's `refetch` function to adapt `from`/`to` parameters to `page` and `count` for search result pagination.
```APIDOC
## makeRefetch()
### Description
Wraps Apollo's `refetch` to translate `from`/`to` to `page` and `count`.
### Signature
```typescript
export const makeRefetch = (refetch: Refetch): Refetch
```
```
--------------------------------
### Execute AutocompleteSearchSuggestions GraphQL Query
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Execute the QueryAutocompleteSearchSuggestions GraphQL query with a 'fullText' variable to get suggestions for a specific search term.
```typescript
const result = await client.query({
query: suggestionSearches,
variables: { fullText: 'shoes' }
})
```
--------------------------------
### Add Search App to Theme Dependencies
Source: https://github.com/vtex-apps/search/blob/master/docs/Banner.md
Ensure the `vtex.search` app is included in your theme's `manifest.json` dependencies.
```json
"dependencies": {
"vtex.search": "2.x"
}
```
--------------------------------
### BiggyClient suggestionProducts Method
Source: https://github.com/vtex-apps/search/blob/master/docs/data-model.md
Retrieves product suggestions based on a term and optional filters. It issues QuerySuggestionProducts and forwards specific cookies and headers. Adding new optional parameters is safe, but removing or reordering existing ones is a breaking change.
```typescript
suggestionProducts(
term: string,
attributeKey?: string,
attributeValue?: string,
productOrigin = false,
simulationBehavior: 'default' | 'skip' | null = 'default',
hideUnavailableItems = false,
orderBy?: string,
count?: number,
shippingOptions?: string[],
advertisementOptions?: AdvertisementOptions
): Promise>
```
--------------------------------
### Main Entry Point: react/index.ts
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/0-overview.md
Exports the BiggyClient class from the utils directory. This client can be imported by host applications.
```typescript
import BiggyClient from './utils/biggy-client'
export default {
BiggyClient,
}
```
--------------------------------
### Fetch Autocomplete Suggestions
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/1-biggy-client.md
Gets search suggestions based on a given term. The response structure is similar to top searches, providing terms that match the input.
```typescript
const result = await biggyClient.suggestionSearches('shoes')
const suggestions = result.data.autocompleteSearchSuggestions.searches
suggestions.forEach(suggestion => {
console.log(suggestion.term)
})
```
--------------------------------
### Import SuggestionProducts GraphQL Query
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Import the QuerySuggestionProducts GraphQL query from vtex.store-resources. This query is used to fetch product suggestions based on a search term and various filters.
```typescript
import suggestionProducts from 'vtex.store-resources/QuerySuggestionProducts'
```
--------------------------------
### Store Framework Blocks
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/INDEX.md
Complete documentation for the four exported Store Framework blocks used to configure blocks in your theme or understand their props and behavior.
```APIDOC
## Store Framework Blocks Reference
### Description
This section details the four exported Store Framework blocks available in the VTEX Search app. These blocks are used for configuring search-related UI components within a VTEX theme.
### Blocks
- **autocomplete-result-list.v2**
- **Purpose**: The main autocomplete dropdown component.
- **Props**: `maxTopSearches`, `maxHistory`, `productLayout`, etc.
- **Behavior**: Handles user input, displays suggestions, and product previews.
- **Styling**: Provides CSS handles for customization.
- **Usage**: Examples provided in the full documentation.
- **did-you-mean**
- **Purpose**: Displays a spelling correction prompt to the user.
- **search-suggestions**
- **Purpose**: Shows related search terms to the user.
- **search-banner**
- **Purpose**: Displays contextual banners based on search results.
### Other Details
- Block composition requirements
- Internationalization (i18n) keys
- Higher-order component wrappers
```
--------------------------------
### Publish a New Release
Source: https://github.com/vtex-apps/search/blob/master/README.md
Command to publish a new version of the Search app. Use 'patch', 'stable', 'minor', or 'major' to specify the release type. The 'prereleasy' hook runs automatically.
```sh
vtex release patch stable # or minor / major
```
--------------------------------
### BiggyClient - suggestionProducts
Source: https://github.com/vtex-apps/search/blob/master/docs/data-model.md
Retrieves product suggestions based on a search term and optional filters. It issues a `vtex.store-resources/QuerySuggestionProducts` Apollo query with various parameters, including dynamic ones like `variant` from cookies.
```APIDOC
## suggestionProducts(term, attributeKey, attributeValue, productOrigin, simulationBehavior, hideUnavailableItems, orderBy, count, shippingOptions, advertisementOptions)
### Description
Issues `vtex.store-resources/QuerySuggestionProducts` with named variables plus specific configurations like `variant` from `sp-variant` cookie and `origin` set to `'autocomplete'`. Uses `fetchPolicy: 'network-only'`.
### Method
`suggestionProducts(
term: string,
attributeKey?: string,
attributeValue?: string,
productOrigin = false,
simulationBehavior: 'default' | 'skip' | null = 'default',
hideUnavailableItems = false,
orderBy?: string,
count?: number,
shippingOptions?: string[],
advertisementOptions?: AdvertisementOptions
): Promise>`
### Parameters
#### Path Parameters
- **term** (string) - Required - The search term to get product suggestions for.
- **attributeKey** (string) - Optional - The key of the attribute to filter by.
- **attributeValue** (string) - Optional - The value of the attribute to filter by.
- **productOrigin** (boolean) - Optional - Defaults to `false`.
- **simulationBehavior** ('default' | 'skip' | null) - Optional - Defaults to `'default'`. Controls simulation behavior.
- **hideUnavailableItems** (boolean) - Optional - Defaults to `false`. Whether to hide unavailable items.
- **orderBy** (string) - Optional - The field to order the results by.
- **count** (number) - Optional - The number of products to return.
- **shippingOptions** (string[]) - Optional - Shipping options to consider.
- **advertisementOptions** (AdvertisementOptions) - Optional - Options for advertisements.
### Request Body
(Not applicable, parameters are passed via method arguments and cookies)
### Response Example
```json
{
"data": {
"productSuggestions": {
"products": [
{
"productId": "12345",
"productName": "Example Product",
"link": "/example-product/p"
}
],
"count": 10,
"misspelled": false,
"operator": "AND",
"searchId": "some-search-id"
}
}
}
```
```
--------------------------------
### Verified Development Commands
Source: https://github.com/vtex-apps/search/blob/master/AGENTS.md
A set of verified commands for local development, linting, formatting, and linking the VTEX app. These commands streamline the development workflow.
```sh
make dev # yarn install (root + react) + vtex setup
make lint # eslint --ext js,jsx,ts,tsx . (no --fix)
make format-check # prettier --check
make check # alias for lint (no test runner configured today)
make link # vtex link (uses active VTEX account/workspace)
make run # alias for make link
```
--------------------------------
### ProductContext
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Provides product data to child components (price, SKU selection, etc.).
```APIDOC
## ProductContext
### Description
Provides product data to child components (price, SKU selection, etc.).
### Usage
```typescript
import { ProductContextProvider } from 'vtex.product-context'
{/* child components like SellingPrice, ListPrice */}
```
```
--------------------------------
### Add Search App Dependency
Source: https://github.com/vtex-apps/search/blob/master/docs/DidYouMean.md
Ensure the 'vtex.search' app is included in your theme's manifest.json dependencies.
```json
{
"dependencies": {
"vtex.search": "2.x"
}
}
```
--------------------------------
### ProductContextProvider Usage
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Wrap child components with ProductContextProvider from vtex.product-context, passing the product and query details to provide product data.
```typescript
import { ProductContextProvider } from 'vtex.product-context'
{/* child components like SellingPrice, ListPrice */}
```
--------------------------------
### Run Linting and Formatting Checks
Source: https://github.com/vtex-apps/search/blob/master/README.md
Commands to check code quality and formatting. 'make lint' runs eslint without auto-fix, and 'make format-check' uses prettier to check formatting.
```sh
make lint # eslint, no auto-fix
```
```sh
make format-check # prettier --check
```
```sh
make check # alias for lint (no Jest/Mocha runner is configured)
```
--------------------------------
### handleProductClick()
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Emits a pixel event when a product is clicked in the autocomplete dropdown, providing product details and search context.
```APIDOC
## handleProductClick()
### Description
Emits a pixel event when a product is clicked in the autocomplete dropdown.
### Signature
```typescript
export function handleProductClick(
push: (data: any) => void,
page: string
): (productId: string, position: number, term: string) => void
```
### Parameters
#### Path Parameters
- **push** (`(data: any) => void`) - Required - Pixel-manager push function (from `vtex.pixel-manager` context)
- **page** (string) - Required - Current page name for context
### Returns
A function `(productId, position, term) => void` that emits the event.
### Event Payload
```typescript
{
page: string,
event: 'autocomplete',
eventType: 'product_click',
product: {
productId: string,
position: number
},
term: string
}
```
### Usage
```typescript
const onProductClick = handleProductClick(push, 'store.search')
onProductClick('product-123', 0, 'shoes')
```
```
--------------------------------
### Execute SuggestionProducts GraphQL Query with Variables
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Execute the QuerySuggestionProducts GraphQL query with a comprehensive set of variables, including search term, facets, sorting, and advertisement options.
```typescript
const result = await client.query({
query: suggestionProducts,
variables: {
fullText: 'shoes',
facetKey: 'color',
facetValue: 'red',
productOriginVtex: false,
simulationBehavior: 'default',
hideUnavailableItems: false,
orderBy: 'price:asc',
count: 5,
shippingOptions: ['standard'],
variant: 'A',
origin: 'autocomplete',
advertisementOptions: {
showSponsored: true,
sponsoredCount: 2
}
}
})
```
--------------------------------
### withDevice
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Higher-order component that injects device detection info.
```APIDOC
## withDevice (vtex.device-detector)
### Description
Higher-order component that injects device detection info.
### Usage
```typescript
const EnhancedComponent = withDevice(MyComponent)
```
### Injected Props
```typescript
isMobile: boolean
isTablet: boolean
isDesktop: boolean
```
```
--------------------------------
### withRuntime
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Higher-order component that injects runtime context via props.
```APIDOC
## withRuntime (Custom)
### Description
Higher-order component that injects runtime context via props.
### Location
`react/utils/withRuntime.tsx`
### Usage
```typescript
function MyComponent(props: { runtime: { page: string; rootPath?: string } }) {
// ...
}
export default withRuntime(MyComponent)
```
```
--------------------------------
### suggestionProducts()
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/1-biggy-client.md
Fetches product suggestions for a given search term. Supports filtering by attributes, controlling product origin (VTEX catalog vs. Biggy), simulation behavior, and sorting. Useful for populating autocomplete product tiles.
```APIDOC
## Method: suggestionProducts()
### Description
Fetches product suggestions for a search term, with optional filtering and ordering. This is the primary method for populating autocomplete product tiles.
### Signature
```typescript
public async suggestionProducts(
term: string,
attributeKey?: string,
attributeValue?: string,
productOrigin: boolean = false,
simulationBehavior: 'default' | 'skip' | null = 'default',
hideUnavailableItems: boolean = false,
orderBy?: string,
count?: number,
shippingOptions?: string[],
advertisementOptions?: AdvertisementOptions
): Promise>
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Table
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| term | `string` | Yes | — | The search term to query |
| attributeKey | `string` | No | `undefined` | Facet key to filter results (e.g., "color") |
| attributeValue | `string` | No | `undefined` | Facet value to filter results (e.g., "red") |
| productOrigin | `boolean` | No | `false` | If `true`, queries VTEX catalog; if `false`, queries Biggy |
| simulationBehavior | `'default' | 'skip' | null` | No | `'default'` | `'default'` to include pricing/promotions; `'skip'` for faster results without simulation |
| hideUnavailableItems | `boolean` | No | `false` | If `true`, excludes out-of-stock products |
| orderBy | `string` | No | `undefined` | Sort order (e.g., "price:asc", "orders:desc") |
| count | `number` | No | `undefined` | Maximum number of products to return |
| shippingOptions | `string[]` | No | `undefined` | Array of shipping options to filter by |
| advertisementOptions | `AdvertisementOptions` | No | `undefined` | Ad placement settings |
### Returns
`Promise>`
The promise resolves to:
```typescript
interface IProductsOutput {
products: ISearchProduct[]
count: number
misspelled: boolean
operator: string
searchId: string
}
```
Where `ISearchProduct` contains product name, price, images, SKUs, and attributes (see `types.md`).
**Throws:** Rejects if the Apollo query fails (network error, GraphQL error).
### Usage Example
```typescript
const result = await biggyClient.suggestionProducts(
'laptop',
undefined,
undefined,
false,
'default',
false,
'price:asc',
5,
['standard-shipping'],
{
showSponsored: true,
sponsoredCount: 2,
advertisementPlacement: 'autocomplete'
}
)
const products = result.data.productSuggestions.products
console.log(`Found ${result.data.productSuggestions.count} total matches`)
console.log(`Showing ${products.length} products`)
console.log(`Query was misspelled: ${result.data.productSuggestions.misspelled}`)
```
```
--------------------------------
### useCssHandles
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Hook for accessing CSS handles for component styling.
```APIDOC
## useCssHandles (vtex.css-handles)
### Description
Hook for accessing CSS handles for component styling.
### Usage
```typescript
import { useCssHandles } from 'vtex.css-handles'
const CSS_HANDLES = ['myHandle', 'anotherHandle']
const handles = useCssHandles(CSS_HANDLES)
// Use: className={handles.myHandle}
```
```
--------------------------------
### Fetch Product Suggestions with Filtering and Ordering
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/1-biggy-client.md
Use this method to retrieve product suggestions based on a search term. It supports filtering by attributes, controlling simulation behavior, hiding unavailable items, sorting, limiting results, and filtering by shipping options and ad placements.
```typescript
const result = await biggyClient.suggestionProducts(
'laptop',
undefined,
undefined,
false,
'default',
false,
'price:asc',
5,
['standard-shipping'],
{
showSponsored: true,
sponsoredCount: 2,
advertisementPlacement: 'autocomplete'
}
)
const products = result.data.productSuggestions.products
console.log(`Found ${result.data.productSuggestions.count} total matches`)
console.log(`Showing ${products.length} products`)
console.log(`Query was misspelled: ${result.data.productSuggestions.misspelled}`)
```
--------------------------------
### useQuery
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Apollo hook for executing GraphQL queries.
```APIDOC
## useQuery (react-apollo)
### Description
Apollo hook for executing GraphQL queries.
### Usage
```typescript
import { useQuery } from 'react-apollo'
const { loading, data, error } = useQuery(QUERY, {
variables: { /* ... */ }
})
```
```
--------------------------------
### Import and Usage of QuerySearchSuggestions
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Import the QuerySearchSuggestions module and use it within a client query to retrieve search suggestions for a given text.
```typescript
import searchSuggestionsQuery from 'vtex.store-resources/QuerySearchSuggestions'
const result = await client.query({
query: searchSuggestionsQuery,
variables: { fullText: 'shoes' }
})
```
--------------------------------
### getSession
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Fetches the current session context, including shipping options and other public data. It can optionally take a root path prefix.
```APIDOC
## getSession()
### Description
Fetches the current session context, including shipping options and other public data.
### Signature
```typescript
const getSession = async (rootPath?: string): Promise | null>
```
### Parameters
#### Function Parameters
- **rootPath** (`string`) - Optional - Optional root path prefix for the API call
### Returns
`Promise | null>`
- Resolves to an array of session items if successful.
- Resolves to `null` if no shipping options are available.
- Rejects on network error or JSON parse error.
### Usage
```typescript
const session = await getSession()
if (session) {
const shippingOptions = session.map(item => item.value)
console.log(shippingOptions)
}
// With root path
const sessionWithPath = await getSession('/my-store')
```
```
--------------------------------
### handleAutocompleteSearch
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Emits a pixel event when the user searches and term suggestions are loaded. It takes several parameters to describe the search context.
```APIDOC
## handleAutocompleteSearch()
### Description
Emits a pixel event when the user searches (term suggestions are loaded).
### Signature
```typescript
export function handleAutocompleteSearch(
push: (data: any) => void,
operator: string,
misspelled: boolean,
count: number,
term: string
): void
```
### Parameters
#### Function Parameters
- **push** (`(data: any) => void`) - Required - Pixel-manager push function
- **operator** (`string`) - Required - Search operator (e.g., "and", "or")
- **misspelled** (`boolean`) - Required - Whether the term was flagged as misspelled
- **count** (`number`) - Required - Number of matching products
- **term** (`string`) - Required - Search term (will be URI-decoded if possible)
### Event Payload
```typescript
{
event: 'autocomplete',
eventType: 'search',
search: {
operator: string,
misspelled: boolean,
text: string, // decoded term
match: number
}
}
```
**Error Handling:** If URI decoding fails, emits the term as-is without decoding.
```
--------------------------------
### Standard Search Result Layout Composition
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/2-blocks.md
Arrange 'search-banner', 'did-you-mean', and 'search-suggestions' within the 'search-result-layout.desktop' before the main search results.
```json
{
"search-result-layout.desktop": {
"blocks": [
"search-banner",
"did-you-mean",
"search-suggestions",
"search-result-layout"
]
}
}
```
--------------------------------
### React Components
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/README.txt
Details on React components like AutoComplete, TileList, ItemList, Attribute, and CustomListItem, including their methods, state, and CSS handles.
```APIDOC
## React Components
### Description
Documentation for the React components that power the search interface, detailing their APIs and styling capabilities.
### Components
- **`AutoComplete`**: A class component that manages the autocomplete dropdown, including methods, state, and lifecycle hooks.
- **`TileList`**: Component for displaying items in a tile format.
- **`ItemList`**: Component for displaying items in a list format.
- **`Attribute`**: Component for rendering product attributes.
- **`CustomListItem`**: A customizable component for rendering individual items, often used for product cards.
- **`Banner`, `DidYouMean`, `Suggestions`**: Components corresponding to the search blocks.
```
--------------------------------
### useRuntime
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Hook to access runtime context (page info, root path, etc.).
```APIDOC
## useRuntime (vtex.render-runtime)
### Description
Hook to access runtime context (page info, root path, etc.).
### Usage
```typescript
import { useRuntime } from 'vtex.render-runtime'
const runtime = useRuntime()
console.log(runtime.page)
```
```
--------------------------------
### Link App to VTEX Workspace
Source: https://github.com/vtex-apps/search/blob/master/README.md
Links the Search app to your active VTEX workspace after confirming the account. Ensure you are logged into the correct VTEX account and workspace before running.
```sh
make link # vtex link in the active workspace (confirms account first)
```
--------------------------------
### Configure Search Suggestions Block
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/2-blocks.md
Include the 'search-suggestions' block within the desktop search result layout to display related search terms.
```json
{
"search-result-layout.desktop": {
"blocks": [
"search-suggestions"
]
}
}
```
--------------------------------
### VTEX Blocks
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/README.txt
Documentation for VTEX Search App blocks, including `autocomplete-result-list.v2`, `did-you-mean`, `search-suggestions`, and `search-banner`, detailing their props, behavior, and integration.
```APIDOC
## VTEX Blocks
### Description
Reference for the pre-built VTEX blocks provided by the Search App, used for enhancing the search experience.
### Blocks
- **`autocomplete-result-list.v2`**: Displays a list of search results in an autocomplete dropdown. Includes props for customization, behavior details, and CSS handles.
- **`did-you-mean`**: Suggests alternative search terms if the initial query is not yielding results.
- **`search-suggestions`**: Provides real-time search term suggestions as the user types.
- **`search-banner`**: Displays promotional banners related to search results or terms.
```
--------------------------------
### Configure Search Banner Block
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/2-blocks.md
Integrate the 'search-banner' block into the desktop search result layout, specifying the banner area and alignment.
```json
{
"search-result-layout.desktop": {
"blocks": [
"search-banner"
],
"props": {
"area": "top",
"horizontalAlignment": "center"
}
}
}
```
--------------------------------
### IProductsOutput Interface
Source: https://github.com/vtex-apps/search/blob/master/docs/data-model.md
Defines the structure for product search results, including products, count, and spelling information.
```typescript
interface IProductsOutput {
products: ISearchProduct[] // see react/models/search-product
count: number
misspelled: boolean
operator: string
searchId: string
}
```
--------------------------------
### BiggyClient - suggestionSearches
Source: https://github.com/vtex-apps/search/blob/master/docs/data-model.md
Fetches text-based autocomplete suggestions for a given search term by issuing a `vtex.store-resources/QueryAutocompleteSearchSuggestions` Apollo query. The `term` is passed as the `fullText` variable.
```APIDOC
## suggestionSearches(term)
### Description
Issues `vtex.store-resources/QueryAutocompleteSearchSuggestions` with `{ fullText: term }` to return text-side autocomplete suggestions.
### Method
`suggestionSearches(term: string): Promise>`
### Parameters
#### Path Parameters
- **term** (string) - Required - The search term to get suggestions for.
### Response Example
```json
{
"data": {
"autocompleteSearchSuggestions": {
"searches": [
{
"term": "suggestion 1",
"count": 50,
"attributes": []
}
]
}
}
}
```
```
--------------------------------
### Import TopSearches GraphQL Query
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Import the QueryTopSearches GraphQL query from vtex.store-resources. This query is used to fetch top search terms.
```typescript
import topSearches from 'vtex.store-resources/QueryTopSearches'
```
--------------------------------
### Configure Autocomplete in Search Bar
Source: https://github.com/vtex-apps/search/blob/master/docs/Autocomplete.md
Integrate the 'autocomplete-result-list.v2' component within the 'search-bar' configuration. It's recommended to enable 'openAutocompleteOnFocus' for an improved user experience.
```json
{
"autocomplete-result-list.v2": {
"blocks": ["product-summary"]
},
"search-bar": {
"blocks": ["autocomplete-result-list.v2"],
"props": {
"openAutocompleteOnFocus": true
}
}
}
```
--------------------------------
### withApollo
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Higher-order component that injects Apollo Client.
```APIDOC
## withApollo (react-apollo)
### Description
Higher-order component that injects Apollo Client.
### Usage
```typescript
const EnhancedComponent = withApollo(MyComponent)
```
### Injected Prop
```typescript
client: ApolloClient
```
```
--------------------------------
### Manifest Builders Configuration
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
This JSON snippet shows the 'builders' section of the manifest.json file, specifying the versions of VTEX builders used by the app, such as 'store', 'react', and 'styles'.
```json
{
"builders": {
"store": "0.x",
"react": "3.x",
"styles": "2.x",
"docs": "0.x",
"messages": "1.x"
}
}
```
--------------------------------
### Import Banners GraphQL Query
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/6-context-and-dependencies.md
Import the QueryBanners GraphQL query from vtex.store-resources. This query is used to fetch banners based on search terms and selected facets.
```typescript
import bannersQuery from 'vtex.store-resources/QueryBanners'
```
--------------------------------
### handleSeeAllClick
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Emits a pixel event when the "See all results" link is clicked. It returns a function that, when called with a term, emits the event.
```APIDOC
## handleSeeAllClick()
### Description
Emits a pixel event when the "See all results" link is clicked. It returns a function that, when called with a term, emits the event.
### Signature
```typescript
export function handleSeeAllClick(
push: (data: any) => void,
page: string
): (term: string) => void
```
### Parameters
#### Function Parameters
- **push** (`(data: any) => void`) - Required - Pixel-manager push function
- **page** (`string`) - Required - Current page name
### Returns
A function `(term) => void` that emits the event.
### Event Payload
```typescript
{
page: string,
event: 'autocomplete',
eventType: 'see_all_click',
search: {
term: string
}
}
```
```
--------------------------------
### IProductsOutput Interface
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/3-types.md
Defines the structure of the product suggestion results returned by the Biggy client. Used by BiggyClient.suggestionProducts().
```typescript
interface IProductsOutput {
products: ISearchProduct[]
count: number
misspelled: boolean
operator: string
searchId: string
}
```
--------------------------------
### fromAttributesToFacets
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Converts Intelligent Search attributes into the VTEX StoreFront facet format for UI rendering.
```APIDOC
## fromAttributesToFacets()
### Description
Converts Intelligent Search attributes into VTEX StoreFront facet format.
### Signature
```typescript
export function fromAttributesToFacets(attribute: any): {
name: string
facets?: Array<{
quantity: number
name: string
link: string
selected: boolean
value: string
}>
map?: string
slug?: string
}
```
### Usage
Maps Biggy attribute structure to storefront facet structure for UI rendering.
```
--------------------------------
### Root Yarn Scripts
Source: https://github.com/vtex-apps/search/blob/master/CLAUDE.md
Provides essential scripts for linting and formatting at the root of the project. 'yarn lint' executes ESLint, and 'yarn format' applies Prettier formatting.
```sh
yarn lint # eslint (root + react)
yarn format # prettier --write
```
--------------------------------
### Configure Banner in Search Results Layout
Source: https://github.com/vtex-apps/search/blob/master/docs/Banner.md
Integrate the `search-banner` block into your desktop or mobile search result layout configuration.
```json
{
"search-result-layout.desktop": {
"children": [
"flex-layout.row#banner-one"
]
},
"search-banner#one": {
"props": {
"area": "one",
"blockClass": "myBanner",
"horizontalAlignment": "center"
}
},
"flex-layout.row#banner-one": {
"children": [
"search-banner#one"
]
}
}
```
--------------------------------
### Higher-Order Component Wrappers for VTEX Search Components
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/5-components.md
Demonstrates how VTEX Search components like Autocomplete, DidYouMean, Suggestions, and Banner are wrapped with Higher-Order Components (HoCs) for dependency injection.
```typescript
// Autocomplete
export default withDevice(withRuntime(withPixel(withApollo(AutoComplete))))
// DidYouMean, Suggestions, Banner
export default DidYouMean // Uses React hooks instead
```
--------------------------------
### Multi-repo Specs Structure
Source: https://github.com/vtex-apps/search/blob/master/AGENTS.md
The structure of the 'is-io-specs' multi-repo workspace, showing the location of team contracts, scope of work documents, and feature-specific specifications.
```text
is-io-specs/
├── .specify/memory/constitution.md # team contract — applies to all seven IS apps
├── docs/scope_of_work/ # per-feature inputs to /speckit.specify
└── specs// # spec.md, plan.md, tasks.md, analysis.md
```
--------------------------------
### Wrap Apollo Refetch with makeRefetch
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/4-utilities.md
Wraps Apollo's refetch function to translate 'from'/'to' parameters to 'page' and 'count' for VTEX search.
```typescript
export const makeRefetch = (refetch: Refetch): Refetch => (
variables
) => {
const { from, to, ...rest } = variables
const page = from ? Math.floor(from / to) : undefined
const count = to
return refetch({ ...rest, page, count })
}
```
--------------------------------
### Utility Functions
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/README.txt
A collection of utility functions for managing search history, handling cookies, encoding terms, formatting prices, tracking pixels, and logging errors.
```APIDOC
## Utility Functions
### Description
A set of utility functions to assist with various aspects of search functionality, including history management, data formatting, and tracking.
### Functions
- **Search History Utilities**: `readSearchHistory()`, `prependSearchHistory(term)`
- **DOM Utilities**: `getCookie(name)`, `setCookie(name, value, days)`, `hasClass(element, className)`
- **Term Encoding**: `encodeSearchTerm(term)`
- **String Utilities**: Various string manipulation functions.
- **Number Utilities**: `formatPrice(price)`
- **Pixel Tracking**: `handleProductClick(product)`, `handleItemClick(item)`
- **Session Utilities**: `getSession()`
- **Logging**: `logError(error)`
```
--------------------------------
### CI Cypress Workflow
Source: https://github.com/vtex-apps/search/blob/master/AGENTS.md
Configuration for the Cypress E2E test suite, which runs against the 'biggy' account in CI. Requires repository secrets for authentication and recording.
```yaml
.github/workflows/pull-request.yml
1. **`Cypress`** — `vtex/action-io-app-cypress@v1` runs the [`vtex/search-tests`](https://github.com/vtex/search-tests) suite against the `biggy` account, 4 containers, parallel. Requires repository secrets `APP_KEY`, `APP_TOKEN`, `RECORD_KEY`.
```
--------------------------------
### StorePreferences Interface Definition
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/3-types.md
Defines the overall structure for store configuration preferences, encompassing price, tile, and autocomplete settings. Used for formatting and UI text customization.
```typescript
export interface StorePreferences {
priceFormatPreferences: PriceFormatPreferences
tilePreferences: TilePreferences
autoCompletePreferences: AutoCompletePreferences
}
export interface PriceFormatPreferences {
prefix: string
decimalPlaces: number
floatIndicator: string
}
export interface TilePreferences {
unavailableMessage: string
oldPricePrefix: string
pricePrefix: string
showPrefixOnlyWhenPriceHasOldPrice?: boolean
}
export interface AutoCompletePreferences {
productCount: number
inputPlaceHolder: string
topSearchedListTitle: string
historyListTitle: string
suggestionListTitle: string
emptySuggestionListTitle: string
tileListTitle: string
subListItemPrefix: string
}
```
--------------------------------
### VTEX Search App Architecture Diagram
Source: https://github.com/vtex-apps/search/blob/master/_autodocs/0-overview.md
Illustrates the flow of data and components within the VTEX Search App, from the storefront header to search results pages.
```markdown
Storefront Header / Search Input
↓
├─ (Autocomplete.tsx)
│ ├─ BiggyClient (biggy-client.ts)
│ │ ├─ QueryTopSearches
│ │ ├─ QueryAutocompleteSearchSuggestions
│ │ ├─ QuerySuggestionProducts
│ │ └─ Session API (/api/sessions)
│ │
│ ├─ → Top Searches, Search History
│ ├─ → Search Suggestions
│ │ └─ → Facet sub-items
│ └─ → Product Tiles
│ └─ or
│
└─ History Cookie (biggy-search-history)
Search Results Page (PLP)
├─ → QueryBanners
├─ → QueryCorrection
├─ → QuerySearchSuggestions
└─ → (from vtex.search-result)
```