> ## Documentation Index
> Fetch the complete documentation index at: https://docs.uselayers.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Text Search: Prepare Search

> Prepare Search API endpoint that starts a search asynchronously so personalization and ranking can run in the background during a redirect or page load.

This endpoint asynchronously prepares expensive personalization for a given query, returning a ULID `search_id` that can be used with the Search API to execute the search.

* Use with: [Search API](/api-reference/search) via the `search_id` body parameter

## Authorization

<ParamField header="X-Storefront-Access-Token" type="string" required>
  Token-based authentication header in the form of `<YOUR_LAYERS_TOKEN>`. Same requirements as the Search API.
</ParamField>

## Headers

<ParamField header="Content-Type" default="application/json" type="string" required />

<ParamField header="Accept" default="application/json" type="string" required />

## Path parameters

<ParamField path="searchQuery" type="string" required>
  The url-encoded search query to prepare.
</ParamField>

## Body

<ParamField body="attributes" type="string[]">
  Optional hint for which product attributes you intend to include in the eventual Search response. Available attributes include: `id`, `title`, `handle`, `body_html`, `vendor`, `product_type`, `tags`, `images`, `available`, `created_at`, `updated_at`, `published_at`, `price_range`, `options`, `original_options`, `metafields`, `named_tags`, `calculated`, `category`, `featured_media`, `is_gift_card`, `has_variants_that_require_components`, `combined_listing_parent_product_id`, `combined_listing_role`, and `first_or_matched_variant`. See the <a href="/developers/product-schema/api-attributes">Product Schema</a>

  for detailed descriptions.
</ParamField>

<ParamField body="filter_group" type="object" description="A group of filter conditions using various operators.">
  Refer to our dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions.
</ParamField>

<ParamField body="pagination" type="Pagination Object" description="Specifies the page number and limit for pagination.">
  <Expandable title="pagination">
    <ParamField body="page" type="int" min="1" max="100">
      The current page of results to fetch.
    </ParamField>

    <ParamField body="limit" type="int" min="1" max="100">
      The max results to fetch per page
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="facets" type="string[]" description="List of facets to include in the response.">
  Facets to be included. Accepts both exact facet codes (e.g., `"vendor"`, `"options.Size"`) and wildcard patterns (e.g., `"options.*"`, `"metafields.product.*"`).

  Wildcard patterns expand to all matching attribute codes. For example, `"options.*"` expands to all option facets like `"options.Size"` and `"options.Color"`. Wildcards must match at least one attribute code to be valid.

  **Examples:**

  ```json theme={null}
  // Exact facet codes
  "facets": ["vendor", "options.Size", "options.Color"]

  // Wildcard pattern
  "facets": ["options.*"]

  // Mixed exact and wildcard
  "facets": ["vendor", "options.*", "metafields.product.*"]
  ```
</ParamField>

<ParamField body="retrieveFacetCount" type="boolean" description="Retrieve facet count.">
  If the count of each facet value should be calculated
</ParamField>

<ParamField body="includeFacetRanges" type="boolean" descriptive="Return min/max range for facets with a numeric value.">
  If you want a min/max range for numeric facets such as price.
</ParamField>

<ParamField body="identity" type="object">
  User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations.

  <Expandable title="Properties">
    <ParamField body="deviceId" type="string">
      Persistent browser identifier that remains constant across sessions. Used to recognize returning visitors for long-term personalization. Automatically generated and managed by the Storefront Pixel.
    </ParamField>

    <ParamField body="sessionId" type="string">
      Temporary session identifier. Typically corresponds to the Shopify session ID and expires after inactivity or when the browser is closed.
    </ParamField>

    <ParamField body="customerId" type="string">
      Shopify customer ID for authenticated users. Only present when the user is signed in to their account.
    </ParamField>

    <ParamField body="companyLocationId" type="string">
      Shopify B2B company location GID (e.g. `gid://shopify/CompanyLocation/123456789`) for the authenticated buyer. Layers resolves the catalog assigned to the company location and uses it to scope results: only products in the catalog are returned, prices come from the catalog's price list, and excluded collections return 404. Omit for retail (DTC) traffic. See [B2B catalogs](/shopify-integration/b2b-catalogs).
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="context" type="object">
  Contextual information about the customer's session, behavior, and environment. Automatically collected by the Storefront Pixel; must be manually provided for headless integrations. See [Contextual Information](/engine/contextual-information) for implementation guidance.

  <Expandable title="Properties">
    <ParamField body="geo" type="object">
      Geographic location information for regional personalization and merchandising. Automatically determined by the platform for client-side requests based on IP address. For server-side API calls (headless integrations), you should provide this explicitly.

      <Expandable title="Properties">
        <ParamField body="country" type="string">
          Country code or name (e.g., "US", "Canada").
        </ParamField>

        <ParamField body="province" type="string">
          State or province name (e.g., "California", "Ontario").
        </ParamField>

        <ParamField body="city" type="string">
          City name (e.g., "Los Angeles", "Toronto").
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="productsInCart" type="array">
      Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring.

      <Expandable title="Array Item Properties">
        <ParamField body="title" type="string" required>
          Product title.
        </ParamField>

        <ParamField body="price" type="number">
          Product price.
        </ParamField>

        <ParamField body="type" type="string">
          Product type or category.
        </ParamField>

        <ParamField body="productId" type="string">
          Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`).
        </ParamField>

        <ParamField body="variantId" type="string">
          Product variant identifier.
        </ParamField>

        <ParamField body="options" type="object">
          Product variant options (e.g., `{"Size": "11", "Color": "Red"}`).
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="productsPurchased" type="array">
      Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items.

      <Expandable title="Array Item Properties">
        <ParamField body="title" type="string" required>
          Product title.
        </ParamField>

        <ParamField body="price" type="number">
          Product price at time of purchase.
        </ParamField>

        <ParamField body="type" type="string">
          Product type or category.
        </ParamField>

        <ParamField body="productId" type="string">
          Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`).
        </ParamField>

        <ParamField body="variantId" type="string">
          Product variant identifier.
        </ParamField>

        <ParamField body="options" type="object">
          Product variant options (e.g., `{"Size": "11", "Color": "Red"}`).
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="priorSearches" type="array">
      Recent search queries and their outcomes. Helps understand customer intent and refine relevance models.

      <Expandable title="Array Item Properties">
        <ParamField body="searchQuery" type="string" required>
          The search query text.
        </ParamField>

        <ParamField body="hadClick" type="boolean" required>
          Whether the customer clicked on any results from this search.
        </ParamField>

        <ParamField body="hasResults" type="boolean" required>
          Whether the search returned any results.
        </ParamField>

        <ParamField body="fromPage" type="string">
          The page the search was initiated from (e.g., the referring page URL or page type).
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="marketing" type="object">
      UTM parameters and marketing campaign information for attribution tracking.

      <Expandable title="Properties">
        <ParamField body="source" type="string">
          Marketing source (e.g., "google", "facebook").
        </ParamField>

        <ParamField body="medium" type="string">
          Marketing medium (e.g., "cpc", "email", "social").
        </ParamField>

        <ParamField body="campaign" type="string">
          Campaign name.
        </ParamField>

        <ParamField body="term" type="string">
          Search term or keyword.
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="customer" type="object">
      Aggregated customer behavior and purchase patterns for personalization.

      <Expandable title="Properties">
        <ParamField body="signedIn" type="boolean">
          Whether the customer is currently authenticated.
        </ParamField>

        <ParamField body="returning" type="boolean">
          Whether this is a returning customer.
        </ParamField>

        <ParamField body="numberOfOrders" type="integer">
          Total number of orders placed.
        </ParamField>

        <ParamField body="averageOrderValue" type="number">
          Average order value in store currency.
        </ParamField>

        <ParamField body="daysBetweenOrders" type="integer">
          Average days between orders.
        </ParamField>

        <ParamField body="daysSinceLastOrder" type="integer">
          Days since the most recent order.
        </ParamField>

        <ParamField body="daysSinceOldestOrder" type="integer">
          Days since the first order.
        </ParamField>

        <ParamField body="totalSpent" type="number">
          Total amount spent in store currency.
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="market" type="string">
      Explicitly set the Shopify Market for this request. Used for market-specific product availability filtering and contextual pricing. Accepts a two-letter country code (e.g., `"US"`, `"CA"`), a numeric Shopify Market ID (e.g., `"12345"`), or a Shopify Market GID (e.g., `"gid://shopify/Market/12345"`).

      When not provided, the market is automatically resolved from the `geo.country` field (or the shopper's detected country for client-side requests). If no matching market is found, the store's primary market is used as the fallback.

      **Behavior depends on the store's market application mode:**

      * **Strict** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied
      * **Pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available
      * **Off** — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers
    </ParamField>

    <ParamField body="shoppingChannel" type="string" default="web">
      The shopping channel the customer is browsing from. Used for channel-specific merchandising, sorting, and analytics segmentation. Automatically detected from request headers when not provided (e.g., mobile app requests via Tapcart or Canvas are detected as `"app"`).

      **Accepted values:**

      * `"web"` — Standard web browser (default)
      * `"app"` — Mobile app (e.g., Tapcart, Canvas)
    </ParamField>

    <ParamField body="custom" type="object">
      Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case.
    </ParamField>
  </Expandable>
</ParamField>

## Behavior

* Returns HTTP 202 (Accepted) immediately with a `search_id`
* Generates a ULID `search_id` that identifies the prepared search
* Starts additional search preparation asynchronously
* Pre-computes query understanding and personalization inputs
* Prepared data is cached for up to 15 minutes; after TTL, Search falls back to normal processing

## Response

### 202 Accepted

<ResponseField name="search_id" type="string">
  ULID identifier for the prepared search. Valid for 15 minutes.
</ResponseField>

<ResponseExample>
  ```json Request theme={null}
  POST /storefront/v1/search/running%20shoes/prepare

  {
    "context": {
      "geo": {
        "country": "US",
        "province": "California"
      },
      "productsInCart": [
        {
          "title": "Nike Air Force 1",
          "productId": "1234567890"
        }
      ],
      "marketing": {
        "source": "google",
        "medium": "cpc"
      },
      "shoppingChannel": "web"
    },
    "identity": {
      "sessionId": "abc123",
      "deviceId": "device-uuid"
    }
  }
  ```

  ```json Response theme={null}
  {
    "search_id": "01HZY7J9ZV6K2T3M6P4FJ3F2QG"
  }
  ```
</ResponseExample>

### Response headers

| Header           | Description                                                                                                                     |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `x-request-id`   | A unique identifier (ULID) for the request. Use it to correlate requests across your infrastructure or when contacting support. |
| `x-layers-build` | The Layers build version that served the request.                                                                               |

### Error conditions

* 401 Unauthorized: Missing/invalid `X-Storefront-Access-Token`
* 422 Unprocessable Entity: Invalid body or parameters

## Next steps

Use the returned `search_id` with the [Search API](/api-reference/search) in the `search_id` body parameter to execute an optimized search.
