# Blocks API: Get Block Products Source: https://docs.uselayers.com/api-reference/blocks POST /blocks/{blockId}/products Blocks API endpoint that returns product recommendations for a specific block using its configured strategy, fallback chain, and merchandising rules. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Path parameters **blockId** `string` *required* The unique identifier (ULID) of the block you wish to retrieve products for. When sourcing the block from a [block metaobject](/shopify-integration/metaobjects-metafields/metaobjects#block-metaobject) in a Shopify theme, note that the metaobject's `system.handle` is `layers-`, not the raw ID. Transform it (`handle | remove_first: 'layers-' | upcase`) before passing it here. Passing the prefixed handle matches no block and returns `404` with `"Block not found"`. ## Body **anchor\_id** `string` The anchor identifier for the block. Required for product, article, and collection anchor types. * **Product anchors**: Numeric product ID (e.g., `"8234567890123"`) or Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). Both formats are resolved automatically. * **Article anchors**: Numeric article ID (e.g., `"556677889900"`) or Shopify GID (e.g., `"gid://shopify/Article/556677889900"`). Both formats are resolved automatically. * **Collection anchors**: Collection ID (e.g., `"456789012345"`) or collection handle (e.g., `"summer-collection"`). The system automatically resolves both numeric IDs and string handles. * **Cart anchors**: Not required. Layers uses every `context.productsInCart` entry with a valid `productId`, removes duplicates, and preserves cart order. Entries without a `productId` are skipped. * **Home, Search, Not Found, Landing, Other anchors**: Not required. These surfaces rely on the `context` and `identity` parameters (search query, landing source, shopper context) to drive strategy selection. Search-anchored strategies (`searched_then_viewed`, `searched_then_purchased`) resolve their query from the last `searchQuery` in `context.priorSearches`, not from `anchor_id`, so callers must pass `context: { priorSearches: [{ searchQuery }] }` for those blocks to return results. * **None anchors**: Not required (global blocks) **anchor\_handle** `string` **Deprecated**: Use `anchor_id` instead. For collection anchors, `anchor_id` now accepts both collection IDs and handles. **variant\_id** `integer` The ID of the specific variant the shopper is viewing on the anchor product. Only used for product-anchored blocks running a variant-aware strategy: * **[Similar Products](/platform/blocks/strategies#similar-products)**: the block seeds similarity from that variant instead of the product as a whole, so recommendations reflect the variant's visual and semantic attributes, such as the selected color. * **[Metafield References](/platform/blocks/strategies#metafield-reference-strategy)** with a variant-scoped metafield: the block reads the reference metafield from that variant, falling back to the anchor product's product-scoped value when the variant has none. * **[Photographed Together](/platform/blocks/strategies#photographed-together)**: when the variant has photography of its own, the set is built from those shots, so shoppers on a specific colorway see the items it was styled with. The value is silently ignored when: * The block's anchor type is not `product`. * The variant does not belong to the anchor product. * The block's strategy is not variant-aware. When `variant_id` is set on a product-anchored similar-products block, results are computed in real time rather than served from the precomputed cache. Different variants of the same product return different results and are cached under separate keys. **attributes** `string[]` Product attributes to include in the response. By default, all attributes are included except opt-in attributes noted below. 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`, `first_or_matched_variant`, and `variants`. The `collection_titles` attribute is opt-in: pass it in `attributes` to include the array of collection titles each product belongs to. It is excluded from responses by default. See the [Product Schema](/developers/product-schema/api-attributes) for detailed descriptions, including [nested field selection](/developers/product-schema/api-attributes#selecting-nested-fields) for slicing arrays and filtering collections (for example, `images[:2].src`, `variants[sku=ABC].price`, `metafields[namespace=custom]`). **excludeProductIds** `string[]` A list of product IDs to exclude from the recommendations returned by this block. Use this to deduplicate products across multiple blocks rendered on the same page. For example, you can prevent the same product from appearing in both a "Frequently Bought Together" block and a "Customers Also Viewed" block. Each entry can be either a numeric product ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). Both formats are accepted and resolved automatically. Excluded products are filtered out before strategy ranking, safeguard checks, and fallback evaluation. If excluding products causes the primary block to fall below its minimum products safeguard, the [fallback chain](/platform/blocks/fallback-chains) is used and exclusions are applied to fallback blocks as well. **filter\_group** `object` Storefront endpoints accept nested `AND`/`OR` filter groups up to two levels deep. Each nested group must contain at least one expression; empty nested groups are rejected. Metafield filter properties may include hyphens in their namespace or key, for example `metafields.my-app.fit-type`. Refer to the dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions. For product blocks, this shopper filter applies to the recommended products. It supports the nested groups described above; content blocks do not accept `filter_group`. **pagination** `Pagination Object` **pagination** **page** `int` The current page of results to fetch. **limit** `int` The max results to fetch per page. **facets** `string[]` 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.*"] ``` **retrieveFacetCount** `boolean` If the count of each facet value should be calculated. **includeFacetRanges** `boolean` If you want a min/max range for numeric facets such as price. **enrichFacetMetaobjects** `boolean` When `true`, any facet backed by a `metaobject_reference` or `list.metaobject_reference` metafield is returned with a companion `facetDisplay` object. Each entry maps a facet value (the metaobject handle) to the referenced metaobject's `display_name` and `fields`. When the metaobject defines a color or image field, the entry also carries a resolved `swatch` object. Use this when your storefront filter UI needs human-readable labels or nested field data (for example, a color name or swatch hex) instead of the raw handle. When `false` or omitted, only the handles are returned in `facets`. Values are looked up from the local metaobject cache. Handles with no matching cached metaobject are omitted from `facetDisplay` and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized shape of each entry. **discountEntitlements** `array` Apply discounts to products, variants, or collections. When provided, price-based sorting and filtering will use discounted prices. See the [Discount Entitlements](/shopify-integration/discount-entitlements) guide for detailed usage. Fixed amounts use your shop's base currency. Layers skips them on market pricing rows in a different native currency, without converting the discount. Percentage discounts still apply to those localized prices. A variant that falls back to its base price can still receive a fixed-amount discount. **Discount Entitlement Object** **entitled** `object` *required* Defines which products qualify for the discount. **entitled** **all** `boolean` When `true`, applies discount to all products. When `false`, uses products, variants, or collections arrays. **products** `string[]` Array of product IDs or handles that qualify for the discount. Maximum 250 entries. **variants** `string[] | number[]` Array of variant IDs that qualify for the discount. Maximum 250 entries. **collections** `string[]` Array of collection handles that qualify for the discount. Maximum 250 entries. **conditions** `object` Optional filter group that qualifies products for the discount based on their attributes (for example, `tags` or `vendor`). Uses the same shape as the top-level `filter_group` parameter. Matches are additive with `products`, `variants`, and `collections` on the same entitlement. **discount** `object` *required* Defines the discount to apply. **discount** **type** `string` *required* The discount type: `PERCENTAGE` or `FIXED_AMOUNT`. **value** `number` *required* The discount value. For `PERCENTAGE`, this must be a number between 0 and 100 (e.g., 10 for 10% off). For `FIXED_AMOUNT`, this is the amount in your shop's base currency, not the shopper's market currency. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. **responseOptions** `object` Per-request overrides for response behavior. Currently controls image preload hints emitted in the `Link` response header. You can disable preloads or narrow the srcset to the breakpoints your storefront uses. You cannot enable preloads when the store has them disabled. **Properties** **mediaPreloads** `object` Controls the `Link: rel=\"preload\"` directives generated for product images in this response. See [Early hints](/sdk/performance#early-hints-link-header-preloading) for background. **Properties** **enabled** `boolean` (default: true) Set to `false` to skip the `Link` header for this request. Useful for server-rendered pages that do not benefit from preload hints, or when you want to reduce response header size. Cannot enable preloads if they are disabled at the store level. **srcsetSizes** `int[]` Custom responsive image widths (in pixels) to emit in `imagesrcset`. Each value must be an integer between `1` and `10000`. Overrides the store-level srcset configuration for this request only. When omitted, the store configuration or platform defaults are used. **sizes** `string` Media query string emitted as the `imagesizes` attribute in the preload `Link` header (for example `(max-width: 600px) 100vw, 50vw`). Tells the browser which srcset width to pick per viewport. Overrides the store-level sizes value for this request only. When omitted or empty, the store configuration is used. Each comma-separated entry may carry a media condition, including the last entry. See the [accepted format](/sdk/performance#customization) for details. The API rejects invalid values with a validation error. **Example:** ```json theme={null} { "responseOptions": { "mediaPreloads": { "enabled": true, "srcsetSizes": [320, 640, 960], "sizes": "(max-width: 600px) 100vw, 50vw" } } } ``` ## Response **results** `Array of Objects` **Properties** **id** `number` The unique identifier of the product. **title** `string` The title of the product. **body\_html** `string` The HTML content describing the product. **vendor** `string` The vendor of the product. **product\_type** `string` The type of the product. **created\_at** `number` The timestamp when the product was created. **handle** `string` The handle of the product. **updated\_at** `number` The timestamp when the product was updated. **published\_at** `number` The timestamp when the product was published. **tags** `Array of strings` The tags associated with the product. **combined\_listing\_parent\_product\_id** `number` The parent product id if a child in a Combined Listing. **combined\_listing\_role** `string` The role of the product if part of a Combined Listing. **images** `Array of Objects` The images of the product. **Properties** **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **variant\_ids** `Array` The variant IDs associated with the image. **metafields** `Object` The metafields of the product. **calculated** `Object` The computed attributes of the product. Only includes attributes with non-null, non-empty values. Attributes that evaluate to null or an empty string are omitted. **category** `Object` The Shopify Product Taxonomy Category of the product. **Properties** **name** `string` The name of the category leaf. **full\_name** `string` The full name of the category. **id** `string` The ID of the category. **is\_leaf** `boolean` Is the category a leaf category. **is\_root** `boolean` Is the category a root category. **first\_or\_matched\_variant** `Object` The first available variant (depending on OOS settings) or the variant matched with a filter or search query. **Properties** **id** `number` The ID of the variant. **title** `string` The title of the variant. **available** `boolean` The availability of the variant. **sku** `number` The sku of the variant. **price** `string` The price of the variant. **compare\_at\_price** `string` The compare at price of the variant. **metafields** `Object` The metafields of the variant. **selected\_options** `Array of Objects` The selected options of the variant. **Properties** **name** `string` The name of the option. **value** `string` The value of the option. **option\_value** `object` The linked metafield of the option. **position** `number` The position of the variant in the product's variant list. **inventory\_quantity** `number` Total inventory quantity across the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope), which is all locations by default. Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_policy** `string` Inventory policy for the variant: `DENY` (stop selling when out of stock) or `CONTINUE` (allow overselling). Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_levels** `object` Object mapping location IDs to available inventory quantities (e.g., `{"1001": 5, "1002": 10}`). Returns empty object `{}` when no inventory data exists. Only included when the store has the **Expose Variant Inventory** setting enabled. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **available** `boolean` The availability of the product. **price\_range** `Object` The price range of the product. **Properties** **from** `number` The starting price of the product. **to** `number` The ending price of the product. > [!NOTE] > > When the store has the **Expose Variant Inventory** setting enabled, variant data in block responses (both `first_or_matched_variant` and `variants`) includes the `inventory_quantity`, `inventory_policy`, and `inventory_levels` fields. This behavior is consistent across all storefront API endpoints: search, browse, and blocks. See [Variant Schema Fields](/developers/product-schema/variant-data#variant-schema-fields) for details on these fields. **totalResults** `number` The total number of results. When a maximum products safeguard is configured, this value is capped to the maximum. When variant breakouts are enabled, this reflects the count of tiles (both product and variant tiles) rather than just products. **page** `number` The current page number. **totalPages** `number` The total number of pages. Calculated from `totalResults` and the requested page size. When a maximum products safeguard is configured, this reflects the capped total. When variant breakouts are enabled, the calculation is based on tile count. **resultsPerPage** `number` The number of results per page (matches the `limit` parameter from the request). **facets** `object` If `retrieveFacetCount` is `true` then an object with keys and values of the specified attributes. When variant breakouts are enabled, facet counts reflect tile counts rather than product counts. Empty values and literal `"null"` strings are automatically excluded from facet results. **facetRanges** `object` If `includeFacetRanges` is `true` then an object with keys of the facet attribute code and value is an object with min/max. **facetDisplay** `object` Only returned when `enrichFacetMetaobjects` is `true` and at least one requested facet is backed by a `metaobject_reference` or `list.metaobject_reference` metafield. Keys are facet attribute codes and values map each facet value (the referenced metaobject's handle) to the metaobject's `display_name` and `fields`. Handles with no matching cached metaobject are omitted here and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized field shape. **attributionToken** `string` A unique request identifier (ULID) for this API call. Use this token to correlate block requests with analytics events via the [Beacon API](/tracking-api/send-events). **block** `object` Information about the block that generated these recommendations. **Properties** **id** `string` The block ID. **title** `string` The customer-facing title of the block. **anchor\_type** `string` The anchor type of the block: `product`, `article`, `collection`, `cart`, `home`, `search`, `not_found`, `landing`, `other`, or `none`. **strategy\_type** `string` The strategy type used: `interaction`, `similar_products`, `manual`, `metafield_reference`, `sequence`, `personalized`, `trending`, `contextual`, `set`, or `related_content`. **strategy\_key** `string` The specific strategy key. For product strategies: `frequently_bought_together`, `customers_also_viewed`, `customers_also_added_to_cart`, `viewed_then_bought`, `customers_also_bought`. For collection strategies: `browsed_then_bought`, `browsed_then_viewed`, `collection_trending`. For trending strategies: `best_sellers`, `trending_in_region`, `live_feed`. For contextual strategies: `searched_then_viewed`, `searched_then_purchased`, `landing_page_picks`, `free_shipping_picks`. For similar products strategies on article anchors: `similar_to_article`. For related content strategies: `related_articles`. **\_training** `boolean` Present and set to `true` when the block's strategy data is still being computed or the strategy doesn't yet have enough signal to return results. This applies to interaction strategies during their initial computation and to trending and contextual strategies that are warming up. It also applies to Photographed Together blocks while image detection is still processing your catalog. In this state, the primary block returns empty results and the fallback chain is used instead. Once the strategy data is ready, this field is no longer included in the response. **\_meta** `object` **Properties** **variantBreakouts** `array of objects` Array of variant breakout configurations applied to this block. Only present when one or more variant breakouts are active. Multiple breakouts with different option codes can work simultaneously. Each object has the structure `{optionCode: "Stone"}`. **Properties** **optionCode** `string` The product option code that determines which variants are broken out (e.g., "Stone", "Color"). Each product is broken out by the first matching option code from the array. **mediaPreloads** `object` Echoes the image preload configuration used to build the `Link` response header for this request. Only present when image preloads are emitted. See [Early hints](/sdk/performance#early-hints-link-header-preloading). **Properties** **srcsetSizes** `int[]` The responsive image widths (in pixels) used in the `imagesrcset` of the `Link` header. Reflects the request override when provided, otherwise the store-level configuration or platform defaults. **discountEntitlements** `array of objects` Echoes the [discount entitlements](/shopify-integration/discount-entitlements) applied to this request. Only present when the request included `discountEntitlements` (either directly or via a matched [request transform](/platform/request-transforms)). Use this to render discount badges or labels on the storefront without re-deriving which entitlements matched. Each entry mirrors the entitlement shape sent in the request. **Properties** **entitled** `object` The entitlement criteria that qualified products for the discount. Contains any of `all`, `products`, `variants`, `collections`, or `conditions`. See the [entitlement criteria](/shopify-integration/discount-entitlements#entitlement-criteria) reference. **discount** `object` The discount Layers applied. **Properties** **type** `string` `"PERCENTAGE"` or `"FIXED_AMOUNT"`. **value** `number` The discount value. Percent off for `PERCENTAGE`, currency amount for `FIXED_AMOUNT`. **\_workflow** `array of objects` An ordered trace of processing steps the engine performed to produce results. Each entry represents a stage in the pipeline, recorded in the order it was executed. See the [Text Search](/api-reference/search) documentation for the full list of possible step types. **Properties** **type** `string` The processing step type (e.g., `"rule-applied"`). **payload** `string | array | object` The data associated with this processing step. ### Hidden blocks return an empty success If an active block is hidden and has no usable fallback, the API returns HTTP `200` with empty results, not a `404`. For example, a matching **Hide Block** rule can produce this response. Treat it as a successful request with nothing to display. The response preserves the requested page and page size, the attribution token, and the block's identity: ```json theme={null} { "results": [], "totalResults": 0, "totalPages": 0, "page": 1, "resultsPerPage": 8, "attributionToken": "01K8A2B3C4D5E6F7G8H9J0K1M2", "block": { "id": "01K8A2B3C4D5E6F7G8H9J0K1M3", "title": "You may also like", "anchor_type": "product", "result_type": "products" }, "_meta": { "experimentsRan": [] } } ``` This empty response doesn't include strategy details in `block`. Missing or inactive blocks still return `404`, and a configuration that can't resolve a required sort order still returns `422`. ### Content block responses Blocks configured with the [related content strategy](/platform/blocks/strategies#related-content-strategy) return articles or pages in `results` instead of products. Each item has this shape: ```json theme={null} { "__typename": "Article", "content_type": "article", "content_id": 556677889900, "title": "How to care for linen", "handle": "how-to-care-for-linen", "summary_text": "Keep your linen pieces looking new with these care tips.", "author": "Jamie Lee", "tags": ["care", "linen"], "image": { "url": "https://cdn.shopify.com/s/files/1/0588/3677/9194/articles/linen-care.jpg", "width": 1200, "height": 800, "alt": "Folded linen shirts" }, "published_at": "2026-08-14T09:00:00Z", "blog_title": "The Journal", "url": "/blogs/the-journal/how-to-care-for-linen" } ``` The item fields match the [Content Search API](/api-reference/search-content) results. `__typename` is `Article` or `Page` depending on the block's configured `content_type`. Pages don't have `author`, `tags`, or `blog_title`, so those fields are `null` for page results. Pagination fields (`totalResults`, `page`, `totalPages`, `resultsPerPage`), `attributionToken`, and the `block` object work the same as for product blocks. Product-only request parameters (`filter_group`, `variant_id`, `attributes`, facets, and `discountEntitlements`) don't apply to content blocks. ### Anchor and strategy compatibility Strategy compatibility depends on the anchor type. See the [strategy availability by anchor type](/platform/blocks/strategies#strategy-availability-by-anchor-type) matrix for the complete list of supported strategies. Requests that use a strategy type not allowed for the anchor are rejected with a validation error on `strategy_type`. ### Response headers Every API response includes the following headers for request tracing and performance optimization: | Header | Description | | - | - | | `x-request-id` | A unique identifier (ULID) for the request. This matches the `attributionToken` in the response body. | | `x-layers-build` | The Layers build version that served the request. | | `X-Layers-Results-Cache` | Indicates whether the response was served from the results cache. Returns `HIT` or `MISS`. | | `Link` | Contains `rel="preload"` directives for product images (up to 6 items). See [Early hints](/sdk/performance#early-hints-link-header-preloading) for details. Only included when early hints are enabled (enabled by default). | ## Block concepts For details on how blocks work conceptually (anchor types, strategies, rules, safeguards, and fallback chains), see the platform documentation: * [Block strategies and anchor types](/platform/blocks/strategies) * [Rules and safeguards](/platform/blocks/rules-and-safeguards) * [Fallback chains](/platform/blocks/fallback-chains) * [Priority and status](/platform/blocks/priority-and-status) ## Error handling **error** `string` Error message when the request fails. **Common errors:** > [accordion] 404 - Block not found > > The specified block ID doesn't exist or is not active. > > ```json theme={null} > { > "error": "Block not found" > } > ``` > [accordion] 422 - Sort order required > > The block's configuration didn't resolve to a valid sort order. This can happen with collection-anchored similar-products blocks when the configured fallback sort order no longer exists. Reconfigure the block with a valid sort order in the dashboard, then retry the request. > > ```json theme={null} > { > "error": "A sort order code or ID is required to load this block." > } > ``` > [accordion] 401 - Unauthorized > > Invalid or missing authentication token. > [accordion] 402 - Store suspended > > The store is suspended. Every storefront API request returns `402` until the suspension is lifted. > > ```json theme={null} > { > "message": "This store has been suspended." > } > ``` ```json Product Anchor - Frequently Bought Together theme={null} POST /storefront/v1/blocks/01HQXYZ123ABC456DEF789/products { "anchor_id": "8234567890123", "pagination": { "page": 1, "limit": 12 }, "context": { "geo": { "country": "US", "province": "California" }, "productsInCart": [ { "title": "Nike Air Force 1", "productId": "8234567890123", "variantId": "45678901234567" } ], "shoppingChannel": "web" }, "identity": { "sessionId": "abc123", "deviceId": "device-uuid" } } ``` ```json Article Anchor - Shop the Article theme={null} POST /storefront/v1/blocks/01HQXYZ654STU321VWX098/products { "anchor_id": "gid://shopify/Article/556677889900", "pagination": { "page": 1, "limit": 12 }, "context": { "geo": { "country": "US" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123" } } ``` ```json Collection Anchor - Collection Interaction Strategy theme={null} POST /storefront/v1/blocks/01HQXYZ789GHI012JKL345/products { "anchor_id": "summer-collection", "pagination": { "page": 1, "limit": 12 }, "context": { "geo": { "country": "US" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123" } } ``` ```json Collection Anchor - Manual Strategy theme={null} POST /storefront/v1/blocks/01HQXYZ789GHI012JKL345/products { "anchor_id": "summer-collection", "pagination": { "page": 1, "limit": 20 }, "filter_group": { "conditional": "AND", "expressions": [ { "property": "available", "operator": "=", "values": [true] } ] }, "context": { "geo": { "country": "US" }, "shoppingChannel": "web" } } ``` ```json Cart Anchor - Complete the Look theme={null} POST /storefront/v1/blocks/01HQXYZ456MNO789PQR012/products { "pagination": { "page": 1, "limit": 8 }, "context": { "geo": { "country": "US" }, "productsInCart": [ { "title": "Nike Air Force 1", "productId": "8234567890123", "variantId": "45678901234567" }, { "title": "Classic Tee", "productId": "8234567890456", "variantId": "45678901234890" } ], "shoppingChannel": "app" }, "identity": { "sessionId": "abc123" } } ``` ```json Market Pricing and Discount Entitlements theme={null} POST /storefront/v1/blocks/01HQXYZ123ABC456DEF789/products { "anchor_id": "8234567890123", "pagination": { "page": 1, "limit": 12 }, "context": { "market": "CA", "geo": { "country": "CA" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123", "customerId": "8123456789", "companyLocationId": "gid://shopify/CompanyLocation/1234567890" }, "discountEntitlements": [ { "entitled": { "collections": ["gid://shopify/Collection/456789012345"] }, "discount": { "type": "PERCENTAGE", "value": 20 } } ] } ``` ```json Deduplicate Products Across Blocks theme={null} POST /storefront/v1/blocks/01HQXYZ456MNO789PQR012/products { "anchor_id": "8234567890123", "pagination": { "page": 1, "limit": 8 }, "excludeProductIds": [ "8234567890456", "gid://shopify/Product/8234567890789" ], "context": { "geo": { "country": "US" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123" } } ``` ```json Response theme={null} { "results": [ { "id": 7003338965178, "title": "SUPREME SEALLINE SEE POUCH SMALL", "body_html": "The Supreme Sealline See Pouch Small is a versatile and waterproof storage solution that seamlessly marries utility and style. With its clear window for easy visibility and the iconic Supreme branding, it's a sought-after accessory for those who appreciate keeping their essentials dry while making a fashion statement, whether at the beach or in the city.", "vendor": "SUPREME", "product_type": "Accessories", "created_at": 1644047925, "handle": "supreme-pouch-44370ss18a32-sm", "updated_at": 1698280024, "published_at": 1644047925, "tags": [ "consignment" ], "images": [ { "alt": "SUPREME POUCH", "src": "https://cdn.shopify.com/s/files/1/0588/3677/9194/products/ss18_supreme_tnf_pouch_blk_2-l_5fb1316e-22f7-4702-9953-57f3fbdda5be.jpg?v=1644047927", "width": 800, "height": 534, "variant_ids": [] } ], "metafields": { "product": { "alias": "SEALLINE SEE POUCH SMALL", "colorway": "BLACK", "styleCode": "SS18A30 BLACK", "yearOfRelease": 2018, "searchColor": [ "black" ] } }, "available": true, "price_range": { "from": 30, "to": 30 } } ], "totalResults": 8, "page": 1, "totalPages": 1, "resultsPerPage": 12, "block": { "id": "01HQXYZ123ABC456DEF789", "title": "Frequently Bought Together", "anchor_type": "product", "strategy_type": "interaction", "strategy_key": "frequently_bought_together" }, "attributionToken": "01JRVX9N4O5P6Q7R8S9T0U1V2W", "_meta": {}, "_workflow": [] } ``` ## See also * [Blocks Platform Documentation](/platform/blocks) - Learn about block concepts and configuration # Browse API: Browse Collection Page Source: https://docs.uselayers.com/api-reference/browse POST /browse/{collection_handle} Browse API endpoint to fetch, filter, sort, and paginate merchandised collection pages in your catalog with facets, pins, and personalization applied. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Path parameters **collection\_handle** `string` *required* The handle of the collection you wish to browse. Use `all` to browse every browsable product in the catalog. This works whether or not your store has a synced `/collections/all` collection. If a collection with the handle `all` is synced, Layers browses that collection's products. If not, it browses the whole catalog with the store's default sort order and no collection-specific variant breakouts. Any other handle that doesn't match a synced collection returns an error. ## Body **sort\_order\_code** `string` Code of the sort order. When provided, it takes precedence over collection and store defaults. If omitted, Layers uses the collection's default sort order, then the store default when the collection has no default. Existing merchandising rules continue to apply as configured. **dynamicLinking** `object` Dynamic linking promotes specific products to the top of the first page of results. Dynamic linking takes priority over merchandising rules and sort orders. > [!NOTE] > > If the Layers tracking pixel is installed, this parameter is **automatically injected** when customers arrive with a `utm_products` URL parameter (e.g., `?utm_products=summer-dress-blue_classic-tee-white_beach-hat`). See [Dynamic Linking for ads](/help/merchandising/dynamic-linking) for details. **Properties** **products** `array` *required* Products to pin. Each entry is either a plain identifier or an object: * **Handle**: a string, for example `"summer-dress-blue"`. * **ID**: a number or numeric string, for example `8234567890123`. * **Object**: `{ "productId": "summer-dress-blue", "position": 2 }`. `productId` takes a handle or ID. `position` is optional. You can mix all three in one array. Any other entry shape (an object without `productId`, an empty string, a nested array) returns `422`. **Position:** * Plain identifiers, and objects without `position`, are pinned in array order: the first one at position 1 (after any `offset`), the next at position 2, and so on. * An object's `position` is the exact 1-based slot for that product on the first page. It must be an integer of `1` or more, and `offset` doesn't apply to it. * Unpositioned products fill the remaining pinned slots in array order. * If the same product appears more than once, the first explicit `position` for it wins. **Behavior:** * Only applies on the first page of results (page 1), except for out-of-collection products (see below) * Non-existent or unavailable products are silently skipped * Products that aren't members of the browsed collection are skipped, unless the store has **Allow Out-of-Collection Dynamic Linking** turned on * Subsequent products shift up to fill any gaps * Takes priority over merchandising rules and sort orders **Out-of-collection products:** When the store turns on **Allow Out-of-Collection Dynamic Linking** (**Settings** → **Developer** → **Response Options**), linked products that aren't members of the collection are added to the results and placed with the same order, `offset`, and `position` rules. They still must be published, available in the request's market, and match the request's filters; filters that rely on collection membership can exclude them. Because placement for these products runs on every page, a `position` or `offset` larger than the page size places the product on a later page. They count toward `totalResults`, and every product appears exactly once across pages. Send the same `dynamicLinking` value with every page request so each page is cut from the same ordered list. Facets and facet counts include only the collection's members. **Example:** ```json theme={null} { "dynamicLinking": { "products": ["summer-dress-blue", 8234567890123, "classic-tee-white"] } } ``` **Example with explicit positions:** pins `classic-tee-white` to position 1 and `summer-dress-blue` to position 4. ```json theme={null} { "dynamicLinking": { "products": [ { "productId": "summer-dress-blue", "position": 4 }, { "productId": "classic-tee-white", "position": 1 } ] } } ``` **offset** `integer` Number of leading positions to leave to the normal result order before the linked products. Defaults to `0`, which pins the first product at position 1. An offset of `2` places the first linked product at position 3. Products with an explicit `position` ignore `offset`. **Example:** ```json theme={null} { "dynamicLinking": { "products": ["summer-dress-blue", "classic-tee-white"], "offset": 2 } } ``` **defaultSelectedOptions** `array` Specify which product variants should be selected by default in the `first_or_matched_variant` field. This is useful for scenarios like defaulting to a specific birthstone option in a jewelry collection. **Properties** **optionCode** `string` *required* The product option code to match (e.g., `"birthstone"`, `"color"`). Option codes are automatically normalized (e.g., `"Birth Stone"` becomes `"birth_stone"`). **value** `string` *required* The option value to match (e.g., `"February"`, `"Blue"`). **Behavior:** * Uses **OR logic** - selects the first variant matching ANY of the specified option values * Falls back to the first variant by position if no match is found * **Automatically skipped** when any option or variant filters are applied (filters take precedence) * Only affects the `first_or_matched_variant` field in the response * **Works with [Variant Breakouts](/platform/variant-breakouts)** — product tiles respect your default selected options, and variant tiles respect non-breakout default selected options (preferring variants that match your preferences within each breakout group, with fallback to position ordering) **Example:** ```json theme={null} { "defaultSelectedOptions": [ { "optionCode": "birthstone", "value": "February" } ] } ``` **Multiple options example (OR logic):** ```json theme={null} { "defaultSelectedOptions": [ { "optionCode": "birthstone", "value": "February" }, { "optionCode": "birthstone", "value": "March" } ] } ``` This will select variants with either February OR March birthstone, preferring the first match found. **attributes** `string[]` Product attributes to include in the response. By default, all attributes are included except opt-in attributes noted below. 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`, `first_or_matched_variant`, and `variants`. The `collection_titles` attribute is opt-in: pass it in `attributes` to include the array of collection titles each product belongs to. It is excluded from responses by default. See the [Product Schema](/developers/product-schema/api-attributes) for detailed descriptions, including [nested field selection](/developers/product-schema/api-attributes#selecting-nested-fields) for slicing arrays and filtering collections (for example, `images[:2].src`, `variants[sku=ABC].price`, `metafields[namespace=custom]`). **filter\_group** `object` Storefront endpoints accept nested `AND`/`OR` filter groups up to two levels deep. Each nested group must contain at least one expression; empty nested groups are rejected. Metafield filter properties may include hyphens in their namespace or key, for example `metafields.my-app.fit-type`. Refer to the dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions. **pagination** `Pagination Object` **pagination** **page** `int` The current page of results to fetch. **limit** `int` The max results to fetch per page. **facets** `string[]` 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} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} // Exact facet codes "facets": ["vendor", "options.Size", "options.Color"] // Wildcard pattern "facets": ["options.*"] // Mixed exact and wildcard "facets": ["vendor", "options.*", "metafields.product.*"] ``` **retrieveFacetCount** `boolean` If the count of each facet value should be calculated. **includeFacetRanges** `boolean` If you want a min/max range for numeric facets such as price. **enrichFacetMetaobjects** `boolean` When `true`, any facet backed by a `metaobject_reference` or `list.metaobject_reference` metafield is returned with a companion `facetDisplay` object. Each entry maps a facet value (the metaobject handle) to the referenced metaobject's `display_name` and `fields`. When the metaobject defines a color or image field, the entry also carries a resolved `swatch` object. Use this when your storefront filter UI needs human-readable labels or nested field data (for example, a color name or swatch hex) instead of the raw handle. When `false` or omitted, only the handles are returned in `facets`. Values are looked up from the local metaobject cache. Handles with no matching cached metaobject are omitted from `facetDisplay` and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized shape of each entry. **discountEntitlements** `array` Apply discounts to products, variants, or collections. When provided, price-based sorting and filtering will use discounted prices. See the [Discount Entitlements](/shopify-integration/discount-entitlements) guide for detailed usage. Fixed amounts use your shop's base currency. Layers skips them on market pricing rows in a different native currency, without converting the discount. Percentage discounts still apply to those localized prices. A variant that falls back to its base price can still receive a fixed-amount discount. **Discount Entitlement Object** **entitled** `object` *required* Defines which products qualify for the discount. **entitled** **all** `boolean` When `true`, applies discount to all products. When `false`, uses products, variants, or collections arrays. **products** `string[]` Array of product IDs or handles that qualify for the discount. Maximum 250 entries. **variants** `string[] | number[]` Array of variant IDs that qualify for the discount. Maximum 250 entries. **collections** `string[]` Array of collection handles that qualify for the discount. Maximum 250 entries. **conditions** `object` Optional filter group that qualifies products for the discount based on their attributes (for example, `tags` or `vendor`). Uses the same shape as the top-level `filter_group` parameter. Matches are additive with `products`, `variants`, and `collections` on the same entitlement. **discount** `object` *required* Defines the discount to apply. **discount** **type** `string` *required* The discount type: `PERCENTAGE` or `FIXED_AMOUNT`. **value** `number` *required* The discount value. For `PERCENTAGE`, this must be a number between 0 and 100 (e.g., 10 for 10% off). For `FIXED_AMOUNT`, this is the amount in your shop's base currency, not the shopper's market currency. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). **preview\_id** `string` When provided, the Browse API loads the specified preview rule instead of the collection's active merchandising rule. Preview rules are temporary and expire one hour after creation. This parameter is automatically included when you open a preview URL from the Layers dashboard. You do not need to set it manually in production integrations. **Behavior:** * Overrides normal merchandising rule resolution for this request * Analytics and beacon events are not recorded for preview requests * Returns a `404` if the preview has expired or does not exist **forceHideOutOfStock** `boolean` (default: false) When set to `true`, products with no available variants are excluded from results regardless of the store-level [out-of-stock visibility](/help/configuration/configure-search-behavior#out-of-stock-product-visibility) setting. If your store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope) is narrowed, the same location rules apply. This is useful when a specific browse integration or page requires strict in-stock filtering even though the store default allows out-of-stock products to appear. > [!NOTE] > > Store-level out-of-stock demoting (the "At the end" option) does not apply to browse results. Browse relies on the Shopify collection itself for product ordering. When you set `forceHideOutOfStock` to `true` on a browse request, out-of-stock products are hidden entirely rather than demoted. **grid** `object` Declares the storefront grid so inline merchandising banners can reserve grid cells and products are paged around them. When `grid` is present, the response includes a top-level [`grid`](#response) block and each anchored inline banner gets a page-local [`placement`](#response) object. Omit `grid` to keep the legacy behavior. Banners return without `placement`, and pagination is computed against products only. **Properties** **columns** `integer` *required* Number of columns in your product grid. Must be between `1` and `12`. Inline banner widths are clamped to `[1, columns]` and heights to `[1, 4]`. When `pagination.limit >= columns`, height is also limited to the number of rows per page (`floor(pagination.limit / columns)`). **device** `string` (default: desktop) `"desktop"` or `"mobile"`. Selects which per-device layout (`web_layout` or `mobile_layout`) the planner reads when anchoring banners to grid cells. **Behavior:** * `cellsPerPage = floor(pagination.limit / columns) * columns`. Any remainder is dropped so pages are always whole rows. * Banners taller than one row cannot straddle a page's last row; they move forward to the next open block. * When two banners target the same cell, the second is bumped to the next open cell (row-major scan). * Banners that cannot be anchored to the grid (missing device layout, no saved `position`, or no fit within the scan buffer) are still returned, but without a `placement` key. * `totalPages` accounts for banner cells across the collection, not just product count. **Example:** ```json theme={null} { "pagination": { "page": 1, "limit": 24 }, "grid": { "columns": 4, "device": "desktop" } } ``` **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. **responseOptions** `object` Per-request overrides for response behavior. Currently controls image preload hints emitted in the `Link` response header. You can disable preloads or narrow the srcset to the breakpoints your storefront uses. You cannot enable preloads when the store has them disabled. **Properties** **mediaPreloads** `object` Controls the `Link: rel=\"preload\"` directives generated for product images in this response. See [Early hints](/sdk/performance#early-hints-link-header-preloading) for background. **Properties** **enabled** `boolean` (default: true) Set to `false` to skip the `Link` header for this request. Useful for server-rendered pages that do not benefit from preload hints, or when you want to reduce response header size. Cannot enable preloads if they are disabled at the store level. **srcsetSizes** `int[]` Custom responsive image widths (in pixels) to emit in `imagesrcset`. Each value must be an integer between `1` and `10000`. Overrides the store-level srcset configuration for this request only. When omitted, the store configuration or platform defaults are used. **sizes** `string` Media query string emitted as the `imagesizes` attribute in the preload `Link` header (for example `(max-width: 600px) 100vw, 50vw`). Tells the browser which srcset width to pick per viewport. Overrides the store-level sizes value for this request only. When omitted or empty, the store configuration is used. Each comma-separated entry may carry a media condition, including the last entry. See the [accepted format](/sdk/performance#customization) for details. The API rejects invalid values with a validation error. **Example:** ```json theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} { "responseOptions": { "mediaPreloads": { "enabled": true, "srcsetSizes": [320, 640, 960], "sizes": "(max-width: 600px) 100vw, 50vw" } } } ``` ## Response **results** `Array of Objects` **Properties** **id** `number` The unique identifier of the product. **title** `string` The title of the product. **body\_html** `string` The HTML content describing the product. **vendor** `string` The vendor of the product. **product\_type** `string` The type of the product. **created\_at** `number` The timestamp when the product was created. **handle** `string` The handle of the product. **updated\_at** `number` The timestamp when the product was updated. **published\_at** `number` The timestamp when the product was published. **tags** `Array of strings` The tags associated with the product. **combined\_listing\_parent\_product\_id** `number` The parent product id if a child in a Combined Listing. **combined\_listing\_role** `string` The role of the product if part of a Combined Listing. **images** `Array of Objects` The images of the product. **Properties** **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **variant\_ids** `Array` The variant IDs associated with the image. **metafields** `Object` The metafields of the product. **calculated** `Object` The computed attributes of the product. Only includes attributes with non-null, non-empty values. Attributes that evaluate to null or an empty string are omitted. **category** `Object` The Shopify Product Taxonomy Category of the product. **Properties** **name** `string` The name of the category leaf. **full\_name** `string` The full name of the category. **id** `string` The ID of the category. **is\_leaf** `boolean` Is the category a leaf category. **is\_root** `boolean` Is the category a root category. **first\_or\_matched\_variant** `Object` The first available variant (depending on OOS settings) or the variant matched with a filter or search query. **Properties** **id** `number` The ID of the variant. **title** `string` The title of the variant. **available** `boolean` The availability of the variant. **sku** `number` The sku of the variant. **price** `string` The price of the variant. **compare\_at\_price** `string` The compare at price of the variant. **metafields** `Object` The metafields of the variant. **selected\_options** `Array of Objects` The selected options of the variant. **Properties** **name** `string` The name of the option. **value** `string` The value of the option. **option\_value** `object` The linked metafield of the option. **position** `number` The position of the variant in the product's variant list. **inventory\_quantity** `number` Total inventory quantity across the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope), which is all locations by default. Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_policy** `string` Inventory policy for the variant: `DENY` (stop selling when out of stock) or `CONTINUE` (allow overselling). Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_levels** `object` Object mapping location IDs to available inventory quantities (e.g., `{"1001": 5, "1002": 10}`). Returns empty object `{}` when no inventory data exists. Only included when the store has the **Expose Variant Inventory** setting enabled. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **available** `boolean` The availability of the product. **price\_range** `Object` The price range of the product. **Properties** **from** `number` The starting price of the product. **to** `number` The ending price of the product. **totalResults** `number` The total number of results. When variant breakouts are enabled, this reflects the count of tiles (both product and variant tiles) rather than just products. The count is scoped to the visibility of the active shopping channel. When `context.shoppingChannel` is `"web"` (the default), only products published to the online store are counted. When it is `"app"` and an [app sales channel](/help/configuration/configure-search-behavior#app-sales-channel) is configured, only products published to that channel are counted. As a result, `totalResults` always matches the number of products a shopper can actually see for that channel. **page** `number` The current page number. **totalPages** `number` The total number of pages. Calculated based on tile count when variant breakouts are enabled. **facets** `object` If `retrieveFacetCount` is `true` then an object with keys and values of the specified attributes. When variant breakouts are enabled, facet counts reflect tile counts rather than product counts. Empty values and literal `"null"` strings are automatically excluded from facet results. Counts are scoped to the visibility of the active shopping channel, so they match the number of products (or tiles) a shopper can actually see. Products that are not published to the requester's channel, are B2B-only, or are hidden by a combined-listing role are excluded from every bucket. When `context.shoppingChannel` is `"app"` but the store does not have an [app sales channel](/help/configuration/configure-search-behavior#app-sales-channel) configured, counts fall back to the web channel. When `filter_group` is present, counts follow the standard "OR within a facet, AND across facets" pattern. Facets whose condition uses a multi-select operator (`IN`, `NOT IN`) are counted against every other active filter except the facet's own, so other values in the same facet stay selectable. Facets whose condition uses a single-select or predicate operator (`EQ`, `NEQ`, `GT`, `LT`, `BETWEEN`, `NULL`, and so on) are counted against the fully filtered result set. **facetRanges** `object` If `includeFacetRanges` is `true` then an object with keys of the facet attribute code and value is an object with min/max. **facetDisplay** `object` Returned when at least one requested facet has display data to hydrate. Keys are facet attribute codes; values map each facet value to a display object. Metaobject-reference facets require `enrichFacetMetaobjects: true` and map each handle to the metaobject's `display_name` and `fields`. Entries also carry a `swatch` object when the metaobject defines a color or image field. Handles with no matching cached metaobject are omitted here and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized field shape and the [Facets API response](/api-reference/facets#response) for the `swatch` shape. For `variants.pickup_locations`, each entry maps a Shopify location id to the location's `id`, `name`, `address`, `instructions`, `pickupTime`, and (when the filter is a `geoRadius`) `distance` and `distanceUnit`. Pickup entries are returned whenever pickup facets are requested, regardless of `enrichFacetMetaobjects`. See [Local pickup filtering](/engine/geospatial-filtering#local-pickup-filtering). **banners** `array of objects` Merchandising banners emitted by any [merchandising rules](/platform/merchandising) that matched this request. Flat across all applied rules and pre-sorted by `sort_index`. Your storefront is responsible for rendering banners into the grid. See [Rendering banners in Liquid](/developers/rendering-banners-in-liquid) and [Rendering banners with the SDK](/developers/rendering-banners-with-the-sdk). Each banner carries the `rule_id` of the rule that produced it. `_meta.appliedRules` still lists every applied rule ID. **Properties** **id** `string` Banner ULID. **rule\_id** `string | null` ID of the [merchandising rule](/platform/merchandising) that produced this banner. Send it on `banner_impression` and `banner_click` [tracking events](/tracking-api/event-types) so engagement attributes back to the rule. **name** `string` Internal name (not shown to shoppers). **mode** `string` `"inject"` or `"overtake"`. `inject` inserts the banner at `position` and shifts trailing products; `overtake` replaces the product at `position`. **link** `string | null` Click-through URL. Only honored on `inject` banners, and only meaningful when `type` is `"link"` (the built-in type). Custom banner types put their click-through URL inside `data` instead. **type** `string` Banner type slug. `"link"` for the built-in type, otherwise the slug of a custom [banner type](/platform/merchandising/banner-types) defined for your store. Storefronts switch renderers on this value. **data** `object` Saved values for the banner type's field schema. Keys match the schema's `key` values. Only keys defined in the current schema are returned. Retyped or removed fields are dropped. `product_reference`, `collection_reference`, and `variant_reference` fields (and their `list.` variants) are resolved to `{ "id", "handle" }` objects; unpublished references are omitted. **sort\_index** `number` Application order when a rule has multiple banners. Lower wins on conflicting cells. **web\_media** `object` Desktop media. `{ id, src, alt, width, height, source, mediaContentType }`. `source` is `"store_file"` today and `mediaContentType` is `"IMAGE"` today. **mobile\_media** `object` Mobile media. Same shape as `web_media`. **web\_layout** `object` Desktop layout. `{ placement: "hero" | "inline", width, height, position }`. For `hero`, render a horizontal banner across the full product-grid width above the first product row; ignore the cell spans and `position`. For `inline`, `position` is a row-major 0-indexed grid cell, and `width` and `height` are column and row spans, not image dimensions in pixels. Inline width is bounded by the grid columns, not limited to one or two; inline banners can span up to four rows, and the editor resizes both width and height. **mobile\_layout** `object` Mobile layout. Same shape as `web_layout`. **placement** `object` Only present when the request includes a [`grid`](#body) block and the banner is an inline banner anchored to a cell on the current page. Hero banners never carry `placement` and are always returned. Inline banners that could not be anchored (missing device layout, no saved `position`, or no fit within the scan buffer) are still returned without this key so they do not vanish from the storefront. **Properties** **page** `number` The 1-indexed page this placement is anchored to. Always matches the requested `pagination.page`. **row** `number` 0-indexed row within the current page. **colStart** `number` 0-indexed column where the banner starts. Combined with `colSpan`, gives the CSS `grid-column: colStart + 1 / span colSpan`. **colSpan** `number` Number of columns the banner spans. Clamped to `[1, grid.columns]`. **rowSpan** `number` Number of rows the banner spans. Clamped to `[1, 4]` and, when `pagination.limit >= grid.columns`, to the number of rows per page. **grid** `object` Only present when the request includes a [`grid`](#body) block. Echoes the resolved grid geometry so the storefront can render banners into the exact cells the planner used to page products. **Properties** **columns** `number` Column count from the request. **device** `string` `"desktop"` or `"mobile"`, from the request. **cellsPerPage** `number` Total grid cells on this page, equal to `floor(pagination.limit / columns) * columns`. **rows** `number` Number of full rows on this page. **bannerCells** `number` How many of `cellsPerPage` are occupied by inline banner placements. The remaining cells hold the products in `results`. **attributionToken** `string` A unique request identifier (ULID) for this API call. Use this token to correlate browse requests with analytics events via the [Beacon API](/tracking-api/send-events), and to match requests to entries in the [Search Inspector](/shopify-integration/storefront-pixel#search-inspector). **\_meta** `object` **Properties** **appliedRules** `Array of strings` The merchandising rule IDs applied to the request. **appliedSearchRules** `Array of strings` The IDs of [request transforms](/platform/request-transforms) whose targeting conditions matched this request. Returns an empty array when no request transforms matched. Use this to verify which request transforms are evaluating against a given browse request. **appliedSearchRuleActions** `array of objects` One entry per action executed by a matched request transform, in execution order. Use `changed` to tell whether an action actually modified the request. A matched rule can appear in `appliedSearchRules` while all of its actions report `changed: false`. See [Debugging with `_meta`](/platform/request-transforms#debugging-with-_meta). **Properties** **ruleId** `string` The ID of the request transform that owns the action. **type** `string` The action type, for example `add_filter_group` or `override_sort_order`. **changed** `boolean` `true` when the action modified the request. `false` when the action was a no-op, for example an `override_sort_order` action matching the already-active sort order. **error** `string` Only present when the action could not run. `"unsupported_action_type"` indicates a stored action type the engine cannot execute. The action is skipped and the rest of the request proceeds normally. **variantBreakouts** `array of objects` Array of variant breakout configurations applied to this collection. Only present when one or more variant breakouts are active for the collection. Multiple breakouts with different option codes can work simultaneously in the same collection. Each object has the structure `{optionCode: "Stone"}`. **Properties** **optionCode** `string` The product option code that determines which variants are broken out (e.g., "Stone", "Color"). Each product is broken out by the first matching option code from the array. **mediaPreloads** `object` Echoes the image preload configuration used to build the `Link` response header for this request. Only present when image preloads are emitted. See [Early hints](/sdk/performance#early-hints-link-header-preloading). **Properties** **srcsetSizes** `int[]` The responsive image widths (in pixels) used in the `imagesrcset` of the `Link` header. Reflects the request override when provided, otherwise the store-level configuration or platform defaults. **discountEntitlements** `array of objects` Echoes the [discount entitlements](/shopify-integration/discount-entitlements) applied to this request. Only present when the request included `discountEntitlements` (either directly or via a matched [request transform](/platform/request-transforms)). Use this to render discount badges or labels on the storefront without re-deriving which entitlements matched. Each entry mirrors the entitlement shape sent in the request. **Properties** **entitled** `object` The entitlement criteria that qualified products for the discount. Contains any of `all`, `products`, `variants`, `collections`, or `conditions`. See the [entitlement criteria](/shopify-integration/discount-entitlements#entitlement-criteria) reference. **discount** `object` The discount Layers applied. **Properties** **type** `string` `"PERCENTAGE"` or `"FIXED_AMOUNT"`. **value** `number` The discount value. Percent off for `PERCENTAGE`, shop base-currency amount for `FIXED_AMOUNT`. An echoed entitlement doesn't guarantee a price reduction on every variant; see the shared `discountEntitlements` request parameter for market-currency limits. **\_workflow** `array of objects` An ordered trace of processing steps the engine performed to produce results for this request. Each entry represents a stage in the browse pipeline, recorded in the order it was executed. Use this field to understand which merchandising rules, sort orders, and boosts were applied. This field is useful for debugging browse behavior in development and is also surfaced in the [Search Inspector](/shopify-integration/storefront-pixel#search-inspector) panel. **Properties** **type** `string` The processing step type. Possible values include: * `"rule-applied"` — A merchandising rule was applied. The `payload` contains the rule identifier. * `"ranking-rules"` — Ranking rules influenced result ordering. See the [Text Search](/api-reference/search) documentation for a full list of possible step types. **payload** `string | array | object` The data associated with this processing step. The structure varies by `type`. ### Response headers Every API response includes the following headers for request tracing and performance optimization: | Header | Description | | - | - | | `x-request-id` | A unique identifier (ULID) for the request. This matches the `attributionToken` in the response body. Use it to correlate requests across your infrastructure or when contacting support. | | `x-layers-build` | The Layers build version that served the request. | | `X-Layers-Results-Cache` | Indicates whether the response was served from the results cache. Returns `HIT` when cached results were used, or `MISS` when results were computed fresh. | | `Link` | Contains `rel="preload"` directives for product images in the response (up to 6 items), enabling browsers and CDNs to begin fetching images before your application processes the JSON body. See [Early hints](/sdk/performance#early-hints-link-header-preloading) for configuration options. Only included when early hints are enabled (enabled by default). | ### Variant breakouts When variant breakouts are configured, results may include both product tiles and variant tiles. Each result includes a `__typename` field to identify the tile type: **\_\_typename** `string` Identifies the type of tile in the results: * `"Product"` - A standard product tile * `"Variant"` - An individual variant tile from a product with a configured breakout option #### Variant tile fields Variant tiles include additional fields to identify the specific variant: **product\_id** `number` The parent product ID. Use this to link back to the full product or group variants from the same product. **variant\_id** `number` The specific variant ID. For variant tiles, this matches the `id` field. > [!NOTE] > > For variant tiles, the `id` field contains the variant ID (not the product ID). The `title` field is formatted as `"{product title} - {option value}"` by default (e.g., "Amethyst Ring - Rose Quartz"), but the format can be configured per breakout. If the breakout's **Include Option Value in Title** setting is disabled, the title is the original product title. See the [Variant Breakouts](/platform/variant-breakouts) documentation for more details. ```json Request theme={null} POST /storefront/v1/browse/summer-collection { "sort_order_code": "best-sellers", "pagination": { "page": 1, "limit": 20 }, "retrieveFacetCount": true, "facets": ["vendor", "product_type"], "context": { "geo": { "country": "US", "province": "California" }, "marketing": { "source": "google", "medium": "cpc", "campaign": "summer-sale" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123", "deviceId": "device-uuid" } } ``` ```json Response theme={null} { "results": [ { "id": 7003338965178, "title": "SUPREME SEALLINE SEE POUCH SMALL", "body_html": "The Supreme Sealline See Pouch Small is a versatile and waterproof storage solution that seamlessly marries utility and style. With its clear window for easy visibility and the iconic Supreme branding, it's a sought-after accessory for those who appreciate keeping their essentials dry while making a fashion statement, whether at the beach or in the city..", "vendor": "SUPREME", "product_type": "Accessories", "created_at": "2022-02-05T01:22:05.000000Z", "handle": "supreme-pouch-44370ss18a32-sm", "updated_at": "2023-10-25T20:47:04.000000Z", "published_at": "2022-02-05T01:22:05.000000Z", "tags": [ "consignment" ], "images": [ { "alt": "SUPREME POUCH", "src": "https://cdn.shopify.com/s/files/1/0588/3677/9194/products/ss18_supreme_tnf_pouch_blk_2-l_5fb1316e-22f7-4702-9953-57f3fbdda5be.jpg?v=1644047927", "width": 800, "height": 534, "variant_ids": [] } ], "metafields": { "product": { "alias": "SEALLINE SEE POUCH SMALL", "colorway": "BLACK", "styleCode": "SS18A30 BLACK", "yearOfRelease": 2018, "searchColor": [ "black" ] } }, "available": true, "price_range": { "from": 30, "to": 30 } } ], "totalResults": 1000, "page": 1, "totalPages": 20, "facets": { "vendor": { "ADIDAS": 30, "JORDAN": 336, "NEW BALANCE": 15, "NIKE": 384, "REEBOK": 4, "SUPREME": 624, "VANS": 32 } }, "attributionToken": "01JRVX8M3N4P5Q6R7S8T9U0V1W", "_meta": { "appliedRules": [], "appliedSearchRules": [], "appliedSearchRuleActions": [] }, "_workflow": [ { "type": "rule-applied", "payload": "rule_01JRVX8M3N4P5Q6R7S8T9U0V1W" } ] } ``` # Facets API: Get Collection Facets Source: https://docs.uselayers.com/api-reference/facets POST /{collection_handle}/facets Facets API endpoint that returns facet values and result counts for a collection without running a full browse query, ideal for filter sidebars. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Path parameters **collection\_handle** `string` *required* The handle of the collection to retrieve facets for. ## Body **facets** `string[]` 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.*"] ``` **retrieveFacetCount** `boolean` If the count of each facet value should be calculated. **includeFacetRanges** `boolean` If you want a min/max range for numeric facets such as price. **enrichFacetMetaobjects** `boolean` When `true`, any facet backed by a `metaobject_reference` or `list.metaobject_reference` metafield is returned with a companion `facetDisplay` object. Each entry maps a facet value (the metaobject handle) to the referenced metaobject's `display_name` and `fields`. When the metaobject defines a color or image field, the entry also carries a resolved `swatch` object. Use this when your storefront filter UI needs human-readable labels or nested field data (for example, a color name or swatch hex) instead of the raw handle. When `false` or omitted, only the handles are returned in `facets`. Values are looked up from the local metaobject cache. Handles with no matching cached metaobject are omitted from `facetDisplay` and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized shape of each entry. **filter\_group** `object` Storefront endpoints accept nested `AND`/`OR` filter groups up to two levels deep. Each nested group must contain at least one expression; empty nested groups are rejected. Metafield filter properties may include hyphens in their namespace or key, for example `metafields.my-app.fit-type`. Refer to the dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions. **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. **discountEntitlements** `array` Apply discounts to products, variants, or collections. When provided, price-based sorting and filtering will use discounted prices. See the [Discount Entitlements](/shopify-integration/discount-entitlements) guide for detailed usage. Fixed amounts use your shop's base currency. Layers skips them on market pricing rows in a different native currency, without converting the discount. Percentage discounts still apply to those localized prices. A variant that falls back to its base price can still receive a fixed-amount discount. **Discount Entitlement Object** **entitled** `object` *required* Defines which products qualify for the discount. **entitled** **all** `boolean` When `true`, applies discount to all products. When `false`, uses products, variants, or collections arrays. **products** `string[]` Array of product IDs or handles that qualify for the discount. Maximum 250 entries. **variants** `string[] | number[]` Array of variant IDs that qualify for the discount. Maximum 250 entries. **collections** `string[]` Array of collection handles that qualify for the discount. Maximum 250 entries. **conditions** `object` Optional filter group that qualifies products for the discount based on their attributes (for example, `tags` or `vendor`). Uses the same shape as the top-level `filter_group` parameter. Matches are additive with `products`, `variants`, and `collections` on the same entitlement. **discount** `object` *required* Defines the discount to apply. **discount** **type** `string` *required* The discount type: `PERCENTAGE` or `FIXED_AMOUNT`. **value** `number` *required* The discount value. For `PERCENTAGE`, this must be a number between 0 and 100 (e.g., 10 for 10% off). For `FIXED_AMOUNT`, this is the amount in your shop's base currency, not the shopper's market currency. ## Response This endpoint returns facet metadata only. It does **not** return product results, pagination fields, or an `attributionToken`. If you need products alongside facets, use the [Browse API](/api-reference/browse) with `retrieveFacetCount` enabled instead. **facets** `object` Object whose keys are facet attribute codes and whose values are objects mapping each facet value to its result count. Only returned when `retrieveFacetCount` is `true`. Counts are scoped to the visibility of the active shopping channel, so they always match the number of products a shopper can actually see in the collection for that channel. Products that are not published to the requester's channel, are B2B-only, or are hidden by a combined-listing role are excluded from every bucket. When the request is a mobile app request but the store does not have an [app sales channel](/help/configuration/configure-search-behavior#app-sales-channel) configured, counts fall back to the web channel. When `filter_group` is present, counts follow the standard "OR within a facet, AND across facets" pattern. Facets whose condition uses a multi-select operator (`IN`, `NOT IN`) are counted against every other active filter except the facet's own condition, so other values in the same facet stay selectable. Facets whose condition uses a single-select or predicate operator (`EQ`, `NEQ`, `GT`, `LT`, `BETWEEN`, `NULL`, and so on) are counted against the fully filtered result set. Facets without an active condition are always counted against the full filter group. **facetRanges** `object` Object whose keys are facet attribute codes and whose values are objects with `min` and `max` numeric properties. Only returned when `includeFacetRanges` is `true`. Ranges are computed only over products visible on the active shopping channel. A numeric range (for example, a price slider's `min` and `max`) cannot come from a product the shopper cannot see. `variants.price` and `variants.compare_at_price` counts and ranges are always converted to the resolved market's currency. A price slider's `min` and `max` match the prices a shopper actually sees for their market. The market is resolved from `context.market` when provided, or from `context.geo.country` otherwise, and falls back to the store's primary market. This matches the pricing behavior of the [Browse API](/api-reference/browse) with `retrieveFacetCount` enabled. Both endpoints return consistent counts and ranges for the same filter group. When the request also includes `discountEntitlements`, discounts are applied on top of the market-converted price. See [Discount entitlements](/shopify-integration/discount-entitlements) for details. **facetDisplay** `object` Returned when at least one requested facet has display data to hydrate. Omitted when empty. Keys are facet attribute codes. Values are objects that map each facet value to a display object: * For facets backed by a `metaobject_reference` or `list.metaobject_reference` metafield, each entry maps the referenced metaobject's handle to its `display_name` and `fields`. These entries require `enrichFacetMetaobjects: true` and are hydrated from the local metaobject cache. Handles with no cached metaobject are omitted from `facetDisplay` and remain as plain values under `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized field shape. * Metaobject entries also carry a `swatch` object when the metaobject defines a color or image field. The swatch is ready to render as an image thumbnail or color chip: * `{ "type": "image", "url": "…", "alt": "…" }` when the metaobject has a `file_reference` or `list.file_reference` field that points at an image. `alt` is present only when the image has alt text. Videos and documents in the field are skipped; the swatch comes from the field's first image. * `{ "type": "color", "colors": ["#191970"] }` when the metaobject has a `color` or `list.color` field instead. `colors` lists every hex value on the field, so a two-tone value carries two entries. An image swatch wins over a color swatch when the metaobject defines both field types. Among fields of the same kind, the field order on the metaobject definition decides. The `swatch` key is absent when the metaobject has no color or image field. * For `variants.pickup_locations`, each entry maps a Shopify location id to the location's `id`, `name`, `address`, `instructions`, `pickupTime`, and (when the filter is a `geoRadius`) `distance` and `distanceUnit`. These entries are returned whenever pickup facets are requested, regardless of `enrichFacetMetaobjects`. See [Local pickup filtering](/engine/geospatial-filtering#local-pickup-filtering) for the full shape. **filters** `object` Echo of the filter group expressions that were applied when computing the counts. Useful for verifying that the request's `filter_group` was interpreted as expected. ## When to use Use this endpoint when you need facet data without fetching product results. Common scenarios include: * **Pre-loading filter options**: Fetch available filter values before the shopper starts browsing * **Sidebar filters**: Build filter UIs that show available options and counts independently of the product grid * **Reducing payload size**: Avoid fetching full product data when you only need facet information For combined product results and facets in a single request, use the [Browse API](/api-reference/browse) with `retrieveFacetCount` enabled instead. ```json Request theme={null} POST /storefront/v1/summer-collection/facets { "facets": ["vendor", "product_type", "variants.price", "metafields.custom.color_swatch"], "retrieveFacetCount": true, "includeFacetRanges": true, "enrichFacetMetaobjects": true, "context": { "market": "CA", "geo": { "country": "CA" } }, "discountEntitlements": [ { "entitled": { "all": false, "collections": ["summer-collection"] }, "discount": { "type": "PERCENTAGE", "value": 20 } } ] } ``` ```json Response theme={null} { "facets": { "vendor": { "Nike": 45, "Adidas": 30, "New Balance": 25, "Puma": 20, "Reebok": 15, "Vans": 15 }, "product_type": { "Shoes": 80, "Apparel": 50, "Accessories": 20 }, "metafields.custom.color_swatch": { "midnight-blue": 42, "sunset-orange": 18 } }, "facetRanges": { "variants.price": { "min": 23.99, "max": 199.99 } }, "facetDisplay": { "metafields.custom.color_swatch": { "midnight-blue": { "handle": "midnight-blue", "display_name": "Midnight Blue", "fields": { "name": "Midnight Blue", "hex_code": "#191970" }, "swatch": { "type": "color", "colors": ["#191970"] } }, "sunset-orange": { "handle": "sunset-orange", "display_name": "Sunset Orange", "fields": { "name": "Sunset Orange", "swatch_image": { "id": "gid://shopify/MediaImage/123456", "url": "https://cdn.shopify.com/s/files/sunset-orange.png", "alt": "Sunset Orange fabric" } }, "swatch": { "type": "image", "url": "https://cdn.shopify.com/s/files/sunset-orange.png", "alt": "Sunset Orange fabric" } } } }, "filters": {} } ``` # Autocomplete: Get Suggestions Source: https://docs.uselayers.com/api-reference/predict GET /search/complete?query={query} Autocomplete API endpoint returning ranked search-query suggestions and top trending queries as shoppers type into your storefront search bar. The Autocomplete endpoint returns ranked **query-text suggestions** for a partial search term. It does **not** return products, product previews, or images. Use the [Search](/api-reference/search) endpoint to fetch products for a chosen suggestion. When no `query` is provided, the endpoint returns the store's top trending queries (subject to the same brand curation rules as live suggestions). ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Query parameters **query** `string` The partial query you want suggestions for. Maximum 255 characters. Sanitized server-side; queries shorter than 2 characters after sanitization are treated as empty and return trending suggestions instead. ## Response **matchedQueries** `string[]` Ranked array of suggestion strings. Prefix matches appear first, followed by non-prefix matches that clear the relevance threshold. Each string is the suggestion text the shopper should see: either the cluster's canonical query or its curated display label when one is configured. **originalQuery** `string | null` The `query` value exactly as sent by the client. `null` when the request omits `query` or when the sanitized query is too short. **normalizedQuery** `string | null` The lowercased, trimmed form of `originalQuery` used internally for matching. `null` when no query was effectively provided. **\_meta** `object` Optional metadata. Present only when a [semantic redirect](/platform/semantic-redirects) matches the current query. **Properties** **redirect** `object` **Properties** **url** `string` The destination URL the storefront should navigate to. Suggestions are still returned alongside the redirect. With the Layers app embed enabled, the Storefront Pixel follows the redirect when the shopper submits the query or clicks its suggestion, so theme code only renders the suggestion list. Headless storefronts without the embed decide whether to follow the redirect immediately or render the suggestion list. > [!NOTE] > > **Semantic Redirects**: When the autocomplete query matches a configured [semantic redirect](/platform/semantic-redirects) term, either exactly or semantically, the response includes a `_meta.redirect` object with the redirect URL. This lets you redirect users directly from the typeahead experience before they submit a full search. ## Suggestion quality Layers applies several techniques to keep autocomplete suggestions relevant and concise. ### Regional suggestions Suggestion candidates can be scoped to the shopper's country before matching runs. Layers resolves the country from IP-based geolocation and applies the store's region mode: * **Separate suggestions per region** (default): shoppers in each country see suggestions built from that country's own search activity. If a country doesn't yet have enough curated search history to stand on its own, shoppers there receive the shared, store-wide suggestion set instead. * **One set of suggestions for all shoppers**: every request returns the same store-wide suggestion set, regardless of the shopper's location. Requests with no resolvable location always receive the store-wide set. Configure the mode in the Layers dashboard under **Settings → Autocomplete**. See [Configure autocomplete curation](/help/configuration/configure-autocomplete-curation#regional-suggestions) for steps. ### Brand curation You can layer a natural-language brand prompt on top of the default suggestion pipeline. Layers uses the prompt, together with your store description, to suppress off-brand suggestions and rewrite display labels for customers. Suppressed clusters never appear in `matchedQueries`, and curated clusters return their rewritten text in place of the canonical query. Matching against raw customer queries is unchanged. See [Autocomplete curation](/platform/autocomplete-curation) for configuration details. ### Stem deduplication Autocomplete automatically collapses singular and plural variants of the same word into a single suggestion. For example, if your query data contains both "diamond" and "diamonds", only the higher-scoring canonical form is returned. This also applies to other English stem variations like "berry" and "berries" or "long sleeve" and "long-sleeve". Stem awareness extends to query matching as well. When a shopper types "diamonds", autocomplete finds suggestions containing the singular "diamond" and vice versa, so singular and plural queries produce the same suggestion list. When multiple suggestions share the same stem, the suggestion with the highest relevance score is kept. Shorter canonical forms (typically the singular) win ties, which keeps the suggestion list clean and predictable. ### Relevance gating Suggestions that don't closely match the query text are filtered out before results are returned. Prefix matches (where the query is the beginning of a suggestion) always pass through. Non-prefix matches must meet a minimum text-similarity threshold to appear. This prevents semantically distant suggestions from surfacing alongside direct matches. ```json Response theme={null} { "matchedQueries": [ "sup", "supreme" ], "originalQuery": "sup", "normalizedQuery": "sup" } ``` ```json Response (with semantic redirect) theme={null} { "matchedQueries": [ "support" ], "originalQuery": "support", "normalizedQuery": "support", "_meta": { "redirect": { "url": "https://yourstore.com/pages/contact-us" } } } ``` ```json Response (no query — trending suggestions) theme={null} { "matchedQueries": [ "summer dresses", "linen shirts", "white sneakers" ], "originalQuery": null, "normalizedQuery": null } ``` # Text Search: Execute Search Source: https://docs.uselayers.com/api-reference/search POST /search/{searchQuery}/execute Text Search API endpoint to run semantic product searches with typo tolerance, query understanding, faceting, and personalization across your catalog. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) **X-SDK-Client** `string` Optional header to identify SDK client requests. Format: `sdk-name/version` (e.g., `layers-js-sdk/1.0.0`). When provided with version >= 1.0.0, the server returns HTTP 425 (Too Early) with a `Retry-After` header when prepared search data isn't ready yet, instead of blocking, so the client can poll until the search is ready. ## Path parameters **searchQuery** `string` *required* The url-encoded search query. Layers normalizes the query before validating it, stripping invisible characters and converting Unicode punctuation to ASCII equivalents. After normalization, the query must be 2 to 255 characters. Queries outside this range return HTTP 422. ## Body **attributes** `string[]` Product attributes to include in the response. By default, all attributes are included except opt-in attributes noted below. 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`, `first_or_matched_variant`, and `variants`. The `collection_titles` attribute is opt-in: pass it in `attributes` to include the array of collection titles each product belongs to. It is excluded from responses by default. See the [Product Schema](/developers/product-schema/api-attributes) for detailed descriptions, including [nested field selection](/developers/product-schema/api-attributes#selecting-nested-fields) for slicing arrays and filtering collections (for example, `images[:2].src`, `variants[sku=ABC].price`, `metafields[namespace=custom]`). **search\_id** `string` ULID identifier from the [Prepare Search](/api-reference/search-prepare) endpoint for optimized search execution. When provided, reuses the precomputed intent analysis and query expansions from that prepare call so the search returns faster. **filter\_group** `object` Storefront endpoints accept nested `AND`/`OR` filter groups up to two levels deep. Each nested group must contain at least one expression; empty nested groups are rejected. Metafield filter properties may include hyphens in their namespace or key, for example `metafields.my-app.fit-type`. Refer to the dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions. **pagination** `Pagination Object` **pagination** **page** `int` The current page of results to fetch. **limit** `int` The max results to fetch per page. **facets** `string[]` 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.*"] ``` **retrieveFacetCount** `boolean` If the count of each facet value should be calculated. **includeFacetRanges** `boolean` If you want a min/max range for numeric facets such as price. **enrichFacetMetaobjects** `boolean` When `true`, any facet backed by a `metaobject_reference` or `list.metaobject_reference` metafield is returned with a companion `facetDisplay` object. Each entry maps a facet value (the metaobject handle) to the referenced metaobject's `display_name` and `fields`. When the metaobject defines a color or image field, the entry also carries a resolved `swatch` object. Use this when your storefront filter UI needs human-readable labels or nested field data (for example, a color name or swatch hex) instead of the raw handle. When `false` or omitted, only the handles are returned in `facets`. Values are looked up from the local metaobject cache. Handles with no matching cached metaobject are omitted from `facetDisplay` and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized shape of each entry. **discountEntitlements** `array` Apply discounts to products, variants, or collections. When provided, price-based sorting and filtering will use discounted prices. See the [Discount Entitlements](/shopify-integration/discount-entitlements) guide for detailed usage. Fixed amounts use your shop's base currency. Layers skips them on market pricing rows in a different native currency, without converting the discount. Percentage discounts still apply to those localized prices. A variant that falls back to its base price can still receive a fixed-amount discount. **Discount Entitlement Object** **entitled** `object` *required* Defines which products qualify for the discount. **entitled** **all** `boolean` When `true`, applies discount to all products. When `false`, uses products, variants, or collections arrays. **products** `string[]` Array of product IDs or handles that qualify for the discount. Maximum 250 entries. **variants** `string[] | number[]` Array of variant IDs that qualify for the discount. Maximum 250 entries. **collections** `string[]` Array of collection handles that qualify for the discount. Maximum 250 entries. **conditions** `object` Optional filter group that qualifies products for the discount based on their attributes (for example, `tags` or `vendor`). Uses the same shape as the top-level `filter_group` parameter. Matches are additive with `products`, `variants`, and `collections` on the same entitlement. **discount** `object` *required* Defines the discount to apply. **discount** **type** `string` *required* The discount type: `PERCENTAGE` or `FIXED_AMOUNT`. **value** `number` *required* The discount value. For `PERCENTAGE`, this must be a number between 0 and 100 (e.g., 10 for 10% off). For `FIXED_AMOUNT`, this is the amount in your shop's base currency, not the shopper's market currency. **defaultSelectedOptions** `array` Specify which product variants should be selected by default in the `first_or_matched_variant` field. This is a presentation preference for search and browse results, not a product filter. Request transforms can set or replace this complete list with the `set_default_selected_options` action. **Properties** **optionCode** `string` *required* The product option code to match (e.g., `"birthstone"`, `"color"`). Option codes are automatically normalized (e.g., `"Birth Stone"` becomes `"birth_stone"`). **value** `string` *required* The option value to match (e.g., `"February"`, `"Blue"`). **Behavior:** * Uses **OR logic** - selects the first variant matching ANY of the specified option values * Query and keyword matches, plus pinned variant choices, take priority over these defaults * Configured defaults take priority over a confident semantic match to a variant * If no variant matches the configured defaults, a confident semantic match can still be selected before falling back to the first variant by position * **Automatically skipped** when any option or variant filters are applied (filters take precedence) * Only affects the `first_or_matched_variant` field in the response * **Works with [Variant Breakouts](/platform/variant-breakouts)**: product tiles respect default selected options, and variant tiles respect non-breakout default selected options, preferring matching variants within each breakout group and falling back to position when needed. This does not change breakout grouping or collapse breakout tiles. **Example:** ```json theme={null} { "defaultSelectedOptions": [ { "optionCode": "birthstone", "value": "February" } ] } ``` **Multiple options example (OR logic):** ```json theme={null} { "defaultSelectedOptions": [ { "optionCode": "birthstone", "value": "February" }, { "optionCode": "birthstone", "value": "March" } ] } ``` This selects variants with either February OR March birthstone, preferring the first match found. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. **sort\_order\_code** `string` Code of the sort order to apply. Use `"relevance"` for the default relevance-based ranking, or any custom sort order code configured in your store. Retrieve available sort order codes from the [Sort Orders API](/api-reference/sort-orders). **forceHideOutOfStock** `boolean` (default: false) When set to `true`, products with no available variants are excluded from results regardless of the store-level [out-of-stock visibility](/help/configuration/configure-search-behavior#out-of-stock-product-visibility) setting. If your store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope) is narrowed, the same location rules apply. This is useful when a specific search integration or page requires strict in-stock filtering even though the store default allows out-of-stock products to appear. **responseOptions** `object` Per-request overrides for response behavior. Currently controls image preload hints emitted in the `Link` response header. You can disable preloads or narrow the srcset to the breakpoints your storefront uses. You cannot enable preloads when the store has them disabled. **Properties** **mediaPreloads** `object` Controls the `Link: rel=\"preload\"` directives generated for product images in this response. See [Early hints](/sdk/performance#early-hints-link-header-preloading) for background. **Properties** **enabled** `boolean` (default: true) Set to `false` to skip the `Link` header for this request. Useful for server-rendered pages that do not benefit from preload hints, or when you want to reduce response header size. Cannot enable preloads if they are disabled at the store level. **srcsetSizes** `int[]` Custom responsive image widths (in pixels) to emit in `imagesrcset`. Each value must be an integer between `1` and `10000`. Overrides the store-level srcset configuration for this request only. When omitted, the store configuration or platform defaults are used. **sizes** `string` Media query string emitted as the `imagesizes` attribute in the preload `Link` header (for example `(max-width: 600px) 100vw, 50vw`). Tells the browser which srcset width to pick per viewport. Overrides the store-level sizes value for this request only. When omitted or empty, the store configuration is used. Each comma-separated entry may carry a media condition, including the last entry. See the [accepted format](/sdk/performance#customization) for details. The API rejects invalid values with a validation error. **Example:** ```json theme={null} { "responseOptions": { "mediaPreloads": { "enabled": true, "srcsetSizes": [320, 640, 960], "sizes": "(max-width: 600px) 100vw, 50vw" } } } ``` ## Why result totals can differ `totalResults` is computed for each request. It is the number of products that clear Layers' relevance thresholds for that request's query interpretation and filters. Two requests for the same text can return different totals when: * **They use different prepare calls.** Each `search_id` carries its own query expansions and intent analysis. To avoid generating intent rules for every keystroke, Layers only generates a new intent modifier (for example, a "jeans" category preference) once it has seen the same query text before, or once the query belongs to a known query cluster. An instant-results request fired while the shopper is still typing is often the first time Layers sees that text, so it can be interpreted more broadly or more narrowly than the results-page search that follows. * **They use different filters.** `filter_group` values, system filters, and [variant breakouts](/platform/variant-breakouts) all change what is counted. * **The catalog or query data changed between the calls.** Examples are a catalog sync, a newly learned query cluster, or an updated merchandising rule. Relevance thresholds are relative to the best match for each request. Any difference in how the query is interpreted therefore changes how many products are counted, not just their order. **Which count to show:** use `totalResults` from the results-page search request, meaning the request that renders the grid with the shopper's filters. Treat totals from instant-results or preview requests (small `limit`, no facets) as approximate. If you show a "View all N results" link in a typeahead, either leave out the number or take it from the same `search_id` the results page will use. > [!NOTE] > > The [Autocomplete](/api-reference/predict) endpoint returns query suggestions only and has no product count. A count shown next to typeahead products always comes from a separate Search request. ## Response **results** `Array of Objects` **Properties** **id** `number` The unique identifier of the product. **title** `string` The title of the product. **body\_html** `string` The HTML content describing the product. **vendor** `string` The vendor of the product. **product\_type** `string` The type of the product. **created\_at** `number` The timestamp when the product was created. **handle** `string` The handle of the product. **updated\_at** `number` The timestamp when the product was updated. **published\_at** `number` The timestamp when the product was published. **tags** `Array of strings` The tags associated with the product. **combined\_listing\_parent\_product\_id** `number` The parent product id if a child in a Combined Listing. **combined\_listing\_role** `string` The role of the product if part of a Combined Listing. **images** `Array of Objects` The images of the product. **Properties** **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **variant\_ids** `Array` The variant IDs associated with the image. **metafields** `Object` The metafields of the product. **calculated** `Object` The computed attributes of the product. Only includes attributes with non-null, non-empty values. Attributes that evaluate to null or an empty string are omitted. **category** `Object` The Shopify Product Taxonomy Category of the product. **Properties** **name** `string` The name of the category leaf. **full\_name** `string` The full name of the category. **id** `string` The ID of the category. **is\_leaf** `boolean` Is the category a leaf category. **is\_root** `boolean` Is the category a root category. **first\_or\_matched\_variant** `Object` The first available variant (depending on OOS settings) or the variant matched with a filter or search query. **Properties** **id** `number` The ID of the variant. **title** `string` The title of the variant. **available** `boolean` The availability of the variant. **sku** `number` The sku of the variant. **price** `string` The price of the variant. **compare\_at\_price** `string` The compare at price of the variant. **metafields** `Object` The metafields of the variant. **selected\_options** `Array of Objects` The selected options of the variant. **Properties** **name** `string` The name of the option. **value** `string` The value of the option. **option\_value** `object` The linked metafield of the option. **position** `number` The position of the variant in the product's variant list. **inventory\_quantity** `number` Total inventory quantity across the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope), which is all locations by default. Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_policy** `string` Inventory policy for the variant: `DENY` (stop selling when out of stock) or `CONTINUE` (allow overselling). Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_levels** `object` Object mapping location IDs to available inventory quantities (e.g., `{"1001": 5, "1002": 10}`). Returns empty object `{}` when no inventory data exists. Only included when the store has the **Expose Variant Inventory** setting enabled. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **available** `boolean` The availability of the product. **price\_range** `Object` The price range of the product. **Properties** **from** `number` The starting price of the product. **to** `number` The ending price of the product. > [!NOTE] > > **Semantic Redirects**: When a text search query semantically matches a configured redirect term, the response will include a `_meta.redirect` object with the redirect URL. In this case, the `results` array will be empty and `totalResults` will be 0. Semantic redirects only apply to text search queries (not image or similar product searches). > [!NOTE] > > **Degraded responses**: Optional relevance steps such as query expansion, intent modifiers, and personalization boosts fail open. If one of these steps is temporarily unavailable, Layers skips it and returns HTTP 200 with results instead of an error. Skipped steps do not appear in `_workflow`. If Layers is temporarily serving keyword-only results platform-wide, the response includes `_meta.search_lane` set to `"prefix_only"`. **totalResults** `number` The total number of results that passed relevance filtering for this request, across all pages. It does not depend on `pagination.limit`, `pagination.page`, or which `facets` you request. When variant breakouts are enabled, this reflects the count of tiles (both product and variant tiles) rather than just products. See [Why result totals can differ](#why-result-totals-can-differ). **page** `number` The current page number. **totalPages** `number` The total number of pages. Calculated based on tile count when variant breakouts are enabled. **attributionToken** `string` A unique request identifier (ULID) for this API call. Use this token to correlate search requests with analytics events via the [Beacon API](/tracking-api/send-events), and to match requests to entries in the [Search Inspector](/shopify-integration/storefront-pixel#search-inspector). **facetRanges** `object` If `includeFacetRanges` is `true` then an object with keys of the facet attribute code and value is an object with min/max. **facets** `object` If `retrieveFacetCount` is `true` then an object with keys and values of the specified attributes. When variant breakouts are enabled, facet counts reflect tile counts rather than product counts. Empty values and literal `"null"` strings are automatically excluded from facet results. **facetDisplay** `object` Returned when at least one requested facet has display data to hydrate. Keys are facet attribute codes; values map each facet value to a display object. Metaobject-reference facets require `enrichFacetMetaobjects: true` and map each handle to the metaobject's `display_name` and `fields`. Entries also carry a `swatch` object when the metaobject defines a color or image field. Handles with no matching cached metaobject are omitted here and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized field shape and the [Facets API response](/api-reference/facets#response) for the `swatch` shape. For `variants.pickup_locations`, each entry maps a Shopify location id to the location's `id`, `name`, `address`, `instructions`, `pickupTime`, and (when the filter is a `geoRadius`) `distance` and `distanceUnit`. Pickup entries are returned whenever pickup facets are requested, regardless of `enrichFacetMetaobjects`. See [Local pickup filtering](/engine/geospatial-filtering#local-pickup-filtering). **\_meta** `object` **Properties** **appliedSearchRules** `Array of strings` The IDs of [request transforms](/platform/request-transforms) whose targeting conditions matched this request. Returns an empty array when no request transforms matched. Use this to verify which request transforms are evaluating against a given search request. **appliedSearchRuleActions** `array of objects` One entry per action executed by a matched request transform, in execution order. Use `changed` to tell whether an action actually modified the request. A matched rule can appear in `appliedSearchRules` while all of its actions report `changed: false`. See [Debugging with `_meta`](/platform/request-transforms#debugging-with-_meta). **Properties** **ruleId** `string` The ID of the request transform that owns the action. **type** `string` The action type, for example `add_filter_group` or `override_sort_order`. **changed** `boolean` `true` when the action modified the request. `false` when the action was a no-op, for example a `replace_query` action on a request with no query or an `override_sort_order` action matching the already-active sort order. **error** `string` Only present when the action could not run. `"unsupported_action_type"` indicates a stored action type the engine cannot execute. The action is skipped and the rest of the request proceeds normally. **redirect** `object` Semantic redirect information. Only present when a semantic match is found for a text search that keeps regular redirect behavior. When a redirect is returned, the `results` array is empty. A supported collection destination can instead be served inline when **Inline Collection Redirects** is enabled; see `collection` below. **Properties** **url** `string` The redirect URL to navigate to. This URL is determined by semantic matching of the search query against configured redirect terms. **collection** `object` Collection browse metadata returned when **Inline Collection Redirects** is enabled and an eligible collection landing page is served inside the search response. Collection links with tags, filters, a chosen sort, or a pagination override keep regular redirect behavior; locale prefixes and tracking-only query parameters do not disqualify a link. The response keeps the original search query, normal facets, and pagination. `redirect` is not returned for this inline response. **Properties** **id** `string | number` The collection identifier. **handle** `string` The collection handle. **title** `string` The collection title. **sort\_order\_code** `string` The sort order that served the collection results. **variantBreakouts** `array of objects` Array of variant breakout configurations applied to search. Only present when one or more variant breakouts are active for search requests. Multiple breakouts with different option codes can work simultaneously. **Properties** **id** `string` The unique identifier of the variant breakout configuration. **name** `string` The display name of the variant breakout configuration (e.g., "Gemstone Breakout", "Color Breakout"). **optionCode** `string` The product option code that determines which variants are broken out (e.g., "Stone", "Color"). Each product is broken out by the first matching option code from the array. **mediaPreloads** `object` Echoes the image preload configuration used to build the `Link` response header for this request. Only present when image preloads are emitted. Use this to confirm which srcset breakpoints were applied, especially when overriding them via `responseOptions.mediaPreloads`. **Properties** **srcsetSizes** `int[]` The responsive image widths (in pixels) used in the `imagesrcset` of the `Link` header. Reflects the request override when provided, otherwise the store-level configuration or platform defaults. **discountEntitlements** `array of objects` Echoes the [discount entitlements](/shopify-integration/discount-entitlements) applied to this request. Only present when the request included `discountEntitlements` (either directly or via a matched [request transform](/platform/request-transforms)). Use this to render discount badges or labels on the storefront without re-deriving which entitlements matched. Each entry mirrors the entitlement shape sent in the request. **Properties** **entitled** `object` The entitlement criteria that qualified products for the discount. Contains any of `all`, `products`, `variants`, `collections`, or `conditions`. See the [entitlement criteria](/shopify-integration/discount-entitlements#entitlement-criteria) reference. **discount** `object` The discount Layers applied. **Properties** **type** `string` `"PERCENTAGE"` or `"FIXED_AMOUNT"`. **value** `number` The discount value. Percent off for `PERCENTAGE`, shop base-currency amount for `FIXED_AMOUNT`. An echoed entitlement doesn't guarantee a price reduction on every variant; see the shared `discountEntitlements` request parameter for market-currency limits. **search\_lane** `string` Only present when Layers is temporarily serving degraded results. The only value is `"prefix_only"`, meaning Layers matched results using keyword and prefix matching only, without semantic ranking, query expansion, or intent detection. The response stays well formed, so no client changes are required. Use this field to tell a keyword-only fallback response apart from a normal semantic one when reviewing analytics or debugging relevance. **\_workflow** `array of objects` An ordered trace of processing steps the engine performed to produce results for this request. Each entry represents a stage in the search pipeline, recorded in the order it was executed. Use this field to understand how Layers interpreted and transformed your query, which rules and boosts were applied, and why results appear in a particular order. This field is useful for debugging search behavior in development and is also surfaced in the [Search Inspector](/shopify-integration/storefront-pixel#search-inspector) panel. **Properties** **type** `string` The processing step type. Possible values: * `"query-replacement"` — The original query was replaced (e.g., by a spelling correction or request transform). The `payload` contains the corrected query string. * `"query-expansion"` — Additional related queries were generated to broaden the search. The `payload` is an array of expanded query strings. * `"query-interpretation"` — The engine analyzed the query to extract intent signals such as spelling corrections, detected language, and classification. The `payload` contains the interpretation details. * `"intent-modifiers"` — AI-powered intent modifiers adjusted the query based on detected shopping intent. The `payload` contains the modifier actions that were applied. * `"ranking-rules"` — One or more [ranking rules](/platform/ranking-relevancy) matched and influenced result ordering. The `payload` lists the applied rules. * `"semantic-redirect"` — A [semantic redirect](/platform/semantic-redirects) matched the query. The `payload` contains the redirect URL. * `"rule-applied"` — A merchandising rule was applied (browse requests). The `payload` contains the rule identifier. **payload** `string | array | object` The data associated with this processing step. The structure varies by `type`; see the `type` values listed for `_workflow`. ### Response headers Every API response includes the following headers for request tracing and performance optimization: | Header | Description | | - | - | | `x-request-id` | A unique identifier (ULID) for the request. This matches the `attributionToken` in the response body. Use it to correlate requests across your infrastructure or when contacting support. | | `x-layers-build` | The Layers build version that served the request. | | `X-Layers-Results-Cache` | Indicates whether the response was served from the results cache. Returns `HIT` when cached results were used, or `MISS` when results were computed fresh. Use this to monitor cache effectiveness and debug performance. | | `Link` | Contains `rel="preload"` directives for product images in the response (up to 6 items), enabling browsers and CDNs to begin fetching images before your application processes the JSON body. Each entry includes a responsive `imagesrcset` with multiple sizes. See [Early hints](/sdk/performance#early-hints-link-header-preloading) for configuration options. Only included when early hints are enabled for your store (enabled by default). | ### Variant breakouts When variant breakouts are configured, results may include both product tiles and variant tiles. Each result includes a `__typename` field to identify the tile type: **\_\_typename** `string` Identifies the type of tile in the results: * `"Product"` - A standard product tile * `"Variant"` - An individual variant tile from a product with a configured breakout option #### Variant tile fields Variant tiles include additional fields to identify the specific variant: **product\_id** `number` The parent product ID. Use this to link back to the full product or group variants from the same product. **variant\_id** `number` The specific variant ID. For variant tiles, this matches the `id` field. > [!NOTE] > > For variant tiles, the `id` field contains the variant ID (not the product ID). The `title` field is formatted as `"{product title} - {option value}"` by default (e.g., "Amethyst Ring - Rose Quartz"), but the format can be configured per breakout. If the breakout's **Include Option Value in Title** setting is disabled, the title is the original product title. See the [Variant Breakouts](/platform/variant-breakouts) documentation for more details. ```json Request theme={null} POST /storefront/v1/search/running%20shoes/execute { "pagination": { "page": 1, "limit": 20 }, "retrieveFacetCount": true, "facets": ["vendor", "product_type"], "context": { "geo": { "country": "US", "province": "California" }, "productsInCart": [ { "title": "Nike Air Force 1", "productId": "1234567890", "variantId": "9876543210" } ], "marketing": { "source": "google", "medium": "cpc", "campaign": "summer-sale" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123", "deviceId": "device-uuid" } } ``` ```json Response theme={null} { "results": [ { "id": 7003338965178, "title": "SUPREME SEALLINE SEE POUCH SMALL", "body_html": "The Supreme Sealline See Pouch Small is a versatile and waterproof storage solution that seamlessly marries utility and style. With its clear window for easy visibility and the iconic Supreme branding, it's a sought-after accessory for those who appreciate keeping their essentials dry while making a fashion statement, whether at the beach or in the city..", "vendor": "SUPREME", "product_type": "Accessories", "created_at": "2022-02-05T01:22:05.000000Z", "handle": "supreme-pouch-44370ss18a32-sm", "updated_at": "2023-10-25T20:47:04.000000Z", "published_at": "2022-02-05T01:22:05.000000Z", "tags": [ "consignment" ], "images": [ { "alt": "SUPREME POUCH", "src": "https://cdn.shopify.com/s/files/1/0588/3677/9194/products/ss18_supreme_tnf_pouch_blk_2-l_5fb1316e-22f7-4702-9953-57f3fbdda5be.jpg?v=1644047927", "width": 800, "height": 534, "variant_ids": [] } ], "metafields": { "product": { "alias": "SEALLINE SEE POUCH SMALL", "colorway": "BLACK", "styleCode": "SS18A30 BLACK", "yearOfRelease": 2018, "searchColor": [ "black" ] } }, "available": true, "price_range": { "from": 30, "to": 30 } } ], "totalResults": 1000, "page": 1, "totalPages": 20, "facets": { "vendor": { "ADIDAS": 30, "JORDAN": 336, "NEW BALANCE": 15, "NIKE": 384, "REEBOK": 4, "SUPREME": 624, "VANS": 32 } }, "attributionToken": "01JRVX7K2M8N9P4Q5R6S7T8U9V", "_meta": { "appliedSearchRules": [], "appliedSearchRuleActions": [] }, "_workflow": [ { "type": "query-expansion", "payload": ["running sneakers", "athletic shoes"] } ] } ``` # Content Search: Execute Search Source: https://docs.uselayers.com/api-reference/search-content POST /search/content/{searchQuery}/execute Content Search API endpoint to run semantic queries across blog articles, knowledge base pages, and other non-product content in your catalog. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Path parameters **searchQuery** `string` *required* The url-encoded search query. Layers normalizes the query before validating it, stripping invisible characters and converting Unicode punctuation to ASCII equivalents. After normalization, the query must be 2 to 255 characters. Queries outside this range return HTTP 422. ## Body **content\_type** `string` Filter results by content type. Supported values: `"article"` and `"page"`. When omitted, all content types are searched and results from both articles and pages are returned together. **pagination** `Pagination Object` **pagination** **page** `int` The current page of results to fetch. **limit** `int` The max results to fetch per page. **tuning** `object` Override default ranking weights for content search. **Properties** **textualWeight** `number` Weight for textual (semantic text) similarity in ranking, between `0` and `1`. Required when `visualWeight` is provided. **visualWeight** `number` Weight for visual (image) similarity in ranking, between `0` and `1`. Required when `textualWeight` is provided. **topK** `integer` Number of candidate results to retrieve before re-ranking, between `1` and `100`. **rankingWeightOverrides** `object` Override the default ranking model weights for this request. Each key is a signal group name and the value is a weight between `0` and `1`. Content search supports the following groups: * `semantic` — controls how much text and image similarity contribute to the score. * `freshness` — controls how much publication recency contributes to the score. When provided, the weights are normalized so they sum to 1. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. ## Response **results** `array` Array of content items matching the search query. Results can include both articles and pages when no `content_type` filter is applied. Each item includes: **Content item properties** **\_\_typename** `string` The content type identifier. Returns `"Article"` for blog articles or `"Page"` for Shopify pages. **content\_type** `string` The content type: `"article"` or `"page"`. **content\_id** `number` The unique identifier for the content item. **title** `string` The content title. **handle** `string` The URL handle for the content item. **summary\_text** `string` The content summary with HTML tags stripped (except images). **author** `string` The author name. For pages, this may be `null`. **tags** `array` Array of tags associated with the content item. For pages, this is an empty array. **image** `object` The featured image. **Properties** **url** `string` The image URL. **width** `number` The image width in pixels. **height** `number` The image height in pixels. **altText** `string` The image alt text. **published\_at** `string` ISO 8601 timestamp of when the content was published. **blog\_title** `string` The title of the blog the article belongs to. For pages, or for articles that haven't synced blog data yet, this is `null`. **url** `string` The root-relative storefront URL for the content item. Articles return `/blogs/{blog_handle}/{handle}` and pages return `/pages/{handle}`. For articles that haven't synced blog data yet, this is `null`. **query** `string` The search query that was executed. **contentType** `string` The content type filter applied, if any. **totalResults** `number` The total number of results matching the search query. **page** `number` The current page number. **totalPages** `number` The total number of pages. **resultsPerPage** `number` The number of results per page. ### 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. | ## Supported content types Content search indexes two types of Shopify content: | Content type | `__typename` | Description | | - | - | - | | **Articles** | `"Article"` | Blog posts from your Shopify blog. Includes author, tags, and blog association. | | **Pages** | `"Page"` | Shopify pages (e.g., About Us, FAQ, Size Guide). Includes featured images when available. | When you omit the `content_type` parameter, results from both articles and pages are returned together, ranked by a unified scoring model. Use the `__typename` field to distinguish between content types when rendering results. ## Search behavior Content search uses a configurable ranking model to score and rank results. The default model combines three signal groups: | Signal group | Default weight | What it measures | | - | - | - | | **Semantic (text)** | 50% | How closely the content text matches the meaning of the query | | **Semantic (image)** | 20% | How closely the content's images match the query | | **Freshness** | 30% | How recently the content was published (newer items score higher) | Scores from each signal group are normalized using min-max scaling across the result set, then combined into a single ranking score using a weighted linear combination. You can override these weights per-request using the `tuning.rankingWeightOverrides` parameter. For product search testing, use [Test text search](/help/evaluate/test-text-search) in Lab. ### Image indexing for articles Layers indexes up to 10 images per article for the image similarity signal. The featured image is always indexed first, followed by images from the article body in the order they appear. Images beyond the first 10 do not contribute to image similarity scores. Text and image indexing are independent. When an article is created or updated, its text becomes searchable immediately, and image similarity may follow shortly after. Text results are never delayed by image processing. ## Error handling When search processing fails (e.g., due to rate limits or service issues), the API returns an empty result set with `totalResults: 0` rather than throwing an error, so your content search UI can render an empty state instead of failing. ```json Response theme={null} { "query": "sustainable fashion tips", "contentType": null, "resultsPerPage": 20, "totalResults": 14, "page": 1, "totalPages": 1, "results": [ { "__typename": "Article", "content_type": "article", "content_id": 12345678901, "title": "10 Ways to Build a Sustainable Wardrobe", "handle": "sustainable-wardrobe-tips", "summary_text": "Discover practical tips for creating an eco-friendly wardrobe that's both stylish and sustainable.", "author": "Emma Green", "tags": ["sustainability", "fashion", "eco-friendly"], "image": { "url": "https://cdn.shopify.com/s/files/1/0588/3677/9194/articles/sustainable-fashion.jpg", "width": 1200, "height": 630, "altText": "Sustainable Fashion Guide" }, "published_at": "2024-06-01T12:00:00Z", "blog_title": "The Journal", "url": "/blogs/journal/sustainable-wardrobe-tips" }, { "__typename": "Page", "content_type": "page", "content_id": 98765432101, "title": "Our Sustainability Commitment", "handle": "sustainability", "summary_text": "Learn about our commitment to ethical sourcing and sustainable materials across all product lines.", "author": null, "tags": [], "image": { "url": "https://cdn.shopify.com/s/files/1/0588/3677/9194/files/sustainability-hero.jpg", "width": 1600, "height": 900, "altText": "Sustainability page hero" }, "published_at": "2024-03-15T10:00:00Z", "blog_title": null, "url": "/pages/sustainability" } ] } ``` ## Usage example ```bash cURL (all content types) theme={null} curl -X POST "https://app.uselayers.com/api/storefront/v1/search/content/sustainable%20fashion/execute" \ -H "X-Storefront-Access-Token: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "pagination": { "page": 1, "limit": 20 }, "context": { "geo": { "country": "US" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123", "deviceId": "device-uuid" } }' ``` ```bash cURL (pages only) theme={null} curl -X POST "https://app.uselayers.com/api/storefront/v1/search/content/return%20policy/execute" \ -H "X-Storefront-Access-Token: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "content_type": "page", "pagination": { "page": 1, "limit": 20 } }' ``` > [!NOTE] > > **Content sync**: Articles and pages are automatically synced from Shopify via webhooks and bulk operations. Only published content without the `seo.hidden` metafield is included in search results. Setting `seo.hidden` also removes the item from Shopify's own search and `sitemap.xml`. To exclude articles or pages from Layers search only, use a [hidden content rule](/platform/hidden-products) with a metafield condition instead. # Text Search: Submit Feedback Source: https://docs.uselayers.com/api-reference/search-feedback POST /search/feedback Search Feedback API endpoint to submit qualitative shopper feedback (thumbs up/down, free-form text, and per-product ratings) for a specific search. This endpoint allows you to capture user feedback on search results, including overall ratings, text feedback, and product-specific feedback. When feedback is submitted, the endpoint retrieves the cached search data (if still available) and stores the original search query, expanded queries, and intent modifier actions alongside the feedback for analysis. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. Same requirements as the Search API. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Body **search\_id** `string` *required* ULID identifier of the search to provide feedback on. This should be the `search_id` returned from the [Prepare Search](/api-reference/search-prepare) endpoint. **rating** `string` Overall rating for the search results. Must be one of: * `"positive"` - Thumbs up, results were helpful * `"negative"` - Thumbs down, results were not helpful **text\_feedback** `string` Free-form text feedback from the shopper. Maximum 2000 characters. **product\_feedback** `array` Array of product-specific feedback objects. Each object contains: **Properties** **product\_id** `integer` *required* The product ID to provide feedback on. **rating** `string` Rating for this specific product. Must be `"positive"` or `"negative"`. **feedback** `string` Optional text feedback for this product. Maximum 500 characters. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). ## Validation rules * `search_id` is required and must be a valid ULID * `rating` must be either `"positive"` or `"negative"` if provided * `text_feedback` has a maximum length of 2000 characters * `product_feedback` is an array where each item must include: * `product_id` (required when `product_feedback` is provided) * `rating` must be `"positive"` or `"negative"` if provided * `feedback` has a maximum length of 500 characters * At least one of `rating`, `text_feedback`, or `product_feedback` should be provided, though all fields are technically optional ## Behavior * Returns HTTP 201 (Created) when feedback is successfully recorded * Attempts to retrieve cached search data using the provided `search_id` * If cached data is available (within 15 minutes of the original search), captures: * Original search query * Expanded queries used for search * Intent modifier actions applied * If cached data is not available (expired or invalid `search_id`), feedback is still recorded but without the search context * Stores identity information (`sessionId` and `customerId`) if provided ## Response ### 201 Created **id** `string` ULID identifier for the created feedback record. **search\_id** `string` The search ID that was provided in the request. **recorded** `boolean` Always `true` when feedback is successfully recorded. ```json Response theme={null} { "id": "01HZY7K2M8N9P4Q5R6S7T8U9V0", "search_id": "01HZY7J9ZV6K2T3M6P4FJ3F2QG", "recorded": true } ``` ### Error conditions * 401 Unauthorized: Missing or invalid `X-Storefront-Access-Token` * 402 Payment Required: The store is suspended. Every storefront API request returns this status until the suspension is lifted * 422 Unprocessable Entity: Invalid body or validation errors ## Example usage ### Basic rating feedback ```typescript theme={null} const response = await fetch('https://app.uselayers.com/api/storefront/v1/search/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': 'your-token-here' }, body: JSON.stringify({ search_id: '01HZY7J9ZV6K2T3M6P4FJ3F2QG', rating: 'positive' }) }); const data = await response.json(); console.log(data); // { id: "01HZY7K2M8N9P4Q5R6S7T8U9V0", search_id: "01HZY7J9ZV6K2T3M6P4FJ3F2QG", recorded: true } ``` ### Feedback with text and identity ```typescript theme={null} const response = await fetch('https://app.uselayers.com/api/storefront/v1/search/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': 'your-token-here' }, body: JSON.stringify({ search_id: '01HZY7J9ZV6K2T3M6P4FJ3F2QG', rating: 'negative', text_feedback: 'The results were not relevant to my search.', identity: { sessionId: 'session-123', customerId: 'customer-456' } }) }); const data = await response.json(); ``` ### Product-specific feedback ```typescript theme={null} const response = await fetch('https://app.uselayers.com/api/storefront/v1/search/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': 'your-token-here' }, body: JSON.stringify({ search_id: '01HZY7J9ZV6K2T3M6P4FJ3F2QG', product_feedback: [ { product_id: 123, rating: 'positive' }, { product_id: 456, rating: 'negative', feedback: 'Not what I was looking for' } ] }) }); const data = await response.json(); ``` ## Next steps * Use this endpoint in conjunction with the [Prepare Search](/api-reference/search-prepare) and [Search](/api-reference/search) endpoints to create a complete search experience with feedback collection * Analyze collected feedback to improve search relevance and user experience # Image Search: Execute Search Source: https://docs.uselayers.com/api-reference/search-image POST /search/image Image Search API endpoint to run visual searches across your product catalog using uploaded image IDs or base64-encoded image payloads. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Body **image\_data** `string` *required* Base64 Encoded PNG or JPEG Image Data. Required if `image_id` is not provided. **image\_id** `string` *required* UUID identifier returned from the [Image Upload API](/api-reference/upload-image). Required if `image_data` is not provided. Use `image_id` for better performance and support for larger images. **attributes** `string[]` Product attributes to include in the response. By default, all attributes are included. 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`, `first_or_matched_variant`, and `variants`. See the [Product Schema](/developers/product-schema/api-attributes) for detailed descriptions, including [nested field selection](/developers/product-schema/api-attributes#selecting-nested-fields) for slicing arrays and filtering collections (for example, `images[:2].src`, `variants[sku=ABC].price`, `metafields[namespace=custom]`). **filter\_group** `object` Storefront endpoints accept nested `AND`/`OR` filter groups up to two levels deep. Each nested group must contain at least one expression; empty nested groups are rejected. Metafield filter properties may include hyphens in their namespace or key, for example `metafields.my-app.fit-type`. Refer to the dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions. **pagination** `Pagination Object` **pagination** **page** `int` The current page of results to fetch. **limit** `int` The max results to fetch per page. **facets** `string[]` 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.*"] ``` **retrieveFacetCount** `boolean` If the count of each facet value should be calculated. **includeFacetRanges** `boolean` If you want a min/max range for numeric facets such as price. **enrichFacetMetaobjects** `boolean` When `true`, any facet backed by a `metaobject_reference` or `list.metaobject_reference` metafield is returned with a companion `facetDisplay` object. Each entry maps a facet value (the metaobject handle) to the referenced metaobject's `display_name` and `fields`. When the metaobject defines a color or image field, the entry also carries a resolved `swatch` object. Use this when your storefront filter UI needs human-readable labels or nested field data (for example, a color name or swatch hex) instead of the raw handle. When `false` or omitted, only the handles are returned in `facets`. Values are looked up from the local metaobject cache. Handles with no matching cached metaobject are omitted from `facetDisplay` and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized shape of each entry. **sort\_order\_code** `string` Code of the sort order to apply. Use `"relevance"` for the default relevance-based ranking, or any custom sort order code configured in your store. Retrieve available sort order codes from the [Sort Orders API](/api-reference/sort-orders). **defaultSelectedOptions** `array` Specify which product variants should be selected by default in the `first_or_matched_variant` field. **Properties** **optionCode** `string` *required* The product option code to match (e.g., `"birthstone"`, `"color"`). Option codes are automatically normalized (e.g., `"Birth Stone"` becomes `"birth_stone"`). **value** `string` *required* The option value to match (e.g., `"February"`, `"Blue"`). **Behavior:** * Uses **OR logic** - selects the first variant matching ANY of the specified option values * Falls back to the first variant by position if no match is found * **Automatically skipped** when any option or variant filters are applied (filters take precedence) * Only affects the `first_or_matched_variant` field in the response **discountEntitlements** `array` Apply discounts to products, variants, or collections. When provided, price-based sorting and filtering will use discounted prices. See the [Discount Entitlements](/shopify-integration/discount-entitlements) guide for detailed usage. Fixed amounts use your shop's base currency. Layers skips them on market pricing rows in a different native currency, without converting the discount. Percentage discounts still apply to those localized prices. A variant that falls back to its base price can still receive a fixed-amount discount. **Discount Entitlement Object** **entitled** `object` *required* Defines which products qualify for the discount. **entitled** **all** `boolean` When `true`, applies discount to all products. When `false`, uses products, variants, or collections arrays. **products** `string[]` Array of product IDs or handles that qualify for the discount. Maximum 250 entries. **variants** `string[] | number[]` Array of variant IDs that qualify for the discount. Maximum 250 entries. **collections** `string[]` Array of collection handles that qualify for the discount. Maximum 250 entries. **conditions** `object` Optional filter group that qualifies products for the discount based on their attributes (for example, `tags` or `vendor`). Uses the same shape as the top-level `filter_group` parameter. Matches are additive with `products`, `variants`, and `collections` on the same entitlement. **discount** `object` *required* Defines the discount to apply. **discount** **type** `string` *required* The discount type: `PERCENTAGE` or `FIXED_AMOUNT`. **value** `number` *required* The discount value. For `PERCENTAGE`, this must be a number between 0 and 100 (e.g., 10 for 10% off). For `FIXED_AMOUNT`, this is the amount in your shop's base currency, not the shopper's market currency. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. **responseOptions** `object` Per-request overrides for response behavior. Currently controls image preload hints emitted in the `Link` response header. You can disable preloads or narrow the srcset to the breakpoints your storefront uses. You cannot enable preloads when the store has them disabled. **Properties** **mediaPreloads** `object` Controls the `Link: rel=\"preload\"` directives generated for product images in this response. See [Early hints](/sdk/performance#early-hints-link-header-preloading) for background. **Properties** **enabled** `boolean` (default: true) Set to `false` to skip the `Link` header for this request. Useful for server-rendered pages that do not benefit from preload hints, or when you want to reduce response header size. Cannot enable preloads if they are disabled at the store level. **srcsetSizes** `int[]` Custom responsive image widths (in pixels) to emit in `imagesrcset`. Each value must be an integer between `1` and `10000`. Overrides the store-level srcset configuration for this request only. When omitted, the store configuration or platform defaults are used. **sizes** `string` Media query string emitted as the `imagesizes` attribute in the preload `Link` header (for example `(max-width: 600px) 100vw, 50vw`). Tells the browser which srcset width to pick per viewport. Overrides the store-level sizes value for this request only. When omitted or empty, the store configuration is used. Each comma-separated entry may carry a media condition, including the last entry. See the [accepted format](/sdk/performance#customization) for details. The API rejects invalid values with a validation error. **Example:** ```json theme={null} { "responseOptions": { "mediaPreloads": { "enabled": true, "srcsetSizes": [320, 640, 960], "sizes": "(max-width: 600px) 100vw, 50vw" } } } ``` ## Response **results** `Array of Objects` **Properties** **id** `number` The unique identifier of the product. **title** `string` The title of the product. **body\_html** `string` The HTML content describing the product. **vendor** `string` The vendor of the product. **product\_type** `string` The type of the product. **created\_at** `number` The timestamp when the product was created. **handle** `string` The handle of the product. **updated\_at** `number` The timestamp when the product was updated. **published\_at** `number` The timestamp when the product was published. **tags** `Array of strings` The tags associated with the product. **combined\_listing\_parent\_product\_id** `number` The parent product id if a child in a Combined Listing. **combined\_listing\_role** `string` The role of the product if part of a Combined Listing. **images** `Array of Objects` The images of the product. **Properties** **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **variant\_ids** `Array` The variant IDs associated with the image. **metafields** `Object` The metafields of the product. **calculated** `Object` The computed attributes of the product. Only includes attributes with non-null, non-empty values. Attributes that evaluate to null or an empty string are omitted. **category** `Object` The Shopify Product Taxonomy Category of the product. **Properties** **name** `string` The name of the category leaf. **full\_name** `string` The full name of the category. **id** `string` The ID of the category. **is\_leaf** `boolean` Is the category a leaf category. **is\_root** `boolean` Is the category a root category. **first\_or\_matched\_variant** `Object` The first available variant (depending on OOS settings) or the variant matched with a filter or search query. **Properties** **id** `number` The ID of the variant. **title** `string` The title of the variant. **available** `boolean` The availability of the variant. **sku** `number` The sku of the variant. **price** `string` The price of the variant. **compare\_at\_price** `string` The compare at price of the variant. **metafields** `Object` The metafields of the variant. **selected\_options** `Array of Objects` The selected options of the variant. **Properties** **name** `string` The name of the option. **value** `string` The value of the option. **option\_value** `object` The linked metafield of the option. **position** `number` The position of the variant in the product's variant list. **inventory\_quantity** `number` Total inventory quantity across the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope), which is all locations by default. Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_policy** `string` Inventory policy for the variant: `DENY` (stop selling when out of stock) or `CONTINUE` (allow overselling). Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_levels** `object` Object mapping location IDs to available inventory quantities (e.g., `{"1001": 5, "1002": 10}`). Returns empty object `{}` when no inventory data exists. Only included when the store has the **Expose Variant Inventory** setting enabled. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **available** `boolean` The availability of the product. **price\_range** `Object` The price range of the product. **Properties** **from** `number` The starting price of the product. **to** `number` The ending price of the product. **totalResults** `number` The total number of results. **page** `number` The current page number. **totalPages** `number` The total number of pages. **facetRanges** `object` If `includeFacetRanges` is `true` then an object with keys of the facet attribute code and value is an object with min/max. **facets** `object` If `retrieveFacetCount` is `true` then an object with keys and values of the specified attributes. Empty values and literal `"null"` strings are automatically excluded from facet results. **facetDisplay** `object` Only returned when `enrichFacetMetaobjects` is `true` and at least one requested facet is backed by a `metaobject_reference` or `list.metaobject_reference` metafield. Keys are facet attribute codes and values map each facet value (the referenced metaobject's handle) to the metaobject's `display_name` and `fields`. Handles with no matching cached metaobject are omitted here and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized field shape. **attributionToken** `string` A unique request identifier (ULID) for this API call. Use this token to correlate requests with analytics events via the [Beacon API](/tracking-api/send-events). **\_meta** `object` Metadata about the search request. **Properties** **mediaPreloads** `object` Echoes the image preload configuration used to build the `Link` response header for this request. Only present when image preloads are emitted. See [Early hints](/sdk/performance#early-hints-link-header-preloading). **Properties** **srcsetSizes** `int[]` The responsive image widths (in pixels) used in the `imagesrcset` of the `Link` header. Reflects the request override when provided, otherwise the store-level configuration or platform defaults. **search\_lane** `string` Only present when Layers is temporarily serving keyword-only results platform-wide. The only value is `"prefix_only"`. Image search depends entirely on semantic matching, so in this mode the endpoint returns a well-formed empty response (`results: []`, `totalResults: 0`) instead of an error. Check this field to show a fallback experience rather than treating the empty result as "no matches." **\_workflow** `array of objects` An ordered trace of processing steps the engine performed. See the [Text Search](/api-reference/search) documentation for the full list of possible step types. ### Response headers | Header | Description | | - | - | | `x-request-id` | A unique identifier (ULID) for the request. This matches the `attributionToken` in the response body. | | `x-layers-build` | The Layers build version that served the request. | | `X-Layers-Results-Cache` | Indicates whether the response was served from the results cache. Returns `HIT` or `MISS`. | | `Link` | Contains `rel="preload"` directives for product images (up to 6 items). See [Early hints](/sdk/performance#early-hints-link-header-preloading) for details. Only included when early hints are enabled (enabled by default). | ## Error responses ### 422 Unprocessable Entity A 422 error is returned when the `image_id` refers to an image that failed to process. This can occur when: * The uploaded image is corrupted or invalid * The image format is unsupported * The image file cannot be read or decoded **Error response structure:** ```json theme={null} { "error": "Image processing failed", "message": "Image is corrupted or invalid" } ``` The `message` field provides specific details about why the image processing failed. ## Usage examples ### Using image ID (recommended) First, upload an image to get an `image_id`: ```bash theme={null} curl -X POST "https://app.uselayers.com/api/storefront/v1/images/upload" \ -H "X-Storefront-Access-Token: YOUR_TOKEN" \ -F "image=@/path/to/your/image.jpg" ``` Then use the returned `image_id` for searching: ```json theme={null} { "image_id": "550e8400-e29b-41d4-a716-446655440000", "pagination": { "page": 1, "limit": 20 }, "context": { "geo": { "country": "US" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123", "deviceId": "device-uuid" } } ``` ### Using base64 image data (legacy) ```json theme={null} { "image_data": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...", "pagination": { "page": 1, "limit": 20 }, "context": { "shoppingChannel": "web" } } ``` ```json Response theme={null} { "results": [ { "id": 7003338965178, "title": "SUPREME SEALLINE SEE POUCH SMALL", "body_html": "The Supreme Sealline See Pouch Small is a versatile and waterproof storage solution that seamlessly marries utility and style. With its clear window for easy visibility and the iconic Supreme branding, it's a sought-after accessory for those who appreciate keeping their essentials dry while making a fashion statement, whether at the beach or in the city..", "vendor": "SUPREME", "product_type": "Accessories", "created_at": "2022-02-05T01:22:05.000000Z", "handle": "supreme-pouch-44370ss18a32-sm", "updated_at": "2023-10-25T20:47:04.000000Z", "published_at": "2022-02-05T01:22:05.000000Z", "tags": [ "consignment", ], "images": [ { "alt": "SUPREME POUCH", "src": "https://cdn.shopify.com/s/files/1/0588/3677/9194/products/ss18_supreme_tnf_pouch_blk_2-l_5fb1316e-22f7-4702-9953-57f3fbdda5be.jpg?v=1644047927", "width": 800, "height": 534, "variant_ids": [] } ], "metafields": { "product": { "alias": "SEALLINE SEE POUCH SMALL", "colorway": "BLACK", "styleCode": "SS18A30 BLACK", "yearOfRelease": 2018, "searchColor": [ "black" ] } }, "available": true, "price_range": { "from": 30, "to": 30 } } ], "totalResults": 1000, "page": 1, "totalPages": 20, "facets": { "vendor": { "ADIDAS": 30, "JORDAN": 336, "NEW BALANCE": 15, "NIKE": 384, "REEBOK": 4, "SUPREME": 624, "VANS": 32 } }, "attributionToken": "2y10smI2dB7XZXXFJsLUELltgueq8NRdcRD3U8djkLqxQmaVMvg1lSCf2" } ``` # Text Search: Prepare Search Source: https://docs.uselayers.com/api-reference/search-prepare POST /search/{searchQuery}/prepare 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 you can use with the Search API to execute the search. * Use with: [Search API](/api-reference/search) via the `search_id` body parameter ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. Same requirements as the Search API. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Path parameters **searchQuery** `string` *required* The url-encoded search query to prepare. Layers normalizes the query before validating it, stripping invisible characters and converting Unicode punctuation to ASCII equivalents. After normalization, the query must be 2 to 255 characters. Queries outside this range return HTTP 422. ## Body **attributes** `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 [Product Schema](/developers/product-schema/api-attributes) for detailed descriptions. **filter\_group** `object` Storefront endpoints accept nested `AND`/`OR` filter groups up to two levels deep. Each nested group must contain at least one expression; empty nested groups are rejected. Metafield filter properties may include hyphens in their namespace or key, for example `metafields.my-app.fit-type`. Refer to the dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions. **pagination** `Pagination Object` **pagination** **page** `int` The current page of results to fetch. **limit** `int` The max results to fetch per page. **facets** `string[]` 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.*"] ``` **retrieveFacetCount** `boolean` If the count of each facet value should be calculated. **includeFacetRanges** `boolean` If you want a min/max range for numeric facets such as price. **enrichFacetMetaobjects** `boolean` When `true`, any facet backed by a `metaobject_reference` or `list.metaobject_reference` metafield is returned with a companion `facetDisplay` object. Each entry maps a facet value (the metaobject handle) to the referenced metaobject's `display_name` and `fields`. When the metaobject defines a color or image field, the entry also carries a resolved `swatch` object. Use this when your storefront filter UI needs human-readable labels or nested field data (for example, a color name or swatch hex) instead of the raw handle. When `false` or omitted, only the handles are returned in `facets`. Values are looked up from the local metaobject cache. Handles with no matching cached metaobject are omitted from `facetDisplay` and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized shape of each entry. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. ## 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 * If Layers is temporarily serving keyword-only results platform-wide, prepare still returns 202 with a usable `search_id` but skips semantic preparation. The execute call then returns keyword-only results with `_meta.search_lane` set to `"prefix_only"`. No client changes are required. ## Response ### 202 Accepted **search\_id** `string` ULID identifier for the prepared search. Valid for 15 minutes. ```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" } ``` ### 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` * 402 Payment Required: The store is suspended. Every storefront API request returns this status until the suspension is lifted * 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. # Search API: Similar Products Source: https://docs.uselayers.com/api-reference/similar-products POST /search/product/{searchProductId} Similar Products API endpoint that returns visually and semantically related items to a given product from your catalog for recommendation carousels. ## How results are served Similar products results are precomputed and cached for fast response times. Layers runs the full ranking pipeline, combining visual and semantic similarity with behavioral signals, and stores the top results for each product. When you call this endpoint, results are served from the precomputed cache. If no precomputed data exists for a product (for example, a newly added product), Layers falls back to computing similarity in real time. Precomputed results are refreshed daily and incrementally when a product's content changes. An hourly coverage check also finds products that are missing precomputed results, such as products added through a bulk catalog import, and queues them for computation. Coverage gaps close without waiting for the daily refresh. All request parameters (filters, facets, pagination, and sort orders) work the same regardless of whether results are served from cache or computed in real time. When you pass `variant_id` in the request body, results are always computed in real time from that variant. Shoppers viewing different variants of the same product see different recommendations. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: application/json) **Accept** `string` *required* (default: application/json) ## Path parameters **searchProductId** `integer` *required* The ID of the product for which you want to find similar products. ## Body **variant\_id** `integer` When provided, the endpoint seeds similarity from that variant rather than the product as a whole. Results then reflect the variant's visual and semantic attributes, such as a specific color or material. Pass the variant currently selected on the product detail page. The value is only used when the variant belongs to the anchor product in the path. If it doesn't match, the value is silently ignored and results fall back to product-level similarity. If the variant isn't indexed yet, results also degrade to product-level similarity. When `variant_id` is set, results are computed in real time rather than served from the precomputed cache. Different variants of the same product return different results and are cached under separate keys. **attributes** `string[]` Product attributes to include in the response. By default, all attributes are included. 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`, `first_or_matched_variant`, and `variants`. See the [Product Schema](/developers/product-schema/api-attributes) for detailed descriptions, including [nested field selection](/developers/product-schema/api-attributes#selecting-nested-fields) for slicing arrays and filtering collections (for example, `images[:2].src`, `variants[sku=ABC].price`, `metafields[namespace=custom]`). **filter\_group** `object` Storefront endpoints accept nested `AND`/`OR` filter groups up to two levels deep. Each nested group must contain at least one expression; empty nested groups are rejected. Metafield filter properties may include hyphens in their namespace or key, for example `metafields.my-app.fit-type`. Refer to the dedicated [Filter Expressions](/engine/filtering) guide to learn more about filter expressions. **pagination** `Pagination Object` **pagination** **page** `int` The current page of results to fetch. **limit** `int` The max results to fetch per page. **facets** `string[]` 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.*"] ``` **retrieveFacetCount** `boolean` If the count of each facet value should be calculated. **includeFacetRanges** `boolean` If you want a min/max range for numeric facets such as price. **enrichFacetMetaobjects** `boolean` When `true`, any facet backed by a `metaobject_reference` or `list.metaobject_reference` metafield is returned with a companion `facetDisplay` object. Each entry maps a facet value (the metaobject handle) to the referenced metaobject's `display_name` and `fields`. When the metaobject defines a color or image field, the entry also carries a resolved `swatch` object. Use this when your storefront filter UI needs human-readable labels or nested field data (for example, a color name or swatch hex) instead of the raw handle. When `false` or omitted, only the handles are returned in `facets`. Values are looked up from the local metaobject cache. Handles with no matching cached metaobject are omitted from `facetDisplay` and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized shape of each entry. **sort\_order\_code** `string` Code of the sort order to apply. Use `"relevance"` for the default relevance-based ranking, or any custom sort order code configured in your store. Retrieve available sort order codes from the [Sort Orders API](/api-reference/sort-orders). **defaultSelectedOptions** `array` Specify which product variants should be selected by default in the `first_or_matched_variant` field. **Properties** **optionCode** `string` *required* The product option code to match (e.g., `"birthstone"`, `"color"`). Option codes are automatically normalized (e.g., `"Birth Stone"` becomes `"birth_stone"`). **value** `string` *required* The option value to match (e.g., `"February"`, `"Blue"`). **Behavior:** * Uses **OR logic** - selects the first variant matching ANY of the specified option values * Falls back to the first variant by position if no match is found * **Automatically skipped** when any option or variant filters are applied (filters take precedence) * Only affects the `first_or_matched_variant` field in the response **discountEntitlements** `array` Apply discounts to products, variants, or collections. When provided, price-based sorting and filtering will use discounted prices. See the [Discount Entitlements](/shopify-integration/discount-entitlements) guide for detailed usage. Fixed amounts use your shop's base currency. Layers skips them on market pricing rows in a different native currency, without converting the discount. Percentage discounts still apply to those localized prices. A variant that falls back to its base price can still receive a fixed-amount discount. **Discount Entitlement Object** **entitled** `object` *required* Defines which products qualify for the discount. **entitled** **all** `boolean` When `true`, applies discount to all products. When `false`, uses products, variants, or collections arrays. **products** `string[]` Array of product IDs or handles that qualify for the discount. Maximum 250 entries. **variants** `string[] | number[]` Array of variant IDs that qualify for the discount. Maximum 250 entries. **collections** `string[]` Array of collection handles that qualify for the discount. Maximum 250 entries. **conditions** `object` Optional filter group that qualifies products for the discount based on their attributes (for example, `tags` or `vendor`). Uses the same shape as the top-level `filter_group` parameter. Matches are additive with `products`, `variants`, and `collections` on the same entitlement. **discount** `object` *required* Defines the discount to apply. **discount** **type** `string` *required* The discount type: `PERCENTAGE` or `FIXED_AMOUNT`. **value** `number` *required* The discount value. For `PERCENTAGE`, this must be a number between 0 and 100 (e.g., 10 for 10% off). For `FIXED_AMOUNT`, this is the amount in your shop's base currency, not the shopper's market currency. **identity** `object` User identity information for tracking and personalization. Automatically managed by the Storefront Pixel; required for headless integrations. **Properties** **deviceId** `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. **sessionId** `string` Temporary session identifier. Layers-generated sessions expire after 30 minutes without activity. The Storefront Pixel refreshes the rolling window at page load and on every route change, including pages without tracked events. When a legacy Shopify or fallback cookie is available, Layers prefers it and does not control its lifetime. Without consent, the pixel uses a sessionStorage or in-memory fallback and does not write an analytics cookie. **customerId** `string` Shopify customer ID for authenticated users. Only present when the customer is signed in to their account. **companyLocationId** `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. When you pass `companyLocationId`, you must also pass the buyer's `customerId`. Layers verifies with Shopify that the customer belongs to the company that owns the location before resolving the catalog; unauthorized or unauthenticated requests return a `403`. See [B2B catalogs](/shopify-integration/b2b-catalogs). **context** `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. **Properties** **geo** `object` Geographic location information for regional personalization and merchandising. Layers determines it from the IP address for client-side requests. For server-side API calls (headless integrations), provide `geo` explicitly. **Properties** **country** `string` Country code or name (e.g., "US", "Canada"). **province** `string` State or province name (e.g., "California", "Ontario"). **city** `string` City name (e.g., "Los Angeles", "Toronto"). **productsInCart** `array` Products currently in the customer's cart. Used to surface complementary products and influence relevance scoring. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **quantity** `integer` Number of units of this line in the cart. Layers rounds fractional values down to a whole number. Missing values, non-numeric values, and values below `1` count as `1`. Layers uses it to calculate the cart subtotal for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks). **freeShippingThreshold** `number` The cart subtotal at which the shopper qualifies for free shipping, in the request currency's major units (e.g. `75.00` for \$75), not cents. Layers ignores values that aren't a number greater than `0`. Required for [Free Shipping Picks](/platform/blocks/strategies#free-shipping-picks) blocks. > [!WARNING] > > Shopify's `/cart.js` and Liquid money values such as `cart.total_price` and `item.price` are in cents. Divide them by 100 before sending `productsInCart[].price` or `freeShippingThreshold`. **productsViewed** `array` Products the shopper has viewed during the current session. Layers uses these as short-lived personalization signals, with recent views weighted more heavily. Only the 20 most recent views are used. The Storefront Pixel populates this automatically; send it manually only for headless integrations. See [Recently viewed products](/engine/contextual-information/data-structure#recently-viewed-products). **Array Item Properties** **id** `string` Product identifier. Accepts a numeric ID or a Shopify GID. Also accepted as `productId`. **at** `integer` Timestamp of the view in Unix milliseconds. Views without `at` still count but skip recency weighting. **title** `string` Product title. **type** `string` Product type or category. **variantId** `string` Variant identifier, if the shopper viewed a specific variant. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **productsPurchased** `array` Products the customer has previously purchased. Informs recommendations and prevents over-promotion of owned items. **Array Item Properties** **title** `string` Product title. Each entry needs at least a `productId`, `variantId`, or non-empty `title`. Layers drops entries with none of these. **price** `number` Unit price in the request currency's major units (e.g. `29.00` for \$29), not cents, at time of purchase. Accepts a JSON number or a numeric string such as `"29.00"`. **type** `string` Product type or category. **productId** `string` Product identifier. Accepts a numeric ID (e.g., `"8234567890123"`) or a Shopify GID (e.g., `"gid://shopify/Product/8234567890123"`). **variantId** `string` Product variant identifier. **options** `object` Product variant options (e.g., `{"Size": "11", "Color": "Red"}`). **priorSearches** `array` Recent search queries and their outcomes. Helps understand customer intent and refine relevance models. **Array Item Properties** **searchQuery** `string` *required* The search query text. **hadClick** `boolean` (default: false) Whether the customer clicked on any results from this search. **hasResults** `boolean` (default: false) Whether the search returned any results. **fromPage** `string` The page the search was started from (e.g., the referring page URL or page type). Layers accepts this field but doesn't currently use it for ranking or rules. **marketing** `object` UTM parameters and marketing campaign information for attribution tracking. **Properties** **source** `string` Marketing source (e.g., "google", "facebook"). **medium** `string` Marketing medium (e.g., "cpc", "email", "social"). **campaign** `string` Campaign name. **term** `string` Search term or keyword. **content** `string` Ad or link variant, such as the value of `utm_content`. **clickIds** `object` Click identifiers from the landing URL, keyed by parameter name (e.g., `fbclid`, `gclid`). Layers derives the originating network from them as `marketing.clickSource` and discards the raw tokens. See [Context data structure](/engine/contextual-information/data-structure#click-identifiers-and-derived-click-source). **referrer** `string` Host or URL of the site that linked the shopper to the storefront (e.g., "google.com"). Layers normalizes it to a lowercase host without `www.`. **landingPath** `string` Storefront path the shopper first landed on this visit (e.g., "/collections/sale"). Layers removes the query string and keeps up to 512 characters. **channel** `string` Arrival channel. Layers derives it from UTMs, click identifiers, and the referring site, and keeps a value you send only when it can't derive one. See [Arrival channel](/engine/contextual-information/data-structure#arrival-channel). **experiments** `object` A/B test assignments for the shopper, keyed by experiment ID with the assigned group ID as the value (e.g., `{"exp_123": "group_b"}`). Used by the **Experiment Group** contextual condition. The Layers app embed fills this from Intelligems automatically; values your storefront sends for the same experiment take precedence. Entries whose value isn't a string are dropped. **customer** `object` Aggregated customer behavior and purchase patterns for personalization. **Properties** **signedIn** `boolean` Whether the customer is currently authenticated. **returning** `boolean` Whether this is a returning customer. **numberOfOrders** `integer` Total number of orders placed. **averageOrderValue** `number` Average order value in store currency. **daysBetweenOrders** `integer` Average days between orders. **daysSinceLastOrder** `integer` Days since the most recent order. **daysSinceOldestOrder** `integer` Days since the first order. **totalSpent** `number` Total amount spent in store currency. **tags** `array` Shopify customer tags on the shopper's profile (e.g., `["vip", "wholesale"]`). Collected by the Storefront Pixel for signed-in customers; `null` for guests. **segments** `array` Shopify customer segment IDs the shopper belongs to. Server-resolved: Layers populates this from the signed-in `identity.customerId` on every request and ignores any value you send. `null` for guests and customers with no segment memberships. Available as `context.customer.segments` in [contextual conditions](/platform/merchandising/contextual-conditions). **market** `string` Explicitly set the Shopify Market for this request. Must be provided inside `context`; it is not a top-level request body parameter. 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 `context.geo.country` (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. When you send a two-letter country code that belongs to the resolved market, Layers also prices for that country, ahead of the shopper's detected location. See [Market resolution](/engine/contextual-information/data-structure#market). **Behavior depends on the store's market application mode** (set under **Settings > Search & Discovery > Search Behavior**, in the **Markets** card): * **Restrict to market catalog** — Products are filtered to only those available in the resolved market, and market-specific pricing is applied * **Adjust pricing only** — The full catalog remains visible, but variant prices are swapped to market-specific values where available * **Ignore markets** (default) — Market resolution is skipped entirely; base catalog and base pricing are used for all shoppers **session** `object` Session-level signals about the current visit. **Properties** **returning** `boolean` Whether the current session belongs to a returning visitor. Layers derives this from the storefront's session cookie when not provided. **locale** `string` Storefront locale code (e.g., `"en"`, `"fr"`, `"pt-br"`). Case-insensitive; Layers normalizes to lowercase. When the locale is published in Shopify and served by the resolved market, Layers returns translated display text (titles, descriptions, option values, filter labels) while IDs, prices, and filter values stay in the source language. Regional locales fall back to their base language (`pt-br` uses `pt`). The store's primary locale returns source text. See [Translations](/shopify-integration/translations). **currency** `string` ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). Case-insensitive; Layers normalizes to uppercase. When Layers can resolve a currency from the shopper's market or pricing context, the server-resolved value takes precedence. **b2bCompany** `string` Shopify B2B company location identifier. When `identity.companyLocationId` is provided, Layers resolves the company location server-side and the server value takes precedence. **shoppingChannel** `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, Fuego, or Mobiloud Canvas are detected as `"app"`). **Accepted values:** * `"web"` — Standard web browser (default) * `"app"` — Mobile app (e.g., Tapcart, Fuego, Mobiloud Canvas) **custom** `object` Custom contextual data specific to your implementation. Structure is flexible and can contain any key-value pairs relevant to your use case. **responseOptions** `object` Per-request overrides for response behavior. Currently controls image preload hints emitted in the `Link` response header. You can disable preloads or narrow the srcset to the breakpoints your storefront uses. You cannot enable preloads when the store has them disabled. **Properties** **mediaPreloads** `object` Controls the `Link: rel=\"preload\"` directives generated for product images in this response. See [Early hints](/sdk/performance#early-hints-link-header-preloading) for background. **Properties** **enabled** `boolean` (default: true) Set to `false` to skip the `Link` header for this request. Useful for server-rendered pages that do not benefit from preload hints, or when you want to reduce response header size. Cannot enable preloads if they are disabled at the store level. **srcsetSizes** `int[]` Custom responsive image widths (in pixels) to emit in `imagesrcset`. Each value must be an integer between `1` and `10000`. Overrides the store-level srcset configuration for this request only. When omitted, the store configuration or platform defaults are used. **sizes** `string` Media query string emitted as the `imagesizes` attribute in the preload `Link` header (for example `(max-width: 600px) 100vw, 50vw`). Tells the browser which srcset width to pick per viewport. Overrides the store-level sizes value for this request only. When omitted or empty, the store configuration is used. Each comma-separated entry may carry a media condition, including the last entry. See the [accepted format](/sdk/performance#customization) for details. The API rejects invalid values with a validation error. **Example:** ```json theme={null} { "responseOptions": { "mediaPreloads": { "enabled": true, "srcsetSizes": [320, 640, 960], "sizes": "(max-width: 600px) 100vw, 50vw" } } } ``` ## Response **results** `Array of Objects` **Properties** **id** `number` The unique identifier of the product. **title** `string` The title of the product. **body\_html** `string` The HTML content describing the product. **vendor** `string` The vendor of the product. **product\_type** `string` The type of the product. **created\_at** `number` The timestamp when the product was created. **handle** `string` The handle of the product. **updated\_at** `number` The timestamp when the product was updated. **published\_at** `number` The timestamp when the product was published. **tags** `Array of strings` The tags associated with the product. **combined\_listing\_parent\_product\_id** `number` The parent product id if a child in a Combined Listing. **combined\_listing\_role** `string` The role of the product if part of a Combined Listing. **images** `Array of Objects` The images of the product. **Properties** **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **variant\_ids** `Array` The variant IDs associated with the image. **metafields** `Object` The metafields of the product. **calculated** `Object` The computed attributes of the product. Only includes attributes with non-null, non-empty values. Attributes that evaluate to null or an empty string are omitted. **category** `Object` The Shopify Product Taxonomy Category of the product. **Properties** **name** `string` The name of the category leaf. **full\_name** `string` The full name of the category. **id** `string` The ID of the category. **is\_leaf** `boolean` Is the category a leaf category. **is\_root** `boolean` Is the category a root category. **first\_or\_matched\_variant** `Object` The first available variant (depending on OOS settings) or the variant matched with a filter or search query. **Properties** **id** `number` The ID of the variant. **title** `string` The title of the variant. **available** `boolean` The availability of the variant. **sku** `number` The sku of the variant. **price** `string` The price of the variant. **compare\_at\_price** `string` The compare at price of the variant. **metafields** `Object` The metafields of the variant. **selected\_options** `Array of Objects` The selected options of the variant. **Properties** **name** `string` The name of the option. **value** `string` The value of the option. **option\_value** `object` The linked metafield of the option. **position** `number` The position of the variant in the product's variant list. **inventory\_quantity** `number` Total inventory quantity across the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope), which is all locations by default. Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_policy** `string` Inventory policy for the variant: `DENY` (stop selling when out of stock) or `CONTINUE` (allow overselling). Only included when the store has the **Expose Variant Inventory** setting enabled. **inventory\_levels** `object` Object mapping location IDs to available inventory quantities (e.g., `{"1001": 5, "1002": 10}`). Returns empty object `{}` when no inventory data exists. Only included when the store has the **Expose Variant Inventory** setting enabled. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **featured\_media** `Object` The featured media of the product. **Properties** **mediaContentType** `string` The type of media. **alt** `string` The alt text of the image. **src** `string` The src of the image. **width** `number` The width of the image. **height** `number` The height of the image. **available** `boolean` The availability of the product. **price\_range** `Object` The price range of the product. **Properties** **from** `number` The starting price of the product. **to** `number` The ending price of the product. **totalResults** `number` The total number of results. **page** `number` The current page number. **totalPages** `number` The total number of pages. **facetRanges** `object` If `includeFacetRanges` is `true` then an object with keys of the facet attribute code and value is an object with min/max. **facets** `object` If `retrieveFacetCount` is `true` then an object with keys and values of the specified attributes. Empty values and literal `"null"` strings are automatically excluded from facet results. **facetDisplay** `object` Only returned when `enrichFacetMetaobjects` is `true` and at least one requested facet is backed by a `metaobject_reference` or `list.metaobject_reference` metafield. Keys are facet attribute codes and values map each facet value (the referenced metaobject's handle) to the metaobject's `display_name` and `fields`. Handles with no matching cached metaobject are omitted here and remain as plain values in `facets`. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the normalized field shape. **attributionToken** `string` A unique request identifier (ULID) for this API call. Use this token to correlate requests with analytics events via the [Beacon API](/tracking-api/send-events). **\_meta** `object` **Properties** **variantBreakouts** `array of objects` Array of variant breakout configurations applied to search. Only present when one or more variant breakouts are active for search requests. Multiple breakouts with different option codes can work simultaneously. **Properties** **id** `string` The unique identifier of the variant breakout configuration. **name** `string` The display name of the variant breakout configuration (e.g., "Gemstone Breakout", "Color Breakout"). **optionCode** `string` The product option code that determines which variants are broken out (e.g., "Stone", "Color"). Each product is broken out by the first matching option code from the array. **mediaPreloads** `object` Echoes the image preload configuration used to build the `Link` response header for this request. Only present when image preloads are emitted. See [Early hints](/sdk/performance#early-hints-link-header-preloading). **Properties** **srcsetSizes** `int[]` The responsive image widths (in pixels) used in the `imagesrcset` of the `Link` header. Reflects the request override when provided, otherwise the store-level configuration or platform defaults. **search\_lane** `string` Only present when Layers is temporarily serving keyword-only results platform-wide. The only value is `"prefix_only"`. Precomputed similar products results continue to be served normally in this mode. Requests that Layers would compute in real time (for example, new products or requests with `variant_id`) return a well-formed empty response (`results: []`, `totalResults: 0`) with this field set, instead of an error. **\_workflow** `array of objects` An ordered trace of processing steps the engine performed. See the [Text Search](/api-reference/search) documentation for the full list of possible step types. ### Response headers | Header | Description | | - | - | | `x-request-id` | A unique identifier (ULID) for the request. This matches the `attributionToken` in the response body. | | `x-layers-build` | The Layers build version that served the request. | | `X-Layers-Results-Cache` | Indicates whether the response was served from the results cache. Returns `HIT` or `MISS`. | | `Link` | Contains `rel="preload"` directives for product images (up to 6 items). See [Early hints](/sdk/performance#early-hints-link-header-preloading) for details. Only included when early hints are enabled (enabled by default). | ```json Request theme={null} POST /storefront/v1/search/product/7003338965178 { "variant_id": 41234567890123, "pagination": { "page": 1, "limit": 20 }, "context": { "geo": { "country": "US" }, "shoppingChannel": "web" }, "identity": { "sessionId": "abc123", "deviceId": "device-uuid" } } ``` ```json Response theme={null} { "results": [ { "id": 7003338965178, "title": "SUPREME SEALLINE SEE POUCH SMALL", "body_html": "The Supreme Sealline See Pouch Small is a versatile and waterproof storage solution that seamlessly marries utility and style. With its clear window for easy visibility and the iconic Supreme branding, it's a sought-after accessory for those who appreciate keeping their essentials dry while making a fashion statement, whether at the beach or in the city..", "vendor": "SUPREME", "product_type": "Accessories", "created_at": "2022-02-05T01:22:05.000000Z", "handle": "supreme-pouch-44370ss18a32-sm", "updated_at": "2023-10-25T20:47:04.000000Z", "published_at": "2022-02-05T01:22:05.000000Z", "tags": [ "consignment", ], "images": [ { "alt": "SUPREME POUCH", "src": "https://cdn.shopify.com/s/files/1/0588/3677/9194/products/ss18_supreme_tnf_pouch_blk_2-l_5fb1316e-22f7-4702-9953-57f3fbdda5be.jpg?v=1644047927", "width": 800, "height": 534, "variant_ids": [] } ], "metafields": { "product": { "alias": "SEALLINE SEE POUCH SMALL", "colorway": "BLACK", "styleCode": "SS18A30 BLACK", "yearOfRelease": 2018, "searchColor": [ "black" ] } }, "available": true, "price_range": { "from": 30, "to": 30 } } ], "totalResults": 1000, "page": 1, "totalPages": 20, "facets": { "vendor": { "ADIDAS": 30, "JORDAN": 336, "NEW BALANCE": 15, "NIKE": 384, "REEBOK": 4, "SUPREME": 624, "VANS": 32 } }, "attributionToken": "2y10smI2dB7XZXXFJsLUELltgueq8NRdcRD3U8djkLqxQmaVMvg1lSCf2" } ``` # Sort Orders API: Get Available Sort Orders Source: https://docs.uselayers.com/api-reference/sort-orders GET /sort-orders Sort Orders API endpoint listing all configured sort orders for your store, including IDs and labels you can pass to browse and search requests. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Accept** `string` *required* (default: application/json) ## Response **sortOrders** `array` Array of available sort orders for the store. **Properties** **code** `string` The unique code identifier for the sort order. **nickname** `string` The human-readable name for the sort order. ```json Response theme={null} { "sortOrders": [ { "code": "relevance", "nickname": "Relevance" }, { "code": "price_asc", "nickname": "Price: Low to High" }, { "code": "price_desc", "nickname": "Price: High to Low" }, { "code": "created_at_desc", "nickname": "Newest First" } ] } ``` # Image Search: Upload Image Source: https://docs.uselayers.com/api-reference/upload-image POST /images/upload Image Upload API endpoint that accepts a binary image and returns an image ID you can pass into the Image Search endpoint for visual product lookup. ## Authorization **X-Storefront-Access-Token** `string` *required* Token-based authentication header in the form of ``. ## Headers **Content-Type** `string` *required* (default: multipart/form-data) **Accept** `string` *required* (default: application/json) ## Body **image** `file` *required* Image file to upload. Supported formats: JPEG, JPG, PNG, WebP, HEIC, and HEIF. Maximum file size: 15MB (15,360 KB). Maximum dimensions: 8,192 pixels per side and 40,000,000 total pixels. **crop\_x** `integer` X-coordinate (in pixels) of the top-left corner of the crop region. Must be `0` or greater. When provided, all four crop parameters (`crop_x`, `crop_y`, `crop_width`, `crop_height`) are required. **crop\_y** `integer` Y-coordinate (in pixels) of the top-left corner of the crop region. Must be `0` or greater. **crop\_width** `integer` Width (in pixels) of the crop region. Must be `1` or greater. **crop\_height** `integer` Height (in pixels) of the crop region. Must be `1` or greater. ## Response **status** `string` Status of the upload operation. Returns "success" on successful upload. **imageId** `string` Unique UUID identifier for the uploaded image. Use this ID in the Image Search API to perform visual searches. ## Usage The Image Upload endpoint enables a two-step process for visual search: 1. **Upload the image** using this endpoint to receive an `imageId` 2. **Search with the image** using the `imageId` in the [Image Search API](/api-reference/search-image) This approach offers several advantages: * **Better performance**: Avoids repeated base64 encoding/decoding * **Caching**: Processed image data is cached for faster subsequent searches * **Reduced payload size**: Use lightweight UUID instead of large base64 strings ## Rate limits Layers rate limits uploads to protect image processing capacity: * **10 requests per minute** per client (IP address) per store * **120 requests per minute** per store across all clients If you exceed either limit, the endpoint returns `429 Too Many Requests`. Wait the number of seconds given in the `Retry-After` response header before retrying. To stay under the limit, upload each image once and reuse the returned `imageId` for subsequent [Image Search](/api-reference/search-image) requests instead of re-uploading. ## Error responses **errors** `object` Validation errors returned when the request fails validation. Common validation errors: * **File required**: No image file provided * **Invalid file type**: File format not supported (must be JPEG, JPG, PNG, WebP, HEIC, or HEIF) * **File too large**: Image exceeds 15MB size limit * **Missing crop parameters**: All four crop parameters must be provided together ### Image dimension limits Layers checks the declared dimensions of every upload before accepting it. The endpoint returns `422 Unprocessable Content` and does not store the image when: * Either side exceeds **8,192 pixels**, or the total pixel count exceeds **40,000,000** (width × height). The response message is `Image dimensions exceed the maximum of 8192px per side or 40000000 total pixels`. * The file cannot be decoded as an image. The response message is `Image could not be decoded`. These limits apply to the source image's declared dimensions, not the file size. Layers rejects a small file that declares oversized dimensions. If your source image is larger than the limits, downscale it client-side before uploading. Layers resizes accepted images to 1000px for processing, so downscaling to 1000px on the longest side loses no search quality. ```json Response theme={null} { "status": "success", "imageId": "550e8400-e29b-41d4-a716-446655440000" } ``` ```json Error Response theme={null} { "message": "The given data was invalid.", "errors": { "image": [ "The image field is required." ] } } ``` # Product attributes: core concepts Source: https://docs.uselayers.com/core-concepts/attributes Attributes are the foundation of the Layers platform. They define what your products are made of and how they can be searched, filtered, and sorted. ## What are attributes? Attributes are the building blocks of your product catalog in Layers. Every piece of product data, from titles and descriptions to metafields and computed values, is represented as an attribute. How you configure each attribute controls how products can be searched, filtered, and sorted. Each attribute has three core properties that determine where and how it can be used across the platform: ```mermaid theme={null} graph TD A[Product Attributes] --> B[Searchable] A --> C[Filterable] A --> D[Sortable] B --> E[Text Search] B --> F[Image Search] C --> G[Faceted Navigation] C --> H[Collection Filtering] D --> I[Sort Orders] D --> J[Merchandising Rules] style A stroke:#2563eb,stroke-width:3px style B stroke:#2563eb,stroke-width:2px style C stroke:#2563eb,stroke-width:2px style D stroke:#2563eb,stroke-width:2px ``` ## How attributes power the platform Every feature in Layers depends on attributes. When you mark an attribute as **searchable**, it becomes part of your text and image search indexes. When you mark an attribute as **filterable**, it becomes available as a facet so customers can narrow results by that value. When you mark an attribute as **sortable**, it can be used in sort orders and merchandising rules to control product ranking. The attributes you configure shape the quality of your search results, the filters available to your customers, and the sort orders you can create. ## Types of attributes **Catalog attributes** come directly from your Shopify product data. They reference fields in your product schema, including standard fields, product options, taxonomy metafields, and custom metafields. Catalog attributes are automatically created during syncs. **Computed attributes** are dynamic values derived from logic you define in the dashboard. Computed attributes let you create new data points from existing product data without modifying your Shopify catalog, such as calculating a discount percentage from price and compare-at price. ## Key capabilities * **Keyword search weight** — Control how much influence each searchable attribute has on keyword-based ranking. For example, prioritize title matches over description matches. * **Attribute classes** — Classify attributes as categorical, feature, price, or identifier to help the search engine apply specialized handling and improve relevance. * **API visibility** — Control whether an attribute appears in storefront responses or stays hidden from customer-facing API requests. * **Storefront facet sync** — Choose whether filterable attributes are synced to Shopify as metaobjects for native storefront filtering. ## Next steps * [Managing catalog attributes](/platform/attributes) — Full guide to configuring searchable, filterable, and sortable attributes * [Catalog attributes](/platform/attributes/catalog-attributes) — Codes, metafield creation, and nested key support * [Attribute options](/platform/attributes/attribute-options) — Searchable, filterable, sortable, and visibility settings * [Attribute classes](/platform/attributes/attribute-classes) — Categorical, feature, price, and identifier classifications * [Computed attributes](/platform/attributes/calculated-attributes) — Creating dynamic attribute values with Functions * [Filtering language](/engine/filtering) — How attributes power the filtering language * [Sorting](/core-concepts/sorting) — How sortable attributes feed into sort orders # Merchandising Source: https://docs.uselayers.com/core-concepts/merchandising Merchandising rules give you manual and automated control over how products are displayed on collection pages, layered on top of your sort orders. ## What is merchandising in Layers? Merchandising rules let you take direct control of how products appear on your collection pages. You can manually pin products to specific positions, create expressions that automatically group and prioritize products based on attributes, or combine both approaches for a hybrid strategy. Merchandising rules extend your sort orders rather than replace them. Products that aren't pinned or matched by expressions continue to follow the base sort order. ## How merchandising fits into the platform Layers uses a priority hierarchy to determine the final order of products on collection pages. Dynamic linking takes the highest priority, followed by merchandising rules, and finally the base sort order: ```mermaid theme={null} graph TD subgraph "Override Behavior" DL[Dynamic Linking] --> DLE{Dynamic Linking Applied?} DLE -->|Yes - Page 1| DLP[Dynamic Linked Products First] DLE -->|No| L[Base Sort Order] DLP --> M{Merchandising Rule Exists?} L --> M M -->|Yes| N[Apply Rule] M -->|No| O[Use Base Sort Order] N --> P[Pinned Products First] P --> Q[Promote / Demote Expressions Second] Q --> S{Diversity Enabled?} S -->|Yes| T[Product Families Cap Applied] S -->|No| R[Remaining Products by Base Sort] T --> R O --> R end style DL stroke:#dc2626,stroke-width:2px style N stroke:#dc2626,stroke-width:2px style T stroke:#7c3aed,stroke-width:2px ``` **Priority hierarchy:** 1. **Dynamic linking** (first page only) — Products from ad campaigns or promotional URLs appear first 2. **Merchandising rules** — Manually pinned products and expression-based groups 3. **Base sort order** — The underlying sort order for all remaining products ## Types of merchandising **Manual merchandising** lets you pin specific products to exact positions on a collection page, so you choose which items get the most visibility. Pins clustered at the top front-pack as a group, and pins dropped further down hold their exact slot. See [pin placement](/platform/merchandising/pins#pin-placement) for the full rules. **Automated merchandising** uses expressions to automatically group and prioritize products based on attributes like product type, vendor, tags, or other criteria. **Hybrid merchandising** combines manual pins with expressions, so you control a few exact positions and let expressions arrange the rest. ## Key capabilities * **Product families** — Group related products (like color variants of the same style) into families so diversity expressions can cap near-duplicates and show a broader assortment * **Diversity expressions** — Limit how many products from the same family appear near the top of a collection, powered by [product families](/platform/product-families) * **Contextual conditions** — Target different audiences with different merchandising strategies based on shopper context (location, channel, customer data) * **Rule scheduling** — Automatically enable and disable rules based on time windows for campaigns and promotions * **Soft boost expressions** — Gently adjust product positions within the sort order without creating hard clusters * **Draft and filtering** — Control how draft products and filters interact with your rules * **Multiple rules per collection** — Layer multiple rules on a single collection with priority ordering * **Live preview** — Preview merchandising on your live storefront before saving or publishing ## Next steps * [Merchandising rules](/platform/merchandising) — Full guide to creating and managing rules * [Product families](/platform/product-families) — Grouping related products for diversity * [Diversity expressions](/platform/merchandising/diversity) — Capping near-duplicates using product families * [Pins & media overrides](/platform/merchandising/pins) — Manual product pinning * [Expressions & automation](/platform/merchandising/expressions) — Attribute-based product grouping * [Soft boost expressions](/platform/merchandising/soft-boost-expressions) — Gentle ranking adjustments * [Contextual conditions](/platform/merchandising/contextual-conditions) — Audience targeting * [Rule scheduling](/platform/merchandising/scheduling) — Time-based activation * [Create a merchandising rule](/help/merchandising/create-merchandising-rule) — Step-by-step guide # Search Source: https://docs.uselayers.com/core-concepts/search How Layers processes search queries using ranking signals, query understanding, and contextual awareness to deliver relevant product results. ## What is search in Layers? Search is the system that connects your customers to your products. When a shopper types a query, Layers combines semantic understanding, keyword relevance, engagement data, and contextual awareness to rank and return the most relevant products. Layers supports multiple search modes: **text search** for keyword and natural-language queries, **image search** for visual discovery, **similar product search** for finding related items, and **autocomplete** for real-time query suggestions. ## How search ranking works Every text search result is scored using five signal groups. Each group contributes a percentage of the total score, and all group weights always sum to 100%: | Signal group | What it measures | | - | - | | **Semantic** | How closely product content matches the meaning of the query | | **Keyword** | How well exact terms in the query match product fields | | **Engagement** | How customers interact with products (views, sales, cart sessions) | | **Freshness** | How recently the product was published | | **Inventory** | Whether the product is in stock | You control how much each signal group contributes to the final score on the **Relevancy** → **Signal Weights** page in the dashboard. ## Query understanding Layers interprets what your customers mean as well as the words they type. The query understanding pipeline includes: * **Query interpretation** — Analyzes each query to correct typos, detect non-product queries that should redirect to help or policy pages, and identify SKU-style lookups. * **Query expansion** — Enriches searches with synonyms and related terms. A search for "sneakers" also considers "athletic shoes" and "trainers." * **Intent detection** — Recognizes signals like price sensitivity, sale interest, and feature preferences within the query. * **Contextual awareness** — Uses cart contents, purchase history, and geographic location to personalize how queries are interpreted. ## Ranking rules Beyond global signal weights, you can create **ranking rules** that apply conditional adjustments to search results: * **Promote** — Move products matching specific attributes higher in results * **Demote** — Move products matching specific attributes lower in results * **Pin** — Lock specific products to exact positions for particular queries Rules can be scoped globally or triggered by specific query conditions, including exact match, substring match, and semantic similarity. ## Request transforms Request transforms modify how search requests are processed before results are returned. A request transform can replace or modify the search query, add filters, or override sort orders. Request transforms apply based on targeting conditions like the query itself, the collection the shopper is browsing, or shopper context such as location, channel, and customer data. ## Next steps * [Ranking relevancy](/platform/ranking-relevancy) — Tuning signal weights and creating ranking rules * [Query understanding](/engine/user-intent-processing) — How Layers interprets search queries * [Query interpretation](/engine/query-interpretation) — How typo correction, redirect routing, and SKU detection work together * [Typo tolerance](/engine/typo-tolerance) — How spelling mistakes are corrected * [Request transforms](/platform/request-transforms) — Dynamic request modification based on conditions * [Filtering language](/engine/filtering) — Applying filters to narrow search results * [Tune signal weights](/help/ranking-relevancy/tune-signal-weights) — Step-by-step guide to adjusting ranking # Sorting Source: https://docs.uselayers.com/core-concepts/sorting Sort orders determine how products are ranked on collection pages using attributes, priority rules, weighted groups, and soft boost. ## What is sorting in Layers? Sort orders control the sequence in which products appear on your collection pages. A sort order can combine multiple signals: product attributes, priority rules, weighted attribute groups, and soft boost. ## How sorting fits into the platform Sort orders build upon your [attribute](/core-concepts/attributes) configuration. Only attributes marked as **sortable** can be used in sort orders. Sort orders can use [sequences](/platform/sequences) to keep related products together, and are subject to [merchandising rule](/core-concepts/merchandising) overrides: ```mermaid theme={null} graph TD A[Attributes] --> B[Sort Orders] A --> PF[Product Families] B --> C{Sequences Enabled?} C -->|Yes| D[Sequences Applied] C -->|No| E[Standard Sort] D --> F[Collection Results] E --> F G[Merchandising Rules] --> H{Diversity Enabled?} PF --> H H -->|Yes| I[Family Caps Applied] H -->|No| J[Final Results] I --> J F --> G ``` ## Key sorting capabilities **Priority rules** are hard overrides that force products to the top or bottom of results based on conditions you define. Promoted products appear at the top and demoted products appear at the bottom. Priority rules are always evaluated first. **Weighted attribute groups** let you combine multiple sortable attributes and metrics into a single blended score, with relative weights and per-attribute direction (higher or lower is better). For example, you could sort by 60% sales performance and 40% freshness to balance proven sellers with new arrivals. Weighted groups can be combined with soft boost to layer modifiers on top of the blend. **Soft boost** adjusts product positions without creating hard clusters. Unlike priority rules, soft boost interleaves boosted products within the existing sort order. **Segmented sorting** changes product rankings based on visitor context like geographic location or marketing channel, so different audiences see different sort behavior. ## Next steps * [Sort orders](/platform/sorting) — Full guide to creating and managing sort orders * [Priority rules](/platform/sorting/priority-rules) — Hard overrides for product positioning * [Weighted groups](/platform/sorting/weighted-groups) — Blend several attributes and metrics into a single sort score * [Soft boost](/platform/sorting/soft-boost) — Gentle, natural ranking adjustments * [Segmented sorting](/platform/sorting/segmented-sorting) — Context-aware personalized sorting * [Sort order recipes](/platform/sorting/recipes) — Pre-configured sort orders to get started * [Preview & annotations](/platform/sorting/preview) — Testing sort orders before publishing * [Create a sort order](/help/sort-orders/create-sort-order) — Step-by-step guide # What the app embed and SDK handle for you Source: https://docs.uselayers.com/developers/app-embed Reference for what the Layers app embed and SDK handle automatically — auth, identity, cart context, attribution, tracking, semantic redirects, and more. ## Overview Most of what makes a Layers integration work end-to-end is **not** code you write in your theme. The Layers app embed (the theme app extension) and the [`@commerce-blocks/sdk`](/sdk/overview) handle the cross-cutting concerns (authentication, identity, cart and customer context, attribution, tracking, third-party forwarding, semantic redirects, and dynamic linking), so your theme code only has to worry about rendering search, browse, blocks, and banner UI. This page is the reference for what is handled automatically. If something on this list isn't behaving in your theme, the fix is almost always a configuration toggle in the Layers dashboard or an embed setting. It is not theme code. > [!NOTE] > > The app embed and the SDK are independent. The app embed is the [Storefront Pixel](/shopify-integration/storefront-pixel) + cross-cutting integrations. The SDK is the optional client library you use to call the Layers APIs. You can use the app embed without the SDK (vanilla `fetch` from Liquid) and you can use the SDK without the app embed (custom storefront), but the two are designed to work together on a Shopify theme. ## What the app embed handles The app embed is delivered as a Shopify theme app extension. Once it is toggled on under **Online Store → Themes → Customize → App embeds**, the following behavior is automatic. ### Authentication and identity * **Storefront token loading.** The embed writes a ` ``` ## 1. Autocomplete in the header The [Autocomplete endpoint](/api-reference/predict) is a `GET` request that returns suggested queries as the shopper types. It also surfaces [semantic redirects](/platform/semantic-redirects). If the typed text matches a configured redirect, the response includes `_meta.redirect`. > [!NOTE] > > With the Layers [app embed](/developers/app-embed) enabled, your theme doesn't handle `_meta.redirect`. The Storefront Pixel reads it from the autocomplete response and sends the shopper to the destination when they submit that query or click its suggestion. Search results pages redirect the same way. Only headless storefronts that don't load the embed need to navigate on `_meta.redirect.url` themselves. ```html theme={null}
``` ```js theme={null} const input = document.getElementById('search-input') const list = document.getElementById('search-suggestions') let abort input.addEventListener('input', async (event) => { const query = event.target.value.trim() if (!query) { list.hidden = true return } abort?.abort() abort = new AbortController() const response = await fetch( `${window.layersConfig.apiBase}/search/complete?query=${encodeURIComponent(query)}`, { headers: { 'X-Storefront-Access-Token': window.layersConfig.storefrontApiToken }, signal: abort.signal, } ).catch(() => null) if (!response?.ok) return const data = await response.json() list.innerHTML = data.matchedQueries .map( (q) => `
  • ${q}
  • `, ) .join('') list.hidden = data.matchedQueries.length === 0 }) ``` `original_query` carries the shopper's typed text so the executed suggestion is attributed to what they actually typed. Debounce input events (300 ms, the default for the SDK's `createDebounce()`, is a good starting point) and abort the previous request on each keystroke. The autocomplete snippet uses `AbortController` to abort the previous request. ## 2. Prepare the search before the results page Call `prepare` the moment the shopper commits to a search (presses enter or clicks a suggestion). The endpoint returns a `search_id` immediately while Layers continues working on personalization in the background. The prepared data is cached for **15 minutes**. You have two practical options: **Option A: prepare on submit and persist the `search_id`.** Best when you can intercept the form submit. ```js theme={null} const form = document.querySelector('form[role="search"]') form.addEventListener('submit', async (event) => { event.preventDefault() const query = form.q.value.trim() if (!query) return // Fire and forget - don't await the full response const preparePromise = fetch( `${window.layersConfig.apiBase}/search/${encodeURIComponent(query)}/prepare`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': window.layersConfig.storefrontApiToken, }, body: JSON.stringify({ // Pass any shopper context you already have (cart, geo, marketing) context: window.layersContext ?? {}, }), } ) .then((r) => r.json()) .then((d) => d.search_id) // Stash the promise so the results page can await it without re-issuing prepare sessionStorage.setItem(`layers:prepare:${query}`, '') preparePromise.then((id) => { sessionStorage.setItem(`layers:prepare:${query}`, id) }) // Navigate to the results page - prepare keeps running in the background window.location.href = `/search?q=${encodeURIComponent(query)}` }) ``` **Option B: prepare on the search results page itself.** Simpler, but loses the in-flight head start during navigation. Use this when you can't intercept the submit (e.g. native form action). ```liquid theme={null} {% comment %} On templates/search.liquid {% endcomment %} ``` ```js theme={null} const query = window.layersSearchQuery const searchIdPromise = fetch( `${window.layersConfig.apiBase}/search/${encodeURIComponent(query)}/prepare`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': window.layersConfig.storefrontApiToken, }, body: JSON.stringify({ context: window.layersContext ?? {} }), } ) .then((r) => r.json()) .then((d) => d.search_id) ``` > [!TIP] > > `prepare` returns HTTP 202 with a `search_id` even before personalization finishes. Always treat it as non-blocking. Never `await` it on the critical path. You can also hand the `search_id` to the results page in the URL (`/search?q=...&search_id=...`) instead of `sessionStorage`. This is useful when the submit happens off-page or when you want the prepared ID preserved in shared or bookmarked links. When an autocomplete suggestion click (rather than typed input) drives the search, also include `original_query` set to the shopper's typed text so analytics and intent modifiers can attribute the executed suggestion back to what the shopper actually typed. The storefront pixel treats `search_id` and `original_query` as first-class URL parameters. ## 3. Execute the search On the results page, call the [Search API](/api-reference/search) with the prepared `search_id`. If `prepare` hasn't returned yet, `execute` waits briefly for it; if more than 15 minutes have passed (or the id is missing), Search falls back to normal processing automatically. ```js theme={null} async function executeSearch({ query, sortCode, filters, facetCodes, page = 1 }) { const params = new URLSearchParams(location.search) const searchId = params.get('search_id') || // URL handoff (shared/bookmarked links) sessionStorage.getItem(`layers:prepare:${query}`) || (await searchIdPromise) // from option B const response = await fetch( `${window.layersConfig.apiBase}/search/${encodeURIComponent(query)}/execute`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': window.layersConfig.storefrontApiToken, }, body: JSON.stringify({ search_id: searchId || undefined, sort_order_code: sortCode || undefined, filter_group: filters, facets: facetCodes, retrieveFacetCount: true, includeFacetRanges: true, pagination: { page, limit: 24 }, }), } ) return response.json() } ``` Key body fields: | Field | Purpose | | :- | :- | | `search_id` | ULID returned by `prepare`. Reuses the cached personalization work. Omit to fall back to standard processing. | | `sort_order_code` | The selected sort metaobject `code`. Omit for relevance-ranked results. | | `filter_group` | Active filters expressed via [filter expressions](/sdk/api-reference/filtering). | | `facets` | List of facet codes (or wildcards like `options.*`) to return values for. | | `retrieveFacetCount` | Include per-value result counts. | | `includeFacetRanges` | Include `min`/`max` for numeric facets (price, ratings). | ## 4. Render facet and sort controls from Liquid Facet and sort controls follow the metaobject pattern described in [Liquid integration](/developers/liquid-integration). Read the metaobjects in Liquid, then pass codes to the API. Filter sort orders by the `search` scope on the search page. ```liquid theme={null} {% assign layers_sorts = shop.metaobjects['app--278936322049--sort_order'] | sort: 'order' %} {% assign layers_facets = shop.metaobjects['app--278936322049--facet'] %}
    ``` For the JavaScript that hydrates the facet and sort controls, see: * [Rendering facets in Liquid](/developers/rendering-facets-in-liquid) — populating filter values with counts and ranges * [Rendering sort orders in Liquid](/developers/rendering-sort-orders-in-liquid) — sort dropdown wiring ## Recommended request flow The end-to-end timeline for a typical search: **1. Header submit** Shopper presses enter. Fire `prepare` (non-blocking) and navigate to `/search?q=...`. Prepare keeps running while the browser loads the results page. **2. Results page render** Liquid renders the full page frame (title, search bar, sort dropdown, empty facet groups, and a skeleton grid), including the active sort/filter state from the URL. The first paint is complete with no client-injected markup (which causes layout shift and hides the search bar while scripts load). **3. Execute** Page JS calls `execute` with the `search_id` from `prepare`, plus any active sort and filters from the URL. Hydrate results into the skeletons in place; for result cards, render tiles through the theme's own card snippet via the [Section Rendering API](/developers/rendering-blocks-with-the-sdk#rendering-cards-with-your-themes-own-liquid-snippets). **4. Interaction** On sort change or filter toggle, re-issue `execute` with the same `search_id` plus the updated `sort_order_code` / `filter_group`. Update the URL so the state survives refresh and back navigation. ## Submit click feedback Once a shopper clicks a result, call the [Search feedback endpoint](/api-reference/search-feedback) with the click event. Click feedback trains relevancy over time. Without it, semantic ranking and personalization can't improve. The Storefront Pixel handles this automatically for themes using the standard search results template. If you're rendering your own grid, send the feedback manually using the `attributionToken` returned in the `execute` response. ## Troubleshooting **`execute` returns no results for a known-good query.** Check that `prepare` and `execute` use the **same** `searchQuery` path parameter (and URL-encoded identically). A mismatched query invalidates the prepared cache and falls back to standard processing. **Suggestions show but redirects don't fire.** The Storefront Pixel performs redirects, so confirm the Layers app embed is enabled and that the configured redirect term in the dashboard actually matches the typed query. On a headless storefront without the embed, your code must follow `_meta.redirect.url` itself. **Stale sort or filter state after back navigation.** Read the active state from `request.params` in Liquid on first render, and mirror every sort/filter change to the URL via `history.replaceState`. The next page load and any back navigation will then hydrate correctly. **Prepare returns 202 but execute is slow.** The prepared cache lives for 15 minutes. If `execute` runs much later, the cache is gone and you're paying normal processing cost. Don't cache `search_id` values across sessions. ## See also * [Liquid integration](/developers/liquid-integration) — metaobject and metafield access * [Rendering facets in Liquid](/developers/rendering-facets-in-liquid) — filter sidebar pattern * [Rendering sort orders in Liquid](/developers/rendering-sort-orders-in-liquid) — sort dropdown pattern * [Search API](/api-reference/search) and [Prepare Search](/api-reference/search-prepare) endpoints * [Autocomplete API](/api-reference/predict) — typeahead suggestions * [Filter expressions](/sdk/api-reference/filtering) — filter group grammar # Implementing search with the SDK Source: https://docs.uselayers.com/developers/implementing-search-with-the-sdk Build a Shopify theme search experience with @commerce-blocks/sdk using autocomplete, prepare/get, facets, sort orders, and reactive controllers. ## Overview This guide is the SDK equivalent of [Implementing search in Liquid](/developers/implementing-search-in-liquid). The same four moving pieces apply: autocomplete, prepare, get, and facets and sort orders. Each is exposed as an SDK controller. The SDK handles request deduplication, prepared search IDs, and reactive state for you. Use this version when you have already installed [`@commerce-blocks/sdk`](/sdk/installation) in your theme. For a no-dependencies version, see the [Liquid + Fetch guide](/developers/implementing-search-in-liquid). ## Prerequisites * The Layers Shopify app installed and synced. * The SDK installed and initialized with `storage` when you need to reuse prepared search IDs across pages. See the [installation guide](/sdk/installation). * The [Storefront Pixel](/shopify-integration/storefront-pixel) installed. The pixel owns device and session identifiers on the storefront; pass them to `createSDK()` through `identity` as a static object or resolver for SDK-issued requests. ## Controllers used | Controller | Purpose | | :- | :- | | `sdk.autocomplete()` | Typeahead suggestions | | `sdk.search()` | Prepare + get the full search request | | `sdk.facets()` | Fetch facet counts for a search or collection | | `sdk.sortOrders()` | Fetch available sort options | All four controllers expose the same reactive `state` and `subscribe()` shape as the collection controller. ## 1. Autocomplete in the header `autocomplete()` fetches suggestions as the shopper types. When a typed query matches a [semantic redirect](/platform/semantic-redirects), the response carries `data._meta.redirect.url`. > [!NOTE] > > With the Layers [app embed](/developers/app-embed) enabled, don't navigate on `_meta.redirect` yourself. The Storefront Pixel remembers the redirect and sends the shopper there when they submit that query or click its suggestion, and it redirects search results pages the same way. Keep rendering the suggestion list. Only headless storefronts that don't load the embed need to follow `data._meta.redirect.url` in their own code. ```html theme={null}
    ``` ```js theme={null} import { getSDK, createDebounce } from '@commerce-blocks/sdk' const { data: sdk, error: sdkError } = getSDK() if (sdkError) { console.error('SDK not initialized:', sdkError.message) } const input = document.getElementById('search-input') const list = document.getElementById('search-suggestions') let autocompleteController const { call: debouncedSearch } = createDebounce(async (query) => { if (autocompleteController) autocompleteController.dispose() autocompleteController = sdk.autocomplete() autocompleteController.subscribe(({ data, error }) => { if (error) { console.error('Autocomplete failed:', error.message) return } if (!data) return list.innerHTML = data.matchedQueries .map( (q) => `
  • ${q}
  • `, ) .join('') list.hidden = data.matchedQueries.length === 0 }) await autocompleteController.get({ query }) }, 200) input.addEventListener('input', (event) => { const query = event.target.value.trim() if (!query) { list.hidden = true return } debouncedSearch(query) }) ``` The controller handles deduplication and guards its state against stale results. Disposing the previous controller clears its subscribers, so its pending result cannot render through that subscription. The network request still runs. Controller `get()` does not accept an `AbortSignal`; use [direct Fetch requests](/developers/implementing-search-in-liquid) if you need to abort the network request. ## 2. Prepare the search before the results page `prepare()` is a first-class method on `sdk.search()`. Call it the moment a shopper commits to a search. The SDK kicks off the request, caches the resulting `search_id` against the query, and `get()` automatically reuses it on the next page. **Option A: prepare on submit.** Best when you can intercept the form submit so prepare keeps running during navigation. ```js theme={null} import { getSDK } from '@commerce-blocks/sdk' const { data: sdk, error: sdkError } = getSDK() if (sdkError) { console.error('SDK not initialized:', sdkError.message) } const form = document.querySelector('form[role="search"]') form.addEventListener('submit', async (event) => { event.preventDefault() const query = form.q.value.trim() if (!query) return const search = sdk.search({ query }) const { error } = await search.prepare() if (error) { console.error('Prepare failed:', error.message) return } window.location.href = `/search?q=${encodeURIComponent(query)}` }) ``` **Option B: prepare on the search results page.** Simpler, but loses the in-flight head start. ```liquid theme={null} ``` ```js theme={null} import { getSDK } from '@commerce-blocks/sdk' const { data: sdk, error: sdkError } = getSDK() if (sdkError) { console.error('SDK not initialized:', sdkError.message) } const search = sdk.search({ query: window.layersSearchQuery }) await search.prepare() ``` > [!TIP] > > Awaiting `prepare()` before navigation is what persists the prepared `search_id` for cross-page reuse. If you cannot await it, the results page still works, but it repeats the prepare step. The SDK resolves the prepared `search_id` itself. `get()` does not read a `search_id` from the URL, so a shopper landing on a shared link without a matching prepare entry gets standard processing. Still put it there (`/search?q=...&search_id=...`) for pixel attribution on shared or bookmarked links. The prepared cache is not reused on a fresh visit, so the ID in the URL preserves attribution, not speed. Also add `original_query` when an autocomplete suggestion click (rather than typed input) drove the search, so analytics can attribute the executed suggestion to what the shopper typed. The storefront pixel treats both as first-class URL parameters. ## 3. Get the search results On the search results page, `get()` resolves the prepared `search_id` automatically when the query and request parameters match. You do not need to read an ID from the URL or pass one to `get()`. The SDK falls back to standard processing if the prepare entry has expired or no prepare ran. ```js theme={null} import { getSDK, filter, and, eq } from '@commerce-blocks/sdk' const { data: sdk, error: sdkError } = getSDK() if (sdkError) { console.error('SDK not initialized:', sdkError.message) } const params = new URLSearchParams(location.search) const query = params.get('q') || '' const sort = params.get('sort') || undefined const page = Number(params.get('page')) || 1 const search = sdk.search({ query }) search.subscribe(({ data, loading, error }) => { if (loading) showLoading() if (error) showError(error.message) if (data) { renderGrid(data.products) renderFacets(data.facets, data.facetRanges) renderPagination(data.page, data.totalPages) } }) await search.get({ sort, pagination: { page }, filterGroup: readActiveFiltersFromUrl(params), }) ``` > [!NOTE] > > Render the results page frame (title, search bar, sort/facet controls, and a skeleton grid) in Liquid so the first paint is complete, then hydrate in place. Injecting the frame from JS causes layout shift and hides the search bar while scripts load. For result cards, render tiles through the theme's own card snippet via the [Section Rendering API](/developers/rendering-blocks-with-the-sdk#rendering-cards-with-your-themes-own-liquid-snippets) rather than a client-side card renderer. A simple `readActiveFiltersFromUrl` helper builds a filter group from URL parameters. Replace the attribute names with the codes configured in your Layers dashboard: ```js theme={null} function readActiveFiltersFromUrl(params) { const expressions = [] for (const [key, value] of params.entries()) { if (key.startsWith('filter_')) { const attribute = key.replace('filter_', '') expressions.push(eq(attribute, value)) } } return expressions.length > 0 ? filter(and(...expressions)) : undefined } ``` Controller options merge across calls, so subsequent interactions only pass what is changing: ```js theme={null} search.get({ sort: 'price-asc', pagination: { page: 1 } }) // change sort, reset page search.get({ filterGroup: filter(eq('your-attribute', 'your-value')) }) // add filter, keep sort search.get({ pagination: { page: 2 } }) // pagination, keep everything else ``` ## 4. Render facet and sort controls at runtime In v3, sort orders and facets are not configured at SDK init. Fetch them at runtime with `sdk.sortOrders()` and `sdk.facets()`. ```js theme={null} import { getSDK, filter, and, eq } from '@commerce-blocks/sdk' const { data: sdk, error: sdkError } = getSDK() if (sdkError) { console.error('SDK not initialized:', sdkError.message) } // Sort dropdown const sortController = sdk.sortOrders() const { data: sortData, error: sortError } = await sortController.get() if (!sortError && sortData) { renderSortDropdown(sortData.sortOrders) } // Facet counts const facetController = sdk.facets({ collectionHandle: 'search' }) const { data: facetData, error: facetError } = await facetController.get() if (!facetError && facetData) { renderFacets(facetData.facets, facetData.facetRanges) } ``` You can also request filtered facet counts by passing the active `filterGroup`: ```js theme={null} await facetController.get({ filterGroup: filter(and(eq('your-attribute', 'your-value'))), }) ``` ## Recommended request flow The end-to-end timeline: **1. Header submit** Shopper presses enter. Create a `search` controller and await `search.prepare()` before navigating to `/search?q=...`. Cross-page reuse requires `storage` in `createSDK()`. The results page resolves the prepared `search_id` itself. **2. Results page render** Render the sort dropdown and empty facet groups from `sdk.sortOrders()` and `sdk.facets()`, including the active sort/filter state from the URL. **3. Get results** Page JS calls `search.get({ sort, filterGroup, pagination })`. The `query` is fixed when the controller is created. The SDK resolves the prepared `search_id` automatically. The subscriber renders the grid, facets, and pagination as soon as data lands. **4. Interaction** On sort change or filter toggle, call `search.get({ ... })` with just the changed fields. Mirror the state to the URL via `history.replaceState`. ## Why the SDK over Fetch | Concern | Fetch version | SDK version | | :- | :- | :- | | Debounced autocomplete | DIY debounce + `AbortController` | `createDebounce()` + `autocomplete()` | | `search_id` lifecycle | `sessionStorage` plumbing across pages | Handled internally by `prepare()`/`get()`; set `storage` for cross-page reuse | | Re-renders | DIY DOM updates | `subscribe()` callback | | Sticky options | Track manually | Shallow-merged by `get()` | | Click feedback / attribution | Read `attributionToken`, POST to feedback endpoint | Storefront Pixel handles standard themes; SDK exposes `attributionToken` on results for custom flows | | Errors | Hand `try/catch` | `{ data, error }` with `ApiError` for HTTP failures | ## Troubleshooting **Suggestions show but redirects do not fire.** The Storefront Pixel performs redirects, so confirm the Layers app embed is enabled and that the configured redirect term matches the typed query. On a headless storefront without the embed, your code must follow `data._meta.redirect.url` itself. **`get()` is slow on the results page.** Prepare was not called, or the cache has expired. The SDK falls back to normal processing. Confirm prepare runs before navigation. **Filters do not apply.** Attribute codes in `filterGroup` must exactly match the codes configured as facets in Layers. Fetch `sdk.facets()` to verify the codes. ## See also * [Implementing search in Liquid (Fetch)](/developers/implementing-search-in-liquid) * [Rendering facets with the SDK](/developers/rendering-facets-with-the-sdk) * [Rendering sort orders with the SDK](/developers/rendering-sort-orders-with-the-sdk) * [Rendering blocks with the SDK](/developers/rendering-blocks-with-the-sdk) * [Client methods](/sdk/api-reference/client-methods) * [Filtering](/sdk/api-reference/filtering) # Liquid integration Source: https://docs.uselayers.com/developers/liquid-integration How to access Layers metaobjects, metafields, and configuration values directly in your Shopify theme using Liquid templates and snippet helpers. ## Overview Layers metaobjects and metafields are accessible in your Shopify theme via Liquid. Use them to render the structure of custom sort order selectors, facet filters, and recommendation blocks (names, codes, and settings) server-side, without JavaScript. The live data that fills them, such as facet values and counts or the products in a recommendation block, comes from the Layers APIs, so you still need JavaScript (or the [SDK](/sdk/overview)) to fetch it. All Layers metaobjects have public storefront access, so they are available in any Liquid template. ## Namespace reference Layers uses the following namespaces for metaobjects: | Resource | Namespace | | :- | :- | | Sort Orders | `app--278936322049--sort_order` | | Facets | `app--278936322049--facet` | | Blocks | `app--278936322049--block` | | Collection Metafields | `layers` | | App Installation Metafields | `layers` | ## Accessing sort orders Sort order metaobjects represent the sort orders configured in your Layers dashboard. ### Basic access ```liquid theme={null} {% assign layers_sort_metaobjects = shop.metaobjects['app--278936322049--sort_order'] %} ``` ### Available fields | Field | Type | Description | | :- | :- | :- | | name | string | Display name of the sort order | | code | string | Unique code identifier | | scope | array | Contexts where available (search, collection) | | order | integer | Display order | ### Filtering by scope Display only sort orders available for specific contexts: ```liquid theme={null} {% assign layers_sort_metaobjects = shop.metaobjects['app--278936322049--sort_order'] %} ``` ### Ordering by display order ```liquid theme={null} {% assign layers_sort_metaobjects = shop.metaobjects['app--278936322049--sort_order'] %} {% assign sorted_orders = layers_sort_metaobjects | sort: 'order' %}
      {% for sort_order in sorted_orders %}
    • {{ sort_order.name.value }}
    • {% endfor %}
    ``` ### Using collection default sort order Access the default sort order assigned to a collection: ```liquid theme={null} {% assign default_sort_code = nil %} {% if collection.metafields.layers.default_sort_order %} {% assign default_sort_code = collection.metafields.layers.default_sort_order.value.code.value %} {% endif %} {% assign layers_sort_metaobjects = shop.metaobjects['app--278936322049--sort_order'] %} ``` ## Accessing facets Facet metaobjects represent filterable attributes configured in Layers. ### Basic access ```liquid theme={null} {% assign layers_facet_metaobjects = shop.metaobjects['app--278936322049--facet'] %}
    {% for facet in layers_facet_metaobjects %}

    {{ facet.name.value }}

    {% endfor %}
    ``` ### Available fields | Field | Type | Description | | :- | :- | :- | | name | string | Display name of the facet | | code | string | Unique code identifier | ### Building a facet filter UI ```liquid theme={null} {% assign layers_facet_metaobjects = shop.metaobjects['app--278936322049--facet'] %} ``` > [!NOTE] > > Facet metaobjects only provide the facet configuration (name and code). Actual facet values, counts, and numeric ranges must be fetched with JavaScript from the [Facets API](/api-reference/facets). Browse responses include the same `facets` and `facetRanges` fields. See [Rendering facets in Liquid](/developers/rendering-facets-in-liquid). ## Accessing blocks Block metaobjects represent recommendation blocks configured in Layers. > [!WARNING] > > The metaobject's system handle is not the block ID. Layers generates handles in the form `layers-` (for example, `layers-01j8abcd1234xyz`), and the block ID itself is not exposed as a field. To get the ID the [Blocks API](/api-reference/blocks) expects, strip the prefix and uppercase the remainder: > > ```liquid theme={null} > {{ block.system.handle | remove_first: 'layers-' | upcase }} > ``` > > Passing the raw `system.handle` as the `blockId` returns no products. The handle never matches a block ID, so the request silently misses the block instead of surfacing an error. ### Basic access ```liquid theme={null} {% assign layers_blocks = shop.metaobjects['app--278936322049--block'] %} {% for block in layers_blocks %}

    {{ block.title.value }}

    {% endfor %} ``` ### Available fields | Field | Type | Description | | :- | :- | :- | | label | string | Display label (formatted as "Title - AnchorType") | | title | string | Block title | | anchor\_type | string | Anchor type (product, collection, cart, none) | ### Filtering by anchor type Display blocks based on the current page context: ```liquid theme={null} {% assign layers_blocks = shop.metaobjects['app--278936322049--block'] %} {% if template == 'collection' %} {% for block in layers_blocks %} {% if block.anchor_type.value == 'collection' %}

    {{ block.title.value }}

    {% endif %} {% endfor %} {% endif %} {% if template == 'product' %} {% for block in layers_blocks %} {% if block.anchor_type.value == 'product' %}

    {{ block.title.value }}

    {% endif %} {% endfor %} {% endif %} ``` ## Accessing app configuration The Layers theme app embed writes your storefront configuration into every page as a JSON script tag in the ``. This tag is the recommended source, so you don't need to read metafields to get it: ```liquid theme={null} ``` Parse it from JavaScript: ```js theme={null} const layersConfig = JSON.parse( document.getElementById('layers-config').textContent, ) // layersConfig.apiToken — analytics tracking token // layersConfig.storefrontApiToken — storefront token ``` ### Available fields | Field | Type | Description | `createSDK()` option | | :- | :- | :- | :- | | apiToken | string | Analytics tracking token | `trackingToken` | | storefrontApiToken | string | Storefront token | `storefrontAccessToken` | | integrations | object | Enabled integrations and their configurations | Not passed to `createSDK()` | | sessionCookieFallbacks | array | Cookie names for session identification | Not passed to `createSDK()` | ### Reading the tokens in Liquid If you need the tokens server-side in Liquid instead, Layers also writes them to shop metafields: | Value | Liquid path | | :- | :- | | Full configuration (same JSON as the tag) | `shop.metafields.layers.embed_settings.value` | | Storefront token | `shop.metafields.commerce_blocks.layers_token` | | Analytics tracking token | `shop.metafields.commerce_blocks.layers_tracking_token` | If these metafields are empty on an older installation, trigger a resync from **Settings → Integrations** in the Layers dashboard. See [Collection & app metafields](/shopify-integration/metaobjects-metafields/app-metafields). ## Best practices ### Performance * Cache metaobject queries when possible using Liquid variables * Minimize the number of metaobject iterations in your templates * Use JavaScript to fetch dynamic data (facet values, recommendations) rather than making multiple Liquid queries ### Error handling Always check if metaobjects exist before accessing them: ```liquid theme={null} {% if shop.metaobjects['app--278936322049--sort_order'] %} {% assign layers_sort_metaobjects = shop.metaobjects['app--278936322049--sort_order'] %} {% endif %} ``` ### Namespace consistency Use the exact namespace values provided in this documentation. The namespace includes the Layers app ID and must match exactly: ```liquid theme={null} {% comment %} Correct {% endcomment %} {% assign layers_sort_metaobjects = shop.metaobjects['app--278936322049--sort_order'] %} {% comment %} Incorrect - missing the app ID prefix {% endcomment %} {% assign layers_sort_metaobjects = shop.metaobjects['sort_order'] %} ``` > [!NOTE] > > Always use the full namespace (`app--278936322049--`) when accessing Layers metaobjects via Liquid. Short forms or aliases will not resolve. ## Troubleshooting ### Metaobjects not appearing If metaobjects are not accessible in Liquid: 1. Verify the sort order has **Enable as Storefront Sort** enabled in Layers 2. Verify the facet has **Enable as Storefront Facet** enabled in Layers 3. Check that the metaobject was created (visible in Shopify admin under Content → Metaobjects) 4. Ensure you're using the correct namespace ### Empty values If metaobject fields return empty values: 1. Verify the field exists in the Layers dashboard 2. Check that the metaobject has been synced (may take a few seconds after creation) 3. Use `.value` to access field values: `{{ sort_order.name.value }}` ### Collection default sort order not found If the collection's default sort order is not accessible: 1. Verify a default sort order is assigned in the Shopify admin (Products → Collections → \[Collection] → Metafields) or on the collection's page in the Layers dashboard 2. Check that the referenced sort order still exists in Layers 3. Ensure you're using the correct metafield namespace ## See also * [Metaobjects & Metafields](/shopify-integration/metaobjects-metafields) — Complete reference for Layers metaobjects * [SDK Reference](/sdk/overview) — JavaScript SDK for Layers integration * [Browse API](/api-reference/browse) — Fetch products with sorting and filtering * [Blocks API](/api-reference/blocks) — Fetch recommendation blocks # MCP servers Source: https://docs.uselayers.com/developers/mcp-servers Connect AI assistants like Claude or ChatGPT to Layers with Model Context Protocol servers for store management and storefront search. Layers exposes two [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers that let AI assistants interact directly with your stores. Use them to manage merchandising, search tuning, catalog operations, and storefront queries through any MCP-compatible client. | Server | Endpoint | Auth | Purpose | | - | - | - | - | | Layers MCP server | `https://app.uselayers.com/mcp/v1` | OAuth (`mcp:use` scope) | Full store management: catalog, merchandising, search tuning, analytics, and more | | Storefront MCP server | `https://app.uselayers.com/mcp/storefront/v1` | Storefront API token | Read-only storefront operations: search, browse, recommendations | ## Browser-local WebMCP controls The Layers dashboard also exposes browser-local WebMCP controls when you are signed in and using a browser that supports `navigator.modelContext`. These tools act on the active dashboard page through its existing UI handlers. They are separate from the remote Layers MCP server and Storefront MCP server, and do not call their endpoints. Open the relevant conditions builder or picker in the dashboard before listing controls. The tools only expose builders and pickers that are currently mounted and visible. For conditions builders: * Use `layers_list_condition_builders` to find open builders, then `layers_conditions_get` to read the current query and the fields, operators, value types, and choices allowed in that builder. * Use `layers_conditions_set` with the builder id, a complete replacement query, and `expected_query` from the latest read. Nested `and`, `or`, and `not` conditions are supported where the builder allows them. Values must be literal; field-sourced values are not supported. * Setting conditions uses the existing UI handler and may sync the dashboard draft, but never submits or publishes it. If the builder is stale or locked, re-read it or unlock it before trying again. For nested pickers: * Use `layers_list_nested_comboboxes` to find open pickers and `layers_combobox_get_options` to read their choices. Option lookup supports search, group, offset, and limit; the default limit is 50 and the maximum is 100. * Use `layers_combobox_select` with the picker id and an exact option value returned by the options tool, not its label. Disabled options are rejected. * If a picker id is stale or the picker is closed, open the relevant control and list the pickers again. Selection does not save or publish the dashboard. ## Layers MCP server The main MCP server exposes tools for managing your Layers stores. It uses OAuth authentication and requires the `mcp:use` scope. ### Connecting The official Layers connector is available in the [Claude directory](https://claude.ai/directory/connectors/uselayers). Add it from **Settings > Connectors** in Claude, then authorize Layers when prompted. You can also open **Install MCP** from your profile menu in the top-right corner of the Layers dashboard. Pick **Claude**, **Claude Code**, **ChatGPT**, or **Generic (any MCP client)** to get the server URL, setup command, or JSON config to copy. If you are using a different MCP client, configure it with the following endpoint: ``` https://app.uselayers.com/mcp/v1 ``` When you connect for the first time, you're redirected to the Layers dashboard to authorize the connection. After authorization, your MCP client stores the OAuth tokens and reconnects automatically. MCP connections are scoped to specific stores **and** specific permissions. On the authorization screen, you select which stores the connection can access and which of your own permissions it may use. A connection can never exceed your own access. If your access is later reduced, the connection's access is reduced immediately to match. Because connections are store-scoped, `store-list` returns only the stores granted to the connection. Each store in `store-list` and `store-details` includes the `permissions` the connection was granted, so an assistant can check what it may do before calling a tool. If a tool is called for a store that wasn't granted the permission it needs, the tool returns a permission error. If a tool is called with a store identifier that doesn't exist, the tool returns a not-found error with up to three near matches drawn from the connection's accessible stores. This distinguishes a typo (fix the slug and retry) from a store that exists but wasn't granted to the connection (ask the connection owner to grant it). The `store` argument accepts a store's UUID, slug, or primary domain (exact match), and also matches on the display name after ignoring case and punctuation, so `Acme Outfitters`, `acme-outfitters`, and `acmeoutfitters` all resolve to the same store. When a name matches more than one accessible store, the tool returns a 422 that names the conflicting slugs so the caller can retry with an exact identifier. ### Granting access to future stores By default, a connection only covers the stores you select on the authorization screen. Turn on **Include future stores** under the store picker to automatically grant the connection access to stores you gain access to after consenting. Use it for a personal assistant connection you want to keep in sync with your account instead of re-authorizing every time you're added to a new store. When the switch is on, pick a permission preset for future stores: | Preset | Permissions granted on each future store | | - | - | | Read-only | View-level permissions only | | Standard | View-level permissions plus merchandising edits | | Full | Every permission you hold on the store | Behavior to know: * "Future" means stores you gain access to after consenting. Stores you could already access but left unselected stay excluded and are never granted automatically. * Grants still never exceed your own access. When you gain a new store, the connection receives the preset's permissions intersected with the permissions you actually hold on that store. * New grants take effect on the connection's next MCP request and appear in the store's **App Connections** table like any other grant. * Re-authorizing the same app replaces the future-store setting along with the store grants. The most recent consent wins. * [Revoking the connection](/help/configuration/manage-api-access#revoke-an-app-connection) for a store permanently excludes that store. Layers won't re-grant it automatically, even if you still have access. ### Available tools Most resources use a `*-manage` tool for actions such as `list`, `create`, `update`, and `delete`. Some resources use separate list and collaborative editing tools instead. > [accordion] Store > > | Tool | Description | > | - | - | > | `store-list` | List all stores you have access to. Each store includes the `permissions` granted to the connection (`null` for dashboard sessions and admin contexts, which have no per-connection grant) | > | `store-details` | Get detailed information about a store, including resource counts and the connection's granted `permissions` | > | `store-search-configuration` | Get or update the dashboard-visible search configuration — brand and search prompts, image-search mode, autocomplete region mode (`pooled` or `per_region`), excluded tags, text/image result balance, ranking signal weights, reranking strength, and diversity strength. `get` returns the effective values search actually runs, so a store that has never overridden its weights sees the platform defaults for `ranking_weights` and `ranking_sub_weights` rather than `null` | > | `store-settings-manage` | Read or update crawler signature settings, Shopify sync preferences, inventory location scope, the app sales channel, and Shopify Markets behavior. Requires `store.configure`. See [Managing store settings](#managing-store-settings) | > | `store-operational-status` | Inspect permission failures, sync blockers, recent tasks, a `search_documents` rollup with `ready`, `pending`, and `needs_attention` counts across the catalog, and a `facets` rollup with each facet's build phase, last refresh time, and any facets currently withheld from the API with the reason | > | `store-maintenance` | Inspect maintenance status. Admin operators can also run maintenance actions such as feature-flag updates, cache purges, and search-index rebuilds | > | `store-evaluations` | List, inspect, compare, start, and rerun search-quality evaluation runs | > | `store-dimensions` | List the dimensions a store can be segmented by and the contextual fields conditions can target, with coverage (percentage of events, unique values, last seen). Pass `dimension` to see the values observed for one dimension. Use it before writing conditions for blocks, merchandising rules, request transforms, or sort orders. See [Discovering targetable fields](#discovering-targetable-fields) | > | `demo-profiles-manage` | List, get, create, update, or delete store-scoped demo shopper profiles. Use the returned `id` as `demo_profile_id` in `blocks-preview` to preview how a block renders for a given persona. Writes require the `store.configure` grant | > [accordion] Customers > > | Tool | Description | > | - | - | > | `audiences-manage` | List, inspect, create, or delete saved audiences; discover supported fields with `attributes`; estimate recent traffic coverage with `estimate`. Edit existing audiences through the shared editor with `resource_type: "audience"`. See [Managing audiences](#managing-audiences) | > [accordion] Catalog > > | Tool | Description | > | - | - | > | `query_catalog` | Query catalog listings for products, variants, or collections with filtering, sorting, field selection, and pagination. By default, product and variant results include both published and unpublished catalog records, matching the dashboard catalog. Pass explicit boolean filters `filter.published_on_web` or `filter.published_on_app` to restrict results by publication on those channels; product and variant rows include both fields. Returns compact rows plus resource URIs for deeper reads. Id filters accept a single id or a comma-separated list of ids — `id` on products, and `id` and `product_id` on variants. Errors for an unsupported resource list the valid resources | > | `category-mapping-manage` | List product-type category mappings, or set a manual category override for a product type or a single product. Setting the category to `null` marks the item as intentionally unmappable | > [accordion] Diagnostics > > | Tool | Description | > | - | - | > | `product-search-diagnostics` | Inspect what content reaches a product's search document, what was excluded and why, and the current indexing readiness state. Resolves a product by numeric id, Shopify gid, or handle. Also accepts an optional `collection` and `facet_codes` to explain which requested facets the API serves and which it drops. Use it when search isn't finding a product or when verifying content-selection behavior | > [accordion] Search > > | Tool | Description | > | - | - | > | `search-semantic` | Run the full semantic storefront search pipeline with query understanding, typo tolerance, query expansion, and intent detection. Accepts an optional `filter_group` (same shape as the browse API), `facets`, a `debug` flag for scoring diagnostics, and `excludeRuleIds` to hold specific ranking rules out of the search. Its default `view` is `compact`, which returns `id`, `title`, `handle`, `vendor`, `product_type`, `available`, and `price_range`, plus requested attributes; facets include up to 50 values each by default. Use `view: "facets"` for totals and facets without results, or `view: "full"` for complete result documents and facet values. `fields` and `facet_values_limit` customize compact responses; `per_page` defaults to 10. See [Testing ranking rule impact](#testing-ranking-rule-impact). Empty results with a filter applied may mean the product wasn't recalled or was filtered out. Follow up with `product-search-diagnostics` | > | `browse` | Browse products using the storefront browse pipeline, including merchandising rules, sort orders, filtering, and facets. Returns compact product summaries and up to 50 values per facet by default; use `view: "facets"` for counts without products or `view: "full"` for complete documents. Set `collection_handle` to `all` to browse the whole catalog when the store has no synced `all` collection. `per_page` defaults to 25 (maximum 100). See [Controlling browse response size](#controlling-browse-response-size) and [Browsing without a sort order](#browsing-without-a-sort-order) | > | `search-autocomplete` | Get autocomplete suggestions for a search query | > | `search-batch` | Run deterministic semantic searches asynchronously across up to 200 queries and up to 3 search variants. Actions are `start`, `get`, `list`, and `cancel`. See [Batch search testing](#batch-search-testing) | > [accordion] Attributes > > | Tool | Description | > | - | - | > | `attributes-manage` | List attributes, fetch selectable values for a single attribute, read one attribute in full, edit an existing attribute, or create, publish, and delete [computed attributes](/platform/attributes/calculated-attributes). Actions include `list`, `values`, `get`, `create`, `update`, `delete`, `publish`, `draft_update`, `draft_clear`, and `preview`. `list` accepts `usable_for` (`attributes` or `facets`), and accepts `search` as an alias for the prefix-match `query` filter. `code` aliases `attribute_code` on actions that select an existing attribute. Check existing attributes and sort keys before creating a computed attribute, and test its input query against real products with `preview`; confirm with the user before `publish`, which recomputes every product and goes live immediately. Supports `keyword_search_weight` (1–10) and a `classes` array (`categorical`, `feature`, `price`, `identifier`). See [Creating and publishing computed attributes](#creating-and-publishing-computed-attributes) | > | `facet-values-manage` | List facet-eligible attributes, read a single facet's sorting, grouping, and hidden-value config, sample the products behind facet values, or upsert values into groups inside the collaborative draft. Actions are `list`, `samples`, and `upsert`. On `list`, `attribute_code` and `code` are aliases for `attribute`. Use the [collaborative editor tools](#collaborative-editor) and `request_publish` to request review of draft changes. Whole-list writes use RFC 6902 patches; use `upsert` for row-level group placement. See [Sampling and grouping facet values](#sampling-and-grouping-facet-values) | > [accordion] Search tuning > > | Tool | Description | > | - | - | > | `request-transforms-manage` | List, create, update, or delete request transforms | > | `semantic-redirects-manage` | List, create, update, or delete semantic redirects | > | `ranking-rules-manage` | List, create, or delete ranking rules. To edit an existing rule or change its enabled status, use the [collaborative editor](#collaborative-editor) with `resource_type: "ranking_rule"`; direct `update` and `toggle_status` calls no longer save changes. Rules can apply to all searches or use a conditional scope. Conditional rules use `targeting_conditions` with a `combinator` and nested `rules`; supported conditions include `request.query`, `request.applied_filters`, `request.sort_order_code`, and `context.*`. Do not use anchor fields in ranking-rule conditions. Supports `boost`, `bury`, `pin`, `sort`, `filter`, `diversity`, and `weights` action types. `boost` and `bury` require a `magnitude` between `0.01` and `0.50`; values outside that range are rejected rather than clamped. A `weights` action carries the full five-signal pie (each group `0.01`–`0.80`, summing to `1.0`) and optional per-group `sub_weights` ratios that replace the store's [Signal Weights](/platform/ranking-relevancy#signal-groups) for matched queries. `weights` is accepted only when every possible matching OR branch requires a query condition, and only one `weights` action is allowed per rule. `filter` adds hidden eligibility filters that combine with system filters using AND; `diversity` configures result spreading | > | `query-dimensions-manage` | List, inspect, create, update, delete, or recheck query dimensions and replace their keyword rules. See [Managing query dimensions](#managing-query-dimensions) | > | `query-expansion-examples-manage` | List, create, update, or delete curated query expansion examples | > | `query-expansions-manage` | List, inspect, update, delete, approve, or reject the live query expansions applied at search time. To add new expansions, create curated examples with `query-expansion-examples-manage`; they sync into live expansions | > | `intent-modifiers-manage` | List, inspect, create, update, delete, suppress, or unsuppress intent modifiers: query-scoped overrides that promote, demote, filter, or sort results for matching searches | > | `query-clusters-manage` | List, inspect, and curate query clusters (label, suppress, set the diversity axis, delete, or recompute), and add, move, or remove the queries in a cluster. Layers periodically re-runs clustering, so a later pass may recompute manual membership edits | > [accordion] Merchandising > > | Tool | Description | > | - | - | > | `merchandising-rules-manage` | List or create merchandising rules. Edit existing rules through the [collaborative editor tools](#collaborative-editor) using RFC 6902 patches | > | `banner-types-manage` | List, inspect, create, update, or delete custom banner types, or discover supported field types and validations with `taxonomy`. Requires `store.configure`. See [Managing banner types](#managing-banner-types) | > | `hidden-products-manage` | List, create, update, or delete [hidden product](/platform/hidden-products) rules. Equality accepts `equals` as an alias for `eq`; `not_equals`, `notEquals`, and `notEq` alias `neq`. Validation errors list supported operators, resources, or surfaces for the rejected value | > | `blocks-catalog` | Read-only catalog of block anchors, strategy types and keys, readiness, configuration schemas, rule vocabulary, and fallback modes. The bounded `detail: "summary"` response is the default; use `detail: "full"` for complete schemas, or filter by anchor, strategy type, or strategy key to narrow the response | > | `blocks-preview` | Preview saved or inline blocks with storefront-shaped context, shopper filters, exclusions, sample anchors, or demo profile context. Pass `explain: true` to receive an execution trace | > | `blocks-manage` | List, create, update, delete, publish, unpublish, duplicate, or bulk manage recommendation blocks with strategies, safeguards, fallback chains, and seven-day performance counters. `bulk_duplicate` creates one copy per requested entry and reports unknown ids in `not_found_ids` | > [accordion] Sort orders > > | Tool | Description | > | - | - | > | `sort-orders-manage` | List or create sort orders, or set a collection's default with `action: "set_collection_default"` and `collection_handle` plus a browsable, non-variant `sort_order_code`; pass `null` or omit the code to clear the collection default and use the store default. The default takes effect immediately; Layers queues the collection metafield sync. Before creating a sort, list existing ones with `include_sorting_attributes: true` and reuse a match rather than duplicating it. Prefer a secondary sort key for null values over a computed fallback attribute. Edit existing sort orders through the [collaborative editor tools](#collaborative-editor) using RFC 6902 patches | > | `sort-orders-preview` | Preview products sorted by a specific sort order, optionally within a collection. Pass `sort_order_codes` (up to 3) to compare sort orders with aligned rankings and rank deltas. Pass `explain: true` for per-product ranking explanations, or `explain_product` to explain a single product's position | > [accordion] Collaborative editor > > | Tool | Description | > | - | - | > | `set_presence` | Announce, refresh, or release an agent's presence on a shared document and read its current revision | > | `validate_document` | Validate the current document or proposed RFC 6902 patches without applying changes; an active `presence_id` can identify the resource | > | `apply_patch` | Apply an atomic RFC 6902 JSON Patch to a shared document using a presence session and observed revision | > | `request_publish` | Request human review for a merchandising rule, sort order, recommendation block, or facet values, or publish immediately when the user explicitly asks. Returns a `publish_request_id` and a dashboard review URL | > | `check_publish_request` | Check whether a publish request for any supported resource has been published, rejected, superseded, or expired | > [accordion] Products > > | Tool | Description | > | - | - | > | `product-families` | List, inspect, create, update, publish/unpublish, or delete manual product families. Use `get_config` and `update_config` to read or change which attribute codes and metafield namespace/key pairs generate automatic families. Write actions on non-manual families return 403 and name the actual source (for example, `Attribute-sourced families are read-only`) | > | `product-sequences` | List, inspect, create, update, publish/unpublish, delete, configure, or re-evaluate ordered product sequence groups. Use `get_config` and `update_config` to read or change sequence metafields, global sequence conditions, and AI ordering settings; call `reevaluate` to re-run condition evaluation for one group or across every sequence. Payloads include `source`, `is_published`, `is_active`, `activation_status`, and `inactive_reason` — see [Publishing product sequences](#publishing-product-sequences). Write actions on non-manual sequences return 403 and name the actual source | > | `variant-breakouts` | List, inspect, create, update, enable, disable, or delete option-based variant breakout rules. Accepts an optional `exclusion_conditions` group (flat `variants.*` or `variant_metafields.*` rules with `and`/`or`) to keep matching variants from breaking out, and an optional `excluded_collection_handles` list of collections the breakout never runs on (a handle cannot appear in both `target_collection_handles` and the exclusion list) | > [accordion] Analytics (LayersQL) > > | Tool | Description | > | - | - | > | `layersql-schema` | Describe and search the LayersQL schema: datasets, allowed metrics, dimensions, and product attributes. Called without `dataset`, it also returns a compact syntax cheat-sheet (clause order, operators, two examples). Pass `include_reference: true` to include the full LayersQL syntax reference and example queries. Pass an optional `store` to cross-link each dimension to that store's coverage and the contextual field conditions can target — see [Discovering targetable fields](#discovering-targetable-fields) | > | `layersql-validate-query` | Fast parser and semantic validation for a LayersQL query. Requires a `store`. Checks that every metric and dimension exists on the dataset and returns validation errors (listing the available names) or the parsed structure | > | `layersql-query` | Run a read-only LayersQL query and return rows. Queries run the same semantic validation as `layersql-validate-query` first, so a query naming an unknown metric or dimension fails with the available names and is never executed. Use `columns` to keep selected result columns. The default limit is 50 rows, with a maximum of 500. Capped responses include `truncated` and `next_offset`. When the query includes a [`VISUALIZE`](/platform/layersql/syntax#visualize-optional) clause, the response also returns a `visualization` chart config (`type`, `x`, `series`, `limit`, `target`, `max`, `x_buckets`) that an assistant can use to draw the result. Runs synchronously by default. Pass `execution: "async"` to queue the query and read the result with `tasks`, see [Asynchronous tasks](#asynchronous-tasks) | > | `tasks` | Check, read, list, and cancel asynchronous tool runs. Actions are `get`, `result`, `list`, and `cancel`. See [Asynchronous tasks](#asynchronous-tasks) | > | `analytics-manage` | List, get, create, update, or delete saved analytics reports and dashboards. A report is a saved LayersQL query (include a `VISUALIZE` clause to set its default chart); a dashboard is an ordered list of cards, each referencing an existing report by `report_id` or creating one inline via `query` and `name`. Card layout is computed from each card's `width` (`full`, `half`, or `third`) on a 12-column grid, so callers never send raw coordinates. `get`, `create`, and `update` return current rows, the `visualization` chart config, and a `url` deeplink into the Layers dashboard. Create, update, and delete actions require the [analytics edit](/help/configuration/manage-api-access) permission — see [Managing saved reports and dashboards](#managing-saved-reports-and-dashboards) | > [accordion] Knowledge > > | Tool | Description | > | - | - | > | `knowledge-manage` | Search, list, get, propose, create, update, approve, or archive store knowledge documents. Knowledge documents are Markdown with YAML frontmatter and live in `pending`, `active`, or `archived` states. Search is powered by Cloudflare AI Search over the active set, and accepts an optional `scope` metadata filter | > [accordion] Documentation > > | Tool | Description | > | - | - | > | `docs-search` | Search the Layers documentation | > [accordion] Feedback > > | Tool | Description | > | - | - | > | `mcp-feedback` | Send feedback about the MCP itself — friction points, tooling gaps, bugs, or suggestions — directly to the Layers team. Available to admin MCP connections | ### Submitting feedback about MCP tooling Admin MCP connections can call `mcp-feedback` to report friction with the MCP itself. Use it when an assistant hits a rough edge you want the platform to fix. Examples include a missing capability, a schema field that isn't exposed, an action that takes too many calls, or a tool description that led an agent astray. The tool accepts a short set of fields: | Field | Required | Description | | - | - | - | | `message` | Yes | Detailed description of the friction point, gap, or suggestion. Be specific about what you were trying to do and what went wrong or is missing | | `category` | Yes | One of `friction`, `gap`, `bug`, or `other` | | `tool` | No | Name of the MCP tool the feedback relates to, as it appears in the tool list (for example, `store-maintenance`) | | `severity` | No | `low`, `medium`, or `high`. Defaults to `low` | | `store` | No | Store slug or domain for context | Example call: ```json theme={null} { "tool": "mcp-feedback", "arguments": { "message": "blocks-manage doesn't expose the fallback chain order, so I can't reorder fallbacks without recreating the block.", "category": "gap", "tool": "blocks-manage", "severity": "medium", "store": "my-store" } } ``` The response confirms the submission: ```json theme={null} { "sent": true, "delivered": true } ``` `delivered` is `false` when feedback routing isn't configured for the environment. The submission is still recorded. ### Usage pattern **1. List your stores** Call `store-list` to see all stores you have access to. Note the store slug for each store you want to work with. **2. Pass the store slug** Include the store slug in all subsequent tool calls. For example, if your store is `my-store.myshopify.com`, the slug is `my-store`. **3. Use manage tools to make changes** Tools ending in `-manage` accept an `action` parameter, commonly `list`, `create`, `update`, or `delete`, plus tool-specific actions such as `toggle_status` or bulk actions like `bulk_publish`. Read-only actions like `list` are safe to call freely. ### Write payload shapes `*-manage` tools declare their writable fields inside a nested `data` object, but they accept the same fields at the top level of the arguments. Both of these calls apply the same update: ```json theme={null} { "store": "my-store", "action": "update", "rule_id": "01JQK5W3N8V7C2RY4F6H9M0TBD", "data": { "enabled": false } } ``` ```json theme={null} { "store": "my-store", "action": "update", "rule_id": "01JQK5W3N8V7C2RY4F6H9M0TBD", "enabled": false } ``` Write calls fail loudly instead of silently succeeding with no effect: * Arguments the tool doesn't recognize return a validation error that names each unsupported argument and lists the fields the tool accepts. A misspelled field can't be dropped silently. * A `create` or `update` call whose payload resolves to nothing returns a validation error rather than reporting `success: true` with an unchanged record. * Invalid field values return a readable `Validation failed: ...` error naming the field. If an assistant reports a successful update but nothing changed, check the tool response. A genuine write returns the refreshed record. A rejected write returns `success: false` with the validation message. ### Smaller MCP responses List actions on updated manage tools accept `fields` to keep only selected keys on each item. Identity and structure keys such as `id`, `code`, and `children` remain in the response. Omit `fields` to return the full item. If you request a key that an item does not contain, the response identifies it in `unknown_fields`. Mutation actions return a compact confirmation with `success`, `action`, an identifier such as `id`, `changed`, and an optional `message`. Toggle and status actions also include the resulting state. Pass `verbose: true` or `include=resource` to include the full stored record in the response. ### Discovering targetable fields `store-dimensions` is the source of truth for what a store's contextual conditions can target. It returns two lists in one response, both scoped to the store you pass: * **`dimensions`** — every dimension Layers records for the store, with `source` (`built_in`, `analytics`, or `custom`), `value_type`, `coverage_percentage`, `unique_values`, and `last_seen_at`. These are the codes accepted after `SEGMENT BY` in LayersQL. * **`contextual_fields`**: the `context.*` field names conditions accept in `blocks-manage`, `request-transforms-manage`, sort orders, and merchandising rules edited through the collaborative editor. Each entry carries a `label`, `group`, `type`, allowed `operators`, and the same coverage stats. Store-specific labels from the [Dimensions page](/help/configuration/manage-dimensions) flow through as `label` and `description`. Product sequences use product attributes instead of shopper context. The contextual fields from `store-dimensions` are not a sequence condition vocabulary. See [Product sequence conditions](#product-sequence-conditions). Filter with `search` (matches name, label, or description) or `group` (for example, `Geography`, `Marketing`, `Custom`), and paginate with `page` and `per_page`. Pass `dimension` to fetch the values observed for a single dimension or field instead of the listing; the tool returns up to `values_limit` samples (default 25, max 100) drawn from real traffic. ```json theme={null} { "tool": "store-dimensions", "arguments": { "store": "my-store", "group": "Location" } } ``` To sample values for one field before writing a condition: ```json theme={null} { "tool": "store-dimensions", "arguments": { "store": "my-store", "dimension": "context.geo.country" } } ``` Custom fields your storefront sends under `custom` on the [contextual payload](/engine/contextual-information/data-structure#custom-context) appear here automatically once Layers has seen them in traffic. There is no registration step. See [Custom context fields](/platform/merchandising/contextual-conditions#custom-context-fields) for the discovery rules. `layersql-schema` accepts the same `store` argument. When present, each dimension in the response gains a `store` block with the matching store dimension code, its coverage stats, and the `context.*` field name conditions can target. Use it to move from an analytics query to a targeting condition without a second lookup. #### Write validation Every write tool that accepts a conditions payload validates leaves against the same registry. Layers rejects any condition that names an unknown field, an unknown operator, or an operator that doesn't fit the field's type. The error includes the nearest valid field name and points back to `store-dimensions`: ``` rules.0.conditions.rules.0 targets an unknown field "context.geo.provnce". Did you mean "context.geo.province"? Call store-dimensions to list the fields this store can target. ``` Store-specific fields (custom parameters, merchant-renamed dimensions) are not enumerated in `tools/list`, so calling `store-dimensions` for the target store is the reliable way to see the current vocabulary before a write. ### Managing query dimensions Use `query-dimensions-manage` to label queries with values from a product attribute and refine their rules. Read actions require `ranking-rules.view`; mutations require `ranking-rules.edit`. * `list` lists definitions. `get` requires `code` and returns the available labels, keyword rules, check status, agreement, grouped top-search preview, and saved corrections. * `create` takes `data` with `code`, `name`, `attribute_code`, and `instructions`; it can also take `included_values`. An attribute may have more than 150 distinct values, but a dimension can include at most 150 selected labels. Omit `included_values` to include all attribute values. `update` takes `code` and `data`; the code is immutable. An omitted `included_values` retains the current selection unless `attribute_code` changes, in which case the selection resets to all values. * Creating a dimension or changing its instructions, attribute, or included values starts background rule generation and checking. A name-only update does not. Use `get` to follow progress. Rechecking compares rules without replacing corrections. * `update_rules` takes `code` and the complete `rules` list, replacing the entire list, including corrections. Preserve every `source: "correction"` entry when sending an update, or those corrections will be lost. Each rule has `match`, `kind` (`phrase` or `word_pattern`), `labels`, and `defer`. Corrections use `kind: "phrase"` with the exact search words and must not defer. Empty labels explicitly mean no signal. Inspect `dropped` in the response for rejected rules and their reasons. Valid rules save and are checked without regeneration. * `recheck` compares current rules again. Set `regenerate: true` to regenerate generated and manually edited rules; this replaces those rules but preserves corrections. A normal recheck does not overwrite corrections. * `delete` requires `code` and is blocked while a ranking rule references the dimension, including unpublished rules. Ranking-rule conditions can target `request.query_dimension.`. A missing verdict does not count as an empty label or satisfy a no-signal condition. For a `boost` or `bury` action using the query's labels, set `filter.value_source` to `query_dimension`, `filter.value` to the dimension code, `filter.operator` to `in`, and `filter.property` to that dimension's `attribute_code`. Empty or unresolved labels skip that action. Use the collaborative editor to edit an existing ranking rule. See [query dimension setup and previews](/help/ranking-relevancy/create-ranking-rule#target-what-a-query-asks-for) for the merchant workflow. ### Managing store settings Use `store-settings-manage` for operational settings, and `store-search-configuration` for search behavior, prompts, and ranking weights. Both require the connection's `store.configure` permission. * `get` returns all sections by default. Pass `sections` to request only `sync_settings`, `preferences`, `sales_channel`, or `markets`. * `update` accepts `data` keyed by those section names. Only supplied fields change; omitted fields keep their saved values. Read the current settings before making a change and check the returned sections afterward. * `sync_settings` manages crawler signature headers. Their values are write-only: reads report whether the headers are set, never their secret contents. Enabling signatures requires both headers, which can already be saved. * `preferences` controls Shopify resource syncing and inventory location scope. Sync overrides accept `true` to force on, `false` to force off, or `null` for auto-detection. Reads include detection state and available inventory locations. Missing Shopify permissions can prevent a sync preference from being changed. * `sales_channel` selects the Shopify channel treated as the app storefront. Read this section to discover available channels before selecting one. * `markets` selects `strict` for market catalog eligibility and localized pricing, `pricing_only` for localized pricing without catalog restrictions, or `off` to ignore markets. Reads include active markets. These are direct saved changes, not collaborative drafts. They use the same validation and follow-up processing as the dashboard. Unsupported sections or fields are rejected rather than silently ignored. Staff-only settings are not available through this tool. ### Managing banner types Use `banner-types-manage` to manage reusable banner definitions. This is separate from placing a banner in a merchandising rule: edit those placements through `set_presence` and `apply_patch` on `/banners`. 1. Call `taxonomy` to discover the supported field types, list support, and validation options. 2. Use `list` or `get` to inspect existing types. `get`, `update`, and `delete` require `banner_type_id`. 3. To `create` a type, provide `data.name`, `data.allowed_modes`, and `data.field_schema`. Placement modes are `inject` for banners between products and `overtake` for replacing the grid. The name determines a permanent slug. 4. To `update` a type, send only the fields you want to change. If you send `field_schema`, it replaces the entire schema, not just individual fields. > [!WARNING] > > Banner type writes save immediately. Removing a field or changing its type can drop stored values from banners that use it. Inspect existing uses before updating, and read any returned `warning` for affected rule banners. System types are read-only. You cannot delete a type while a rule banner still uses it; remove those banners or switch their type first. Invalid schemas are rejected using the same validation as the dashboard. ### Example: edit a merchandising rule Ask your AI assistant: > "Pin the product 'Classic White Tee' to position 1 in the Summer Sale collection, and boost all products where brand is 'Nike' using a soft boost expression." The assistant uses `merchandising-rules-manage` to find an existing rule, then calls `set_presence` and `apply_patch` to edit its draft. To create a rule, use the tool's create action. Newly created merchandising rules start disabled and do not affect live results until published. ### Bulk actions `blocks-manage` can duplicate one block with `action: "duplicate"` and `block_id`. The response includes the source `block_id`, the new `duplicated_id`, a message, and `next_steps` for continuing with the draft. ```json theme={null} { "store": "my-store", "action": "duplicate", "block_id": "01J8A1V2K3M4N5P6Q7R8S9T0VW" } ``` The tool also accepts bulk variants so an assistant can apply the same change to many blocks in one call: * `blocks-manage` — `bulk_publish`, `bulk_unpublish`, `bulk_duplicate`, `bulk_delete` (pass `block_ids`) `bulk_duplicate` creates one copy for each entry in `block_ids`, in input order; repeating an id creates another copy. Unknown ids are returned in `not_found_ids`. Use bulk actions to update many blocks at once, such as unpublishing a batch of drafts after a seasonal campaign or deleting duplicate blocks. ```json theme={null} { "store": "my-store", "action": "bulk_unpublish", "block_ids": ["blk_123", "blk_456", "blk_789"] } ``` The response includes an `affected_count` so the assistant can confirm how many records changed. ### Collaborative editor Assistants edit merchandising rules, sort orders, recommendation blocks, facet values, ranking rules, and audiences through a collaborative editing flow instead of direct writes. An assistant announces presence on a resource, reads the current shared document and its revision, then applies small RFC 6902 JSON Patch operations. This lets multiple humans and agents work on the same resource without overwriting each other. It also powers the same [real-time collaboration](/platform/real-time-collaboration) experience that shows other editors in the dashboard. When an agent calls `set_presence` or `apply_patch`, humans on the same page see the agent live in the dashboard. The agent gets its own presence avatar with a distinct color, and its focused field or selected rows are tinted and locked like any other collaborator's. On the facet-values editor, a compact **agent activity** popover also surfaces the `intent` and `message` your agent supplies. Provide a short, human-readable `activity.intent` and `activity.message` on `set_presence`, and a concise `metadata.intent` on `apply_patch`. This lets a human co-editor tell at a glance what your agent is doing. Use the collaborative editor tools when your assistant needs to change: * Merchandising rule fields, pins, or banners * Sort order fields (referenced by id or handle) * Recommendation block fields (referenced by block id) * Facet value sorting, grouping, and hidden values (referenced by attribute id or code) * Ranking rule fields, including targeting, actions, visual pins, and enabled status (referenced by rule id) * Audience names, conditions, and optional SegmentQL source (referenced by audience id) The supported `resource_type` values are `merchandising_rule`, `sort_order`, `block`, `facet_values`, `ranking_rule`, and `audience`. Use `merchandising-rules-manage` and `sort-orders-manage` to list or create those resources. Use `blocks-manage` with `action: "list"` or `blocks-catalog`, `facet-values-manage` with `action: "list"`, `ranking-rules-manage` with `action: "list"`, and `audiences-manage` with `action: "list"` or `action: "get"` to inspect other resources. > [!NOTE] > > Use the collaborative editor to change existing merchandising rules, sort orders, blocks, or facet values. `ranking-rules-manage` supports creating and deleting ranking rules; edit existing rules through the shared editor rather than direct `update` or `toggle_status` calls. New merchandising and ranking rules start disabled. Publishing a new draft turns it on when both its saved and draft states are off; if you explicitly turn an already-live resource off in the draft, publishing keeps it off. Newly created blocks remain drafts until published. A new sort order is not added to the storefront's available sort menu, but it can still affect a request when a collection, rule, or block explicitly references it. When a management tool creates a draft, follow the returned `next_steps`: call `set_presence` with the indicated resource type and id, use `validate_document` and `apply_patch` if you need to edit its content, then call `request_publish` and check the result with `check_publish_request`. The admin tool `sort-orders-manage` does not replace the storefront `sort-orders-list` tool, which remains available to list sort orders for storefront integrations. #### Managing audiences Use `audiences-manage` to discover and create [saved audiences](/help/configuration/manage-audiences). Reads require `merchandising-rules.view`; creation, deletion, and publishing edits require `merchandising-rules.edit`. Your MCP connection must have access to the store. * **Discover:** `list` supports name search and pagination. `get` takes `audience_id` and returns the audience and its references, so you can check where a change will apply. * **Choose fields:** `attributes` lists supported condition fields, operators, and SegmentQL codes. Use `store-dimensions` for store-specific custom context fields. * **Create:** Pass `data.name` and `data.conditions`. Names are unique within the store, ignoring case. An audience cannot reference another audience. * **Estimate:** Pass `audience_id` for a saved audience, or `data.conditions` for a proposed definition. Estimates use recent recorded traffic and report conditions they cannot measure; they are not forecasts. See [traffic estimate limitations](/help/configuration/manage-audiences#read-the-traffic-estimate). * **Edit:** There is no direct `update` action. Call `set_presence` with `resource_type: "audience"` and the audience id as `resource_id`, then validate and patch `/fields/name`, `/fields/conditions`, or `/fields/segmentql`. Finish with `request_publish` and `check_publish_request`. * **Delete:** Pass `audience_id`. Deletion is refused while rules reference the audience, a person has it open, or a publish review is pending. Remove references or settle the review first; a refused deletion leaves the audience unchanged. `conditions` is the authoritative audience definition. The optional `segmentql` text is retained for display, not compiled by `audiences-manage` or the shared-editor publish path. Do not patch only the query text and expect targeting to change. When changing conditions without matching source text, clear `/fields/segmentql` to `null` so the editor opens the builder instead of a stale query. Audience drafts do not affect live targeting until saved. Approval or immediate publishing saves the definition used by every referencing rule; audiences do not have a separate enabled toggle. Audience publish responses use `config_version_id: null`. #### Editing flow The safe change-and-review sequence is `set_presence` -> `validate_document` -> `apply_patch` -> `request_publish` -> `check_publish_request`. **1. Announce presence and read the document** Call `set_presence` with the store, `resource_type`, and `resource_id`. If you do not pass a `presence_id`, the tool creates an active session or reuses your existing one for that store and resource. The response includes the `presence_id`, current `document`, `revision`, `active_editors`, and an `expires_at` timestamp. **2. Plan and (optionally) validate patches** Build small RFC 6902 patches against the public roots `/fields`, `/pins`, and `/banners`. Prefer granular list operations like `add /pins/-`, `replace /pins/5`, `remove /pins/3`, and `move` over replacing the entire `/pins` or `/banners` collection. Call `validate_document` first when it would reduce risk, for example before a large or unusual patch. **3. Apply the patch** Call `apply_patch` with the same `presence_id`, the observed `revision`, and the RFC 6902 patch list. Patches are applied atomically: if any operation fails, no changes are committed and the revision is unchanged. On success, the response returns the new `revision` and `document`. **4. Refresh presence and retry on conflict** Presence expires at `expires_at` unless refreshed. Calling `set_presence` again with the same `presence_id` refreshes it; calling without an id reuses your active session for the same store and resource. Successful `apply_patch` calls also refresh presence. Use `release: true` to end the session when you are done. If a patch fails with a stale revision or a failed `test` operation, refresh presence to re-read the document and re-plan. #### `set_presence` Declares an agent's activity state and returns the shared document. Supported `activity_state` values are `viewing`, `editing`, `thinking`, and `validating`. An agent has one active presence per store and resource: calling without `presence_id` reuses that session and updates its activity state and expiry. Supply `release: true` with the `presence_id` or the resource locator to release it; `activity_state` is not required for a release. A successful release returns `released: true`; releasing an already missing or expired session is idempotent and returns `released: false`. ```json theme={null} { "tool": "set_presence", "arguments": { "store": "my-store", "resource_type": "merchandising_rule", "resource_id": "rule_123", "activity_state": "viewing", "activity": { "intent": "inspect_rule", "message": "Reviewing current pins and fields" } } } ``` Example response: ```json theme={null} { "success": true, "presence_id": "prs_01j_example", "resource_type": "merchandising_rule", "resource_id": "rule_123", "activity_state": "viewing", "active_editors": [], "expires_at": "2026-07-07T16:21:44Z", "revision": "sha256-document-revision", "document": { "fields": { "name": "Summer collection" }, "pins": [], "banners": [] } } ``` Pass a sort order handle or id as `resource_id` when `resource_type` is `sort_order`. Keep the returned `presence_id` for later editor calls, or pass it to `set_presence` to refresh or release the session. ```json theme={null} { "tool": "set_presence", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "release": true } } ``` #### `validate_document` Validates the current document or a proposed set of patches without applying changes. Whole-collection replacements return warnings so agents prefer granular list operations. An active `presence_id` can identify the resource without `resource_type` and `resource_id`; if you pass both forms, they must identify the same resource. ```json theme={null} { "tool": "validate_document", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "revision": "sha256-document-revision", "patches": [ { "op": "add", "path": "/pins/-", "value": { "id": "gid://shopify/Product/222", "position": 2, "pin_type": "product" } } ] } } ``` #### `apply_patch` Applies an atomic RFC 6902 patch. Requires an active `presence_id` from `set_presence` and the latest observed `revision`. Supported operations are `add`, `remove`, `replace`, `move`, `copy`, and `test`. Patch paths must be under `/fields`, `/pins`, or `/banners`. ```json theme={null} { "tool": "apply_patch", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "revision": "sha256-document-revision", "metadata": { "intent": "move_pins", "client": "mcp-agent" }, "patches": [ { "op": "add", "path": "/pins/-", "value": { "id": "gid://shopify/Product/222", "position": 2, "pin_type": "product" } } ] } } ``` ##### Readable pin positions `set_presence`, `apply_patch`, and `validate_document` responses include `pin_positions` alongside the shared document. Use this read-only summary to describe pin order without treating the document's raw `position` values as shopper-facing slot numbers. | Field | Meaning | | - | - | | `path` | The pin's current JSON Patch path, such as `/pins/2`. The array index is not its display position. | | `id` | The pin's product identifier | | `pinned_variant_id` | The selected variant identifier, or `null` | | `sequential_position` | One-based order among sequential pins, excluding absolute pins; `null` for an absolute pin | | `absolute_position` | The pin's fixed result position, or `null` for a sequential pin | For merchandising rules, each entry also reports whether the pin is live on the storefront right now. Other resource types return only the fields above. | Field | Meaning | | - | - | | `serving` | `true` when the pin currently serves, `false` when it doesn't, or `null` for a pin that hasn't been published yet | | `condition_type` | The pin's condition type: `always`, `scheduled`, `advanced`, or `advanced_scheduled` | | `schedule_start_at` | The schedule start time, or `null` | | `schedule_end_at` | The schedule end time, or `null` | | `not_serving_reason` | Why the pin isn't serving: `schedule_not_started`, `schedule_ended`, `condition_not_met`, `variant_missing` (the pinned variant is no longer available), `disabled`, or `unpublished`. `null` while the pin serves | A pin that isn't serving has a `null` `sequential_position` and doesn't count toward the numbering of other sequential pins, which matches how browse places pins. Serving state is read-only and comes from the published rule. To change a pin's schedule or conditions, use the **Pin Conditions** panel in the dashboard. `validate_document` and `request_publish` also return a `PinNotServing` warning for each merchandising rule pin that won't serve. The warning includes the pin's `path`, and its message names the slot, product, and reason. When you pass `patches` to `validate_document`, the warnings use the post-patch paths reported in `patched_pin_positions`. These warnings don't make a document invalid and don't block publishing. For example, a sequential pin with a raw ordering value of `2048` might be second in the sequence, not result 2048. A pin fixed at absolute position 10 reports that value separately and does not count toward sequential numbering. Use the returned `path` to patch the correct item, and refresh it after edits that change the array. Do not patch `pin_positions` itself. ##### Pin consistency Each pin must be internally consistent. A pin with `pin_type: "variant"` requires a non-null `pinned_variant_id`. Any other pin type requires a null `pinned_variant_id`. If you omit `pin_type`, it defaults to `product`. `apply_patch` rejects any patch that leaves a pin inconsistent and doesn't change the document. `validate_document` reports the same problem without writing. To change a pin's type, set both fields in the same patch. You can also `remove` the pin and `add /pins/-` a new, consistent one. `apply_patch` rejects a lone `replace /pins/0/pin_type` that leaves `pinned_variant_id` unchanged. ```json theme={null} { "patches": [ { "op": "replace", "path": "/pins/0/pin_type", "value": "product" }, { "op": "replace", "path": "/pins/0/pinned_variant_id", "value": null } ] } ``` Use `test` before `replace` to catch concurrent edits: ```json theme={null} { "patches": [ { "op": "test", "path": "/fields/name", "value": "Summer collection" }, { "op": "replace", "path": "/fields/name", "value": "Summer collection hero merchandising" } ] } ``` ##### Explaining edits with `metadata.notes` `metadata` accepts an optional `notes` object that maps an exact patch `path` in the same call to a one-line reason for the change. Notes appear in the dashboard's agent activity feed as the caption for that step, so a human co-editor can see why the agent made each change. ```json theme={null} { "tool": "apply_patch", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "revision": "sha256-document-revision", "metadata": { "intent": "reorder_pins", "notes": { "/pins/0/position": "featured jacket leads the launch collection", "/fields/facet_value_group_sorts": "in-stock colors first" } }, "patches": [ { "op": "replace", "path": "/pins/0/position", "value": 1 } ] } } ``` Rules for `notes`: * Each key must match a `path` present in the same `patches` list. Notes for unknown paths are dropped. * Values must be non-empty strings. Non-strings and empties are dropped. * Notes are trimmed and capped at 240 characters. * Write a short reason (why this helps the shopper), not a restatement of the operation. `notes` is optional. Patches sent without `notes` apply the same way. #### Error handling `apply_patch` returns deterministic errors so agents can recover automatically: | Status | Error | Recovery | | - | - | - | | 403 | `PermissionDenied` | Ask for an editor with the required store permission. | | 404 | `ResourceNotFound` | Re-check the resource id or sort order handle. | | 409 | `PresenceRequired` | Call `set_presence` to create or refresh a `presence_id`, then retry. | | 409 | `RevisionConflict` | Refresh presence, re-read `document` + `revision`, and retry only if the edit still applies. | | 409 | `TestFailed` | Another editor changed the tested value. Re-read the document and re-plan. | | 422 | `InvalidPatch` | Fix the RFC 6902 operation shape, or restrict paths to `/fields`, `/pins`, or `/banners`. | #### Requesting publish approval `apply_patch` only updates the shared draft. To save a change to the live store, use `request_publish` for any supported resource: merchandising rules, sort orders, recommendation blocks, facet values, ranking rules, or audiences. Human review is the default. For a new draft, the reviewer must explicitly choose **Approve & save** to activate it. A regular editor save can also settle a pending request as published, but it preserves the submitted live/enabled state, so a published status alone does not guarantee that the resource is enabled. After requesting review, poll `check_publish_request` until the request settles. Do not call `apply_patch` again on the same resource while a request is pending unless the request is rejected or the user explicitly asks for more edits. The **Review changes** dialog shows the requesting assistant and its summary. **Review in editor** closes the dialog so the reviewer can inspect the actual draft. **Approve & save** saves the current editor contents, so the reviewer should check the draft rather than relying only on the assistant's summary. Review and rejection are supported for all six resource types. Selecting **Reject** opens a confirmation step with an optional note and two choices: * **Discard draft**, selected by default, restores the last saved version in the shared editor and removes unpublished changes. Confirm with **Reject & discard draft**. * **Keep draft for further edits** leaves the shared draft available for revision. Confirm with **Reject & keep draft**. Neither rejection choice changes the published version. Continue polling `check_publish_request` to read the outcome and any note. For facet values, approval requires a full dashboard save that submits both `facet_value_group_sorts` and `hidden_values`. A partial facet save leaves the request pending and preserves the shared draft, while a save to unrelated attribute settings does not approve it. See [Editing facet values](#editing-facet-values) for the facet-specific workflow. **1. Request approval** Call `request_publish` with the same `presence_id` and the latest observed `revision`. Include an optional `message` describing what changed so the reviewer has context. The response includes a `publish_request_id`, a dashboard `review_url`, and an `expires_at` timestamp. **2. Share the review URL and wait** Send the `review_url` to the user or reviewer. They can inspect the affected resource in the dashboard and choose **Approve & save** or **Reject** from the request review. A regular editor save can also settle a pending request as published while preserving the submitted live/enabled state. Do not make further edits in that shared room while the request is pending unless the request is rejected or the user explicitly asks for more changes. **3. Poll for the outcome** Call `check_publish_request` with the `publish_request_id` until `settled` is `true`. The final `status` is `published`, `rejected`, `superseded`, or `expired`. Publish requests expire after 72 hours. **4. Handle the result** On `published`, the resource was saved. A ranking rule's `enabled` field still determines whether it runs on the storefront. Merchandising rules, sort orders, and ranking rules have a `config_version_id`; blocks, facet values, and audiences return `null`. For `rejected` or `expired`, review any resolution note before deciding what to do. On `superseded`, a newer request has replaced this one. Switch to the newer `publish_request_id`. ##### `request_publish` Requests human approval for the shared document the agent is currently editing. Review is the default; use [`publish_immediately`](#publishing-immediately) only when the user explicitly asks to publish without review. Requires an active `presence_id` from `set_presence` and the latest `revision` you observed. The revision must still match the current room revision, or the tool returns a `RevisionMismatch` error. Refresh presence and try again. ```json theme={null} { "tool": "request_publish", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "revision": "sha256-document-revision", "message": "Pin the featured jacket to position 1 for the launch" } } ``` Example response: ```json theme={null} { "success": true, "publish_request_id": "pubreq_01j_example", "status": "pending", "review_url": "https://app.uselayers.com/stores/my-store/merchandise/rule_123?publish_request=pubreq_01j_example", "expires_at": "2026-08-17T12:00:00Z", "config_version_id": null, "next": "The publish request is pending human review. Poll check_publish_request with the publish_request_id until it is settled. The reviewer approves by saving from the dashboard review URL." } ``` Calling `request_publish` while another request is pending for the same shared editor room marks the older request as `superseded` and returns the new `publish_request_id`. ##### `check_publish_request` Returns the current state of a publish request. Safe to call as often as needed. ```json theme={null} { "tool": "check_publish_request", "arguments": { "store": "my-store", "publish_request_id": "pubreq_01j_example" } } ``` Example response after approval: ```json theme={null} { "success": true, "settled": true, "status": "published", "publish_request_id": "pubreq_01j_example", "review_url": "https://app.uselayers.com/stores/my-store/merchandise/rule_123?publish_request=pubreq_01j_example", "resolved_by": "Jamie Reviewer", "resolution_note": null, "config_version_id": "cfgv_01j_example", "resolved_at": "2026-08-14T15:04:00Z", "expires_at": "2026-08-17T12:00:00Z", "next": "The publish request was approved and published. The changes are now live." } ``` `status` values: | Status | Meaning | | - | - | | `pending` | Waiting on a reviewer. Keep polling. | | `published` | The resource was saved. `config_version_id` identifies the new version for merchandising rules, sort orders, and ranking rules; it is `null` for blocks, facet values, and audiences. | | `rejected` | The request was rejected. `resolution_note` may explain why. | | `superseded` | A newer `request_publish` call replaced this request. Use the newer `publish_request_id`. | | `expired` | 72 hours passed without a decision. | #### Publishing immediately Set `publish_immediately: true` on `request_publish` to apply the shared editor document straight to the saved merchandising rule, sort order, recommendation block, facet values, ranking rule, or audience, with no reviewer step. Use it only when the user has explicitly asked to publish without review. When you omit the flag or pass `false`, the tool creates a pending review request. Requirements and behavior: * Supported for `resource_type: "merchandising_rule"`, `sort_order`, `block`, `facet_values`, `ranking_rule`, and `audience`. * The caller needs the resource's edit permission on the store: `merchandising-rules.edit` for merchandising rules and audiences, `sort-orders.edit`, `blocks.edit`, `attributes.edit` for facet values, or `ranking-rules.edit`. Without it, the tool returns 403. * There is no `force` override for a stale revision or a human editing the room. * The provided `revision` must still match the current room revision, or the tool returns 409 `RevisionMismatch`. Call `set_presence` to refresh and retry. * If a human is actively co-editing the room, or connects during the publish, the tool returns 409 `HumanEditingInProgress` and nothing is written. Ask the user to save from the dashboard, or retry once the human leaves. * The document is validated with the same rules the dashboard save uses. Validation errors are returned as 422 with per-field messages. * On success, the response includes `status: "published"`, confirming the resource was saved. `config_version_id` is populated for merchandising rules, sort orders, and ranking rules, and is `null` for blocks, facet values, and audiences. Pass the returned `publish_request_id` to `check_publish_request` to verify the saved result without waiting for review. Layers uses a stable snapshot for an immediate publish. If a human is editing the same room, the publish is rejected rather than overwriting that work. ```json theme={null} { "tool": "request_publish", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "revision": "sha256-document-revision", "publish_immediately": true, "message": "User asked to publish the featured-jacket pin without review" } } ``` Example response: ```json theme={null} { "success": true, "publish_request_id": "pubreq_01j_example", "status": "published", "review_url": "https://app.uselayers.com/stores/my-store/merchandise/rule_123?publish_request=pubreq_01j_example", "expires_at": "2026-08-17T12:00:00Z", "config_version_id": "cfgv_01j_example", "next": "The change was published immediately and is now live. No review is needed." } ``` #### `collaborative-merchandising-editor` prompt The Layers MCP server exposes a `collaborative-merchandising-editor` prompt that describes the full safe-edit workflow, including the `request_publish` handshake. MCP clients that surface prompts (for example, Claude Desktop) can select it to prime an assistant with the correct presence-then-patch-then-request sequence before making changes. #### Editing facet values Facet value sorting, grouping, and hidden values live inside a filterable attribute's configuration. Assistants co-edit them through the same collaborative editor tools by passing `resource_type: "facet_values"` and the attribute id or code as `resource_id`. The shared document exposes two keys under `/fields`: * `facet_value_group_sorts` — an ordered list of `{ facet_value, position, facet_value_group_filter }` entries. `position` controls the manual storefront order, and `facet_value_group_filter` is `{ name }` when the value belongs to a named group (all values sharing one `facet_value_group_filter.name` render as one group), or `null` when ungrouped. * `hidden_values` — a list of facet value strings that are hidden on the storefront. Rows in `facet_value_group_sorts` carry **no ids**. The server keys sorts by `facet_value` and groups by `name` (both distinct per attribute) and owns the underlying UUIDs. Never send an `id` on a sort entry or on `facet_value_group_filter`. Layers rejects it. Facet value sorting, grouping, and hidden values are edited in the shared document. Use `request_publish` to request human review, or [`publish_immediately`](#publishing-immediately) only when the user explicitly asks to publish without review. `attributes-manage` `create` and `update` reject `facet_value_group_sorts` and `hidden_values` with a 422 that points back to the shared editor. Don't try to set them alongside other attribute fields. Facets don't have `/pins` or `/banners`, so patches must target `/fields/facet_value_group_sorts` or `/fields/hidden_values`. The `attributes.view` permission is required to read a facet's document and `attributes.edit` is required to apply patches or call `request_publish`. Reorder a value: ```json theme={null} { "tool": "apply_patch", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "revision": "sha256-document-revision", "patches": [ { "op": "test", "path": "/fields/facet_value_group_sorts/0/facet_value", "value": "Red" }, { "op": "replace", "path": "/fields/facet_value_group_sorts/0/position", "value": 3 } ] } } ``` Group two values under a shared display name by giving both entries the same `facet_value_group_filter.name`: ```json theme={null} { "patches": [ { "op": "replace", "path": "/fields/facet_value_group_sorts/1/facet_value_group_filter", "value": { "name": "Warm tones" } }, { "op": "replace", "path": "/fields/facet_value_group_sorts/2/facet_value_group_filter", "value": { "name": "Warm tones" } } ] } ``` Hide a value from the storefront: ```json theme={null} { "patches": [ { "op": "add", "path": "/fields/hidden_values/-", "value": "Discontinued" } ] } ``` ##### Sampling and grouping facet values `facet-values-manage` exposes two actions that operate on facet values directly, without drafting RFC 6902 patches by hand. **`samples`** shows what a facet value actually resolves to on the storefront. For each requested value it returns the shopper-visible product count (computed on the same filter path the storefront uses, so counts match what a shopper sees), the display name, the swatch (metaobject or option), and a few sample products and variants: | Argument | Description | | - | - | | `attribute` (required) | Facet attribute id or code | | `values` (required) | Facet values to resolve (max 25) | | `per_value` | Sample products per value (default 3, max 5) | | `include_images` | Also return image content blocks: the first sample image per value, Shopify CDN width 256, at most 8 per call. Defaults to `false` | ```json theme={null} { "tool": "facet-values-manage", "arguments": { "store": "my-store", "action": "samples", "attribute": "color", "values": ["Emerald", "Sage Mist"], "per_value": 3 } } ``` Each entry in `values` reports `{ facet_value, display_name, product_count, swatch, samples }`, where each sample is `{ product_title, product_handle, variant_title, image_url }`. For a facet that isn't filterable on the storefront (for example, one not visible on the storefront), `product_count` is `null` and the entry carries an `error` note instead of failing the call. **`upsert`** places individual values into groups inside the shared collaborative draft. Use it when you want to group a handful of values without rewriting the whole `facet_value_group_sorts` list with `apply_patch`. Call `set_presence` first to get a `presence_id`; the draft's current revision is resolved for you. Each row in `rows` is `{ facet_value, group, after? }`: * `facet_value` — the value to place. All existing memberships of that value are removed before the new row is inserted. * `group` — the group name to place the value in. A new name creates the group; `null` ungroups the value. Required on every row. * `after` — optional. Place the value directly after this value inside the target group; when omitted or when `after` isn't in that group, the row lands at the end of the group. A moved value keeps its position only when staying in its current group. ```json theme={null} { "tool": "facet-values-manage", "arguments": { "store": "my-store", "action": "upsert", "attribute": "color", "presence_id": "prs_01j_example", "rows": [ { "facet_value": "Emerald", "group": "Green tones" }, { "facet_value": "Sage Mist", "group": "Green tones", "after": "Emerald" }, { "facet_value": "Discontinued", "group": null } ], "metadata": { "notes": "Group green shades for the spring collection" } } } ``` The response returns the new draft `revision` and the `changed_rows` that were applied. `upsert` requires `attributes.edit` and an authenticated user, and writes into the same shared draft `apply_patch` edits. Request review of the finished draft with `request_publish`. ##### Requesting approval for the facet-values draft `apply_patch` and `facet-values-manage` `upsert` only update the shared draft. By default, call `request_publish` with the active `presence_id`, the latest `revision`, and an optional `message` to request human review. See [Requesting publish approval](#requesting-publish-approval) for the review and polling workflow, and [Publishing immediately](#publishing-immediately) only when the user explicitly asks for no review. The reviewer approves by saving from the dashboard review URL. A facet-values approval requires a full save that submits both `facet_value_group_sorts` and `hidden_values`. Partial saves leave the request pending and preserve the shared draft; saves to unrelated attribute settings do not approve it. `check_publish_request` reports `config_version_id: null` for facet values. ```json theme={null} { "tool": "request_publish", "arguments": { "store": "my-store", "presence_id": "prs_01j_example", "revision": "sha256-document-revision", "message": "Sort color values and hide discontinued shades" } } ``` The response follows the `request_publish` shape described in [Requesting publish approval](#requesting-publish-approval). For facet values, `config_version_id` is `null`. The removed `facet-values-manage` `publish` action is not supported: cached clients that call it receive an error directing them to `request_publish` with the `presence_id` and latest `revision` from `set_presence`. The `list`, `samples`, and `upsert` actions are unchanged. #### `collaborative-facet-editor` prompt The Layers MCP server also exposes a `collaborative-facet-editor` prompt covering the presence-patch-review flow, `/fields` patch boundaries, and the human-in-the-loop rule for publishing. Select it before asking an assistant to reorder, group, or hide facet values. ### Working with grouped attributes Some attributes are containers that hold other attributes rather than a single filterable value, for example a "dimensions" attribute that wraps `length`, `width`, and `height`. MCP tools treat these differently: * **Groups are listed but not selectable.** `attributes-manage` with `action: "list"` returns grouped attributes as read-only entries with their child attributes nested under `children`. Only the scalar children are marked `selectable`. * **Search, browse, facets, and sort orders reject group codes.** Passing a group, object, or otherwise non-selectable attribute code to `filter_group`, `facets`, or a sort order returns a validation error. When the parent has scalar children, the error lists them so your assistant can retry with a valid code. Use `attributes-manage` with `action: "list"` to discover which attributes are selectable before building filters or sort orders. Pass `usable_for: "attributes"` to get exactly the codes accepted as result attributes, or `usable_for: "facets"` for the codes accepted in `facets` and `filter_group`. ### Checking the keyword weight budget The `list` response includes a top-level `keyword_weight_holders` summary of the store's [keyword search weight budget](/platform/attributes/attribute-options#keyword-search-weight-limits). Check it before you set `keyword_search_weight` so your assistant knows how much budget is left. The summary lists every attribute holding a weight, including group or structured metafield attributes that never appear as individual entries in the list: ```json theme={null} { "keyword_weight_holders": { "total": 10, "remaining": 0, "holders": [ { "code": "body_html", "weight": 1.5, "is_searchable": true, "hidden": false }, { "code": "metafields.custom.shop", "weight": 1, "is_searchable": false, "hidden": true }, { "code": "title", "weight": 7.5, "is_searchable": true, "hidden": false } ] } } ``` * `total` and `remaining` are the combined weight in use and the weight still available, out of 10. * `is_searchable` is `false` for attributes that hold a weight but aren't searchable. Their weight still counts toward the budget. * `hidden` is `true` for attributes that don't appear as selectable entries in the `list` output. `attributes-manage` rejects a `keyword_search_weight` on an attribute that isn't searchable. To add a weight, set `is_searchable: true` in the same `update` request. ### Fetching attribute values Call `attributes-manage` with `action: "values"` to enumerate the values available for a single scalar attribute. Use it before building `filter_group` conditions when your assistant needs to know what values a facet actually contains. For example, list every vendor or size before choosing one to filter on. The response depends on the attribute's type: * **Categorical attributes** return a cursor-paginated `values` array. Each entry is `{ "value": "", "kind": "group" | "value" }`. Pass the returned `next_cursor` back in a follow-up call to fetch the next page. * **Numeric attributes** return a `range` object with the minimum and maximum values in the catalog. Both responses can be scoped to a collection with `collection_handle` so the values reflect only products in that collection. When the attribute has [facet value groups](/help/advanced-merchandising/facet-grouping), the first page lists each group with `kind: "group"` before any raw values, and raw members of a group are hidden from the results. Pass the group name as the filter value and Layers expands it to the group's members at match time. Ungrouped raw values are returned with `kind: "value"`. ```json theme={null} { "type": "values", "attribute_code": "color", "values": [ { "value": "Purple", "kind": "group" }, { "value": "Neutrals", "kind": "group" }, { "value": "Emerald", "kind": "value" } ], "next_cursor": null, "limit": 50 } ``` ```json theme={null} { "store": "my-store", "action": "values", "attribute_code": "vendor", "collection_handle": "summer-sale", "limit": 50 } ``` ### Selecting product and variant fields The `attributes` argument on `search-semantic`, `browse`, and related tools accepts three kinds of selectors, all discoverable through `attributes-manage` with `action: "list"`: * **Attribute codes** — any storefront-visible attribute code (`vendor`, `color`, `size`). * **Core product fields** — top-level product columns like `title`, `handle`, `featured_image`, `body_html`, `product_type`, `tags`. Dotted sub-paths (`images.src`) are only accepted under jsonb product columns. * **Qualified variant selectors** — variant fields must be qualified with a container: `variants.` returns the value for every variant, and `first_or_matched_variant.` returns the single variant that matches the current filter (or the first variant when no variant filter is active). Hidden variant columns such as `cost` are rejected. Bare variant field names like `price` are rejected with a message that names the qualified forms (`variants.price`, `first_or_matched_variant.price`). Unknown sub-paths on a core product field return a 422 that suggests the parent field, for example `title.foo` → *Did you mean 'title'*. ```json theme={null} { "tool": "browse", "arguments": { "store": "my-store", "collection_handle": "summer-sale", "attributes": ["title", "handle", "featured_image", "first_or_matched_variant.price", "variants.selected_options.name"] } } ``` `attributes-manage` with `action: "list"` lists the qualified variant selectors alongside attribute codes so an assistant can discover the full vocabulary in one call. When a query matches nothing, the response includes a `suggestions` list of the top-5 nearest codes. ### Classifying attributes for query understanding `attributes-manage` `create` and `update` accept a `data.classes` array that controls how the query-understanding pipeline uses an attribute. Set it separately from `is_searchable`, `keyword_search_weight`, and `enable_as_storefront_facet`. Each switch controls a different behavior. | Class | What it enables | | - | - | | `categorical` | Filters and sorts on exact values (color, size, brand). Required for the attribute to appear in intent detection. | | `feature` | Keyword-style modifiers and context priors from descriptive terms (waterproof, slim fit, wireless). | | `price` | Price-aware filtering and ranking. Use for price or price-derived signals. | | `identifier` | Exact and prefix matching during SKU prefix search for codes shoppers type verbatim (MPN, style number, UPC/EAN). Only `metafields.*` and `variant_metafields.*` attributes qualify. The attribute can't be searchable, and a store can have at most five. See [Identifier attributes](/platform/attributes/attribute-classes#identifier-attributes). | Pass one or more classes; values are lowercased and deduped server-side. To leave the existing classes unchanged on `update`, omit the `classes` key. Passing `null` or any non-array value returns a validation error rather than clearing the field. Adding `identifier` to a searchable attribute, a non-metafield attribute, or a store that already has five identifier attributes also returns a validation error. ```json theme={null} { "tool": "attributes-manage", "arguments": { "store": "my-store", "action": "update", "attribute_code": "color", "data": { "classes": ["categorical"] } } } ``` Toggling `is_searchable` triggers a catalog reindex, so batch those changes. The `attribute-setup` prompt walks an assistant through the full workflow: discovering the attribute, sampling values with `query_catalog`, picking classes, and verifying with `product-search-diagnostics`. Select it from an MCP client that surfaces prompts (for example, Claude Desktop) before asking an agent to classify attributes. ### Creating and publishing computed attributes `attributes-manage` `create`, `update`, `publish`, and `delete` operate on [computed attributes](/platform/attributes/calculated-attributes). Shopify options, metafields, and other catalog fields sync automatically and can't be created or removed through MCP. **What each action does:** | Action | Purpose | | - | - | | `create` | Create a new computed attribute. `data.type` must be `calculated` (JavaScript Function) or `derived` (JsonLogic). | | `get` | Return one attribute, including `compile_status`, `compile_error`, and source fields. Use it to poll after `publish`. | | `update` | Edit an existing attribute in place. On computed attributes, `data.source_code`, `data.input_query`, `data.output_schema`, and `data.calculated_logic` may be written directly. Attribute codes are immutable, so a `data.code` change is always rejected. | | `publish` | Promote a saved draft (`draft_source_code`, `draft_input_query`, `draft_output_schema`), or explicit `data.source_code`, `data.input_query`, and `data.output_schema`, into the live computed attribute. This runs the same path as the dashboard **Save** button. Rejected on catalog attributes. | | `preview` | Resolve an input query against 1–5 real products (ids or handles) and return the exact `input` object `main()` receives for each. Pass `data.input_query`, or an `attribute_code` to use its draft (then live) input query. Add `run_function: true` to also return the live compiled function's output. Writes nothing. | | `delete` | Delete a computed attribute. Rejected on catalog attributes and on any computed attribute referenced by a sort rule, sequence, family, merchandising rule, or report. | **Rules `create` enforces:** * `data.type` must be `calculated` or `derived`. * `data.code` is auto-prefixed with `calculated.` when it has no reserved namespace, so `style_number` becomes `calculated.style_number`. A code that already targets a synced namespace (contains a dot, for example `options.size` or `metafields.custom.x`) is rejected. A code that matches an existing attribute case-insensitively (`options.Size` when `options.size` already exists, or a bare `vendor`) is rejected too. Call `list` to confirm what's already there. * `type: "calculated"` requires `data.source_code`. `type: "derived"` requires `data.calculated_logic`. * Exactly one implementation may be set per attribute. `create`, `update`, and `publish` all reject a request whose effective `source_code` and `calculated_logic` are both non-blank. Pass `null` on the field you're clearing in the same request. * `data.output_schema` is a list of `{ "name": "", "type": "", "nullable": }` objects, never a bare object. * A multi-field `output_schema` (more than one entry) can't set `enable_as_storefront_facet: true` on the parent. Enable the facet on the specific virtual child code instead, for example `calculated.dimensions.width`. `create` a JavaScript computed attribute: ```json theme={null} { "tool": "attributes-manage", "arguments": { "store": "my-store", "action": "create", "data": { "code": "calculated.style_number", "label": "Style Number", "type": "calculated", "source_code": "export function main(input) { return input.title.split(' ')[0]; }" } } } ``` **Source validation at write time.** `create`, `update`, and `publish` validate `data.source_code` synchronously before persisting. Source that can't compile is rejected with a 422 carrying the parser's rejection, instead of being accepted and surfacing later as an asynchronous `compile_error`. The same applies to `data.input_query`, which must be a bare selection set (a `query { ... }` document is rejected). `publish` validates the effective payload, so a bad draft saved earlier is also rejected at publish time. **Input query validation.** `data.input_query` is checked against your store's schema at every level. Unknown fields are rejected with the valid sibling fields and a closest-match suggestion, as are sub-selections on fields that have none and `calculated`, which always resolved to `null` inside an input query. Metafield names and reference sub-selections are checked against your store's metafield definitions. `draft_update` applies the same `input_query` and `output_schema` rules as `create`, `update`, and `publish`, and an unknown output type lists the allowed ones. **Previewing before publishing.** Use `preview` to confirm an input query returns the data your function expects before you publish: ```json theme={null} { "tool": "attributes-manage", "arguments": { "store": "my-store", "action": "preview", "attribute_code": "calculated.style_number", "products": ["heritage-tee", "8123456789012"], "run_function": true } } ``` Each entry in the response's `products` array carries the resolved `input` and, with `run_function: true`, the function's `output` (or an `output_error` for a product where it failed). Values over 16 KB per product come back truncated. `run_function` needs an attribute whose `compile_status` is `ready`, and it always runs the live function on the live input query. Draft source never runs server-side, so publish it and wait for `ready` first. When the previewed query differs from the live one, the response includes a `note` saying the output came from the live query. After `publish` reaches `ready`, Layers recomputes only that attribute's values on each product. A full catalog rebuild runs only when the attribute feeds search, sequences, families, merchandising rules, or variant breakout conditions. **Drafts and publishing.** `draft_update` writes to `draft_source_code`, `draft_input_query`, `draft_output_schema`, and `draft_test_state` on the live attribute. A draft is an editor autosave buffer only. Nothing compiles until `publish` promotes it into the live fields. A partial `draft_update` only touches the keys you send. Omitted draft fields keep their saved value, and an explicit `null` clears just that one field. `publish` promotes the draft. Compilation runs asynchronously, so poll `get` (or `list`) afterward to read `compile_status` and `compile_error`: ```json theme={null} { "tool": "attributes-manage", "arguments": { "store": "my-store", "action": "publish", "attribute_code": "calculated.style_number" } } ``` Each of `source_code`, `input_query`, and `output_schema` resolves independently on `publish`. An explicit `data.*` value beats a saved draft, which beats the current live value. Publishing a single-field override, for example just `data.output_schema`, doesn't drop a saved draft for the other fields. `calculated_logic` is only touched when you pass it explicitly. **Deleting a computed attribute.** `delete` runs the same usage guard the dashboard does, extended to cover reports and every virtual output-schema child. A blocked delete names the context, for example `Cannot delete attribute that is used in a sort order.` When the blocking usage sits on a virtual child, the message adds `(referenced via output field '')` so you know which field to detach first. Catalog attributes always fail this action. Use the dashboard or Shopify to remove those sources. ### Diagnosing search coverage Use `product-search-diagnostics` when a product is missing from `search-semantic` results, to verify what content reached its search document, or to confirm an attribute change flowed through. Resolve a product by numeric id, Shopify gid (`gid://shopify/Product/...`), or handle. Pass `include_variant_documents: true` on per-variant-indexed products to include the rendered document text for each variant. The response has three sections: | Field | Contents | | - | - | | `document` | The rendered search text plus a structured `toFilteredArray()` view, and per-variant documents when requested | | `content` | Per-content-type `included` and `excluded` lists for collections, tags, named tags, metafields, variant options, and variant metafields. Exclusions carry a `reason`: `ai_excluded`, `repeatedly_excluded`, `not_descriptive`, `not_searchable` (**Searchable** is turned off on the attribute in Layers; the entry includes the `attribute_id`. For metafields this means a merchant explicitly turned the option off. Metafields left disabled by the [automatic search review](/platform/attributes/attribute-options#automatic-search-review-for-metafield-and-named-tag-attributes) are not reported under this reason. For named tags it covers both merchant overrides and keys the automatic search review left off), or `not_breakout_dimension` (returned for `variant_options` when a [variant breakout](/platform/variant-breakouts#search-indexing) resolved the split dimension; the option may still reach each variant's document through `variant_content`) | | `indexing` | Readiness status (`ready` or `rebuild_pending`), `indexed_as` (`product` or `per_variant`), `indexed_as_source` (`breakout` when a [variant breakout](/platform/variant-breakouts#search-indexing) forced per-variant grouping, otherwise `model`), and document and image counts | ```json theme={null} { "tool": "product-search-diagnostics", "arguments": { "store": "my-store", "product": "classic-white-tee", "include_variant_documents": false } } ``` On dev stores that skip LLM content selection, the payload's `content_selection` field is `"skipped"`, and the store indexes the full unfiltered catalog instead. ### Diagnosing missing facets `product-search-diagnostics` also explains facet availability. Pass `facet_codes` (and optionally a `collection` handle) to check why a facet you requested from the [Facets API](/api-reference/facets) is missing from the response: ```json theme={null} { "tool": "product-search-diagnostics", "arguments": { "store": "my-store", "collection": "shirts", "facet_codes": ["color", "brand"] } } ``` The response's `facet_diagnostics` section lists the `requested` codes, which were `included`, and which were `dropped` with a `reason`: `attribute_not_found`, `not_enabled_as_facet`, `attribute_not_filterable`, `facet_still_building`, `facet_build_failed`, or `facet_cardinality_exceeded` (Layers turned the facet off automatically because it has [too many distinct values](/platform/facets#facets-with-too-many-distinct-values)). These are the same readiness checks the Facets API applies when serving requests, so a dropped code here explains a missing facet in storefront responses. See [When a facet goes live](/platform/facets#when-a-facet-goes-live) for how facet builds work. For a store-wide rollup, call `store-operational-status` and read `search_documents`. It returns aggregate `ready`, `pending`, and `needs_attention` counts across the catalog. The same response includes a `facets` section with each facet's build phase and last refresh time under `states`, plus a `withheld` list naming any enabled facets the API is currently holding back and why. ### Asynchronous tasks Tools run synchronously unless you ask for asynchronous execution. Today, `layersql-query` accepts `execution: "async"`, and new `search-batch` runs are also tracked as tasks. Use async execution for LayersQL queries that might take longer than your client waits for a tool response. | Parameter | Effect | | - | - | | `execution` | `sync` (default) or `async`. Tools that don't support async return an error when you pass `async` | | `idempotency_key` | Optional key of up to 128 characters. Reuse it when you retry the same call so Layers doesn't queue a duplicate task | #### Starting an async LayersQL query ```json theme={null} { "tool": "layersql-query", "arguments": { "store": "my-store", "query": "FROM products SHOW SUM(total_sales) GROUP BY product SINCE -30d", "execution": "async", "idempotency_key": "revenue-by-source-2026-11-03" } } ``` Layers validates the query before queueing it. Syntax errors, unknown metrics or dimensions, and a `SINCE` clause combined with `start_date` or `end_date` return immediately, just as they do in synchronous mode. When the query is valid, the response returns a task instead of rows: ```json theme={null} { "task_id": "01j_example_task", "status": "queued", "poll_after_ms": 1000, "next": { "tool": "tasks", "arguments": { "store": "my-store", "action": "get", "task_id": "01j_example_task" } } } ``` The response also includes `expires_at`, `error_code`, `retryable`, and `correlation_id`. Relative dates such as `SINCE -30d` are evaluated when the query runs, not when you submit it. #### Reading task status and results Call the tool in `next` to continue. Start polling after `poll_after_ms` and back off to about five seconds between checks. | Action | Returns | | - | - | | `get` | Status (`queued`, `running`, `completed`, `failed`, or `cancelled`), progress, failure details, and the exact `next` call | | `result` | `task_id`, `status`, and `result`, which holds the tool response exactly as synchronous mode returns it | | `list` | Your recent tasks with `task_id` and `status`, `per_page` at a time (maximum 25). There's no total count, so keep following `next` until it's `null`, even if a page is empty | | `cancel` | Requests cancellation. Cancellation is cooperative: it doesn't undo work that already finished | For `layersql-query`, the saved result is the same payload a synchronous call returns, including `visualization`, column errors, `truncated`, and `next_offset`. Reading a completed task never reruns the query. To fetch the next page of rows, submit the query again with `offset` set to `next_offset`, and use a new idempotency key if you used one. **Behavior:** * Layers rechecks your access to the store and tool when the task runs and each time you read it. If your access is removed, you can no longer read the result. * Results larger than 1 MiB fail with the `result_too_large` error code instead of being truncated. Narrow the query or lower `limit` and try again. * Completed results expire 24 hours after the task finishes. * `search-batch` responses keep `run_id` and their existing shapes. New runs also return a `task_id`, so you can read them with `tasks` too. ### Batch search testing Use `search-batch` to test search relevance across many queries at once. For example, check a regression list after tuning ranking weights, or compare how a configuration change affects a set of important queries. Runs are deterministic and unjudged: the tool records what each search returned, with no LLM grading. For judged, admin-managed evaluation runs over stored query sets, use `store-evaluations` instead. The tool is action-based, like the publish-request flow: `start` kicks off an asynchronous run and returns a `run_id`, `get` polls progress and reads results, `list` shows recent runs, and `cancel` stops a run. Limits per run: | Limit | Value | | - | - | | Queries | 200 | | Variants | 3 | | Total searches (queries × variants) | 200 | | In-flight runs per store | 3 | | Result retention | 24 hours | #### Starting a run Each entry in `queries` is a plain string or an object with `query`, an optional `expect` (a product id, handle, or title the query is expected to return), `per_page` (1-25, default 10), and an optional `filter_group`. Attributes and every `filter_group` are validated synchronously when you call `start`, so an invalid code fails the start call instead of failing jobs mid-run. Each entry in `variants` accepts a `label`, `bypass_cache`, an `excludeRuleIds` list of ranking rule ids to hold out (see [Testing ranking rule impact](#testing-ranking-rule-impact)), and the same `tuning`, `searchStrategy`, and pipeline bypass options as `search-semantic` (`bypassQueryExpansion`, `bypassIntentModifiers`, `bypassAICuration`, `bypassAIDiversity`, `bypassRankingRules`). Layers validates rule ids in `excludeRuleIds` when you call `start`, so an unknown id fails the start call before any searches run. When `variants` is omitted, the run uses a single baseline variant. Batch searches bypass the results cache by default so comparisons reflect live behavior; set `bypass_cache: false` to opt out. ```json theme={null} { "tool": "search-batch", "arguments": { "store": "my-store", "action": "start", "label": "reranking strength A/B", "queries": [ "running shoes", { "query": "red summer dress", "expect": "8861042344178", "per_page": 10 } ], "variants": [ { "label": "baseline" }, { "label": "no-ranking-rules", "bypassRankingRules": true } ] } } ``` The response returns the `run_id`, the run status, `total_searches`, and the store's current `config_version_id`: ```json theme={null} { "run_id": "01j_example_run", "status": "running", "total_searches": 4, "config_version_id": "cfgv_01j_example", "next": "Poll search-batch action=get with run_id 01j_example_run. Most runs take roughly a few seconds to a minute; partial results are readable while it runs." } ``` If dispatch fails, the response carries `status: "failed"` and an `error` explaining why. #### Reading results Poll with `action: "get"` and the `run_id`. Partial results are readable while the run is in progress; `settled` turns `true` once the run reaches `completed`, `failed`, or `cancelled`. Results paginate with `page` and `per_page` (max 25). | Parameter | Effect | | - | - | | `include: "summary"` | Default. Per-search status, hit count, top result, and expectation outcome | | `include: "results"` | Adds the full result payload for each search | | `include: "diff"` | Per-query comparison across variants. Requires at least two variants | | `only: "failures"` | Only failed searches and searches whose `expect` product wasn't found | | `only: "changed"` | Only queries where the top result differs between variants | Every `get` response also reports `config_changed_during_run`. When `true`, the store's search configuration changed after the run started, so discard the comparison and start a new run. `include: "diff"` tracks the baseline variant's top product across the other variants. For each query, every variant reports the rank of that product in its own results (`compared_product_rank`) and the `rank_delta_from_baseline`. If the product dropped out of a variant's results entirely, the rank is `null` with the reason `baseline_top_product_not_in_variant_results`. Queries with an `expect` product report whether it was found and at what rank: ```json theme={null} { "query": "red summer dress", "variant": "no-ranking-rules", "status": "completed", "total_hits": 42, "top_result": { "id": "8861042344178", "title": "Crimson Wrap Dress", "rank": 1 }, "expectation": { "found": true, "rank": 1 } } ``` A search job that fails is recorded as a failed row with its error message, so `completed + failed` always accounts for every search in the run. Runs and their results are pruned after 24 hours. ### Testing ranking rule impact Use `excludeRuleIds` on `search-semantic` to hold specific [ranking rules](/platform/ranking-relevancy) out of a single search. This answers "is this rule still earning its place?" with one read-only call, instead of disabling the rule in live config, testing, and re-enabling it. Pass an array of ranking rule ids (up to 50). Get ids from `ranking-rules-manage` with `action: "list"`, or from `debug.appliedRankingRules` on a previous debug search. The debug payload reports each applied rule as an `{id, name, type}` object. The tool also accepts `exclude_rule_ids` as an alias. ```json theme={null} { "tool": "search-semantic", "arguments": { "store": "my-store", "query": "running shoes", "excludeRuleIds": ["01JQK5W3N8V7C2RY4F6H9M0TBD"] } } ``` The response echoes an `excluded_ranking_rules` block naming each held-out rule: ```json theme={null} { "excluded_ranking_rules": [ { "id": "01JQK5W3N8V7C2RY4F6H9M0TBD", "name": "Boost new arrivals", "enabled": true } ] } ``` Use the echo to distinguish "the rule was excluded and results didn't change" from "the exclusion didn't take". Behavior to know: * Unknown rule ids fail with a validation error rather than being silently ignored, so an inert exclusion never reads as an inert rule. * Disabled rules are accepted. The echo reports `enabled: false` so you can tell the rule wasn't running anyway. * `bypassRankingRules: true` takes precedence: no rules run at all and the exclusion list has no effect. * Layers treats searches with a non-empty exclusion list as diagnostic, so holdout sweeps stay out of search analytics and zero-result reporting. To compare baseline results against results without a rule in one run, pass `excludeRuleIds` on a `search-batch` variant and read the diff: ```json theme={null} { "tool": "search-batch", "arguments": { "store": "my-store", "action": "start", "label": "prune check: boost new arrivals", "queries": ["running shoes", "trail runners", "walking sneakers"], "variants": [ { "label": "baseline" }, { "label": "without-rule", "excludeRuleIds": ["01JQK5W3N8V7C2RY4F6H9M0TBD"] } ] } } ``` > [!NOTE] > > Pin actions share a single pin budget across all ranking rules. Holding out a pin-heavy rule can let later rules' pins land, so result movement can exceed the excluded rule's own pins. This matches what deleting the rule would do. ### Comparing sort orders `sort-orders-preview` accepts `sort_order_codes` (up to 3) to compare how the same products rank under different sort orders. The response aligns each product's rank across every requested code and includes `rank_deltas` relative to the first code: ```json theme={null} { "tool": "sort-orders-preview", "arguments": { "store": "my-store", "sort_order_codes": ["best-sellers", "price-low-to-high"], "collection_handle": "summer-sale" } } ``` Ranks are computed over a bounded comparison window per sort order (reported in the response as `comparison_window`), not just the requested page. The window catches cases where a product sits on page 1 of one sort order and page 3 of another. A product outside the window reports a `null` rank with the reason `outside_comparison_window`. Use `sort_order_code` (singular) for a plain paginated preview of one sort order. ### Explaining sort order rankings `sort-orders-preview` returns a compact product payload with a 1-based `position` for each product. Image URLs and variant details are omitted to keep responses small. Pass `explain: true` to attach the full ranking explanation to every product on the page. The explanation contains the same sort effects the dashboard preview renders, including matched soft boosts, position movement, lift, and any boost-mode switch. To explain one product, pass `explain_product` with a product ID, GID, handle, or SKU. This requires a singular `sort_order_code`. The tool scans a bounded window of results (up to 500 products) for the product and returns its position and full explanation: ```json theme={null} { "tool": "sort-orders-preview", "arguments": { "store": "my-store", "sort_order_code": "best-sellers", "collection_handle": "summer-sale", "explain_product": "trail-runner-2" } } ``` ### Controlling browse response size The admin `browse` tool returns compact summaries by default so a large catalog page doesn't fill your assistant's context with every variant, image, and inventory location. This changes only the admin MCP tool, not the storefront MCP tool or browse API. | Parameter | Behavior | | - | - | | `view: "compact"` | Default. Each product includes available `id`, `title`, `handle`, `vendor`, `product_type`, `available`, and `price_range` fields, plus any requested `attributes` | | `view: "facets"` | Omits product results; keeps totals, pagination, facets, and other collection metadata | | `view: "full"` | Returns complete product documents and all facet values allowed by your existing attribute selection; ignores `fields` and the facet cap. Can produce very large responses | | `fields` | Replaces the compact product field list with selected top-level keys already present in the response. `id` and requested debug summaries are retained. Does not fetch additional fields or bypass attribute permissions | | `attributes` | Requests specific, validated attributes from the browse pipeline. Use `variants[].price` to return only prices within variant objects; plain `variants.price` retains the existing full-variant behavior | | `facet_values_limit` | Caps each facet's values in compact and facets-only views. Default 50; minimum 1. Display labels are limited to the retained values too | Keep `per_page` unchanged and increment `page` when you continue through a collection. The default page size remains 25, with a maximum of 100; compact mode never drops products to fit a byte budget. Large attributes, banners, explicit field selections, or full responses can still exceed your client's context limit. Request only the detail you need. For example, request vendor facet values without product documents for Acme Outfitters. Use the identifier returned by `list-stores` for your own connection: ```json theme={null} { "tool": "browse", "arguments": { "store": "acme-outfitters", "collection_handle": "all", "view": "facets", "facets": ["vendor"], "facet_values_limit": 3 } } ``` The decoded tool response returns facet values, not per-value product counts, and keeps the existing browse pagination names. `facets_truncated` reports the original value count for each capped facet, not the number removed. Facet ranges, sort metadata, banners, and grid settings are preserved when present: ```json theme={null} { "view": "facets", "resultsPerPage": 25, "totalResults": 250, "page": 1, "totalPages": 10, "facets": { "vendor": ["Acme", "Evergreen", "Northstar"] }, "facets_truncated": { "vendor": 120 }, "sort_order_code": "relevance", "sort_order_defaulted": true } ``` Increase `facet_values_limit` to inspect more values, or request `view: "full"` explicitly. A facet-only response has no `results` key. Compact responses with `debug: true` still include ranking summaries but never raw pipeline metadata. Use the [OAuth connection](#connecting) with `mcp:use`, access to the store, and the `catalog.read` permission. There is no separate browse-specific rate limit; if your connection returns a 429, wait for the retry interval before calling again. Handle MCP tool errors before reading product or facet data. Common failures include missing authentication (401), insufficient store access (403), an unknown store or collection (404), and invalid arguments (422). For example, an unsupported view returns a validation error containing this message: ```text theme={null} view must be one of: compact, facets, full. ``` Correct the view and retry. For access errors, reconnect or ask a store administrator for access; for throttling, wait for the rate-limit reset rather than repeatedly retrying. ### Browsing without a sort order `browse` picks a sort order automatically when you omit `sort_order_code`. It uses the collection's default when one is set. If the collection has no default, it falls back to the store's storefront-visible `relevance` sort order, and then to the first storefront-visible sort order (ordered by display order, then creation time). The call only fails with a 422 when the store has no storefront-visible sort orders at all. The response echoes the resolved sort order so an assistant can confirm what actually ran: | Field | Meaning | | - | - | | `sort_order_code` | The sort order code applied to the browse call | | `sort_order_defaulted` | `true` when Layers picked the fallback, `false` when the caller passed `sort_order_code` or the collection's default was used | Pass `sort_order_code` explicitly to override both the collection default and the fallback. ### Product sequence conditions Use product attributes in `contextual_conditions` and `global_sequence_conditions`, such as `vendor`, `product_type`, `tags`, `available`, `collection_handles`, `price_range.min`, and product metafields. Layers evaluates these conditions against each sequenced product, not a shopper's session. When you use `valueSource: "field"`, the comparison value must also reference a supported product attribute. Sequence conditions reject shopper-context fields, audience references, the `similar` operator, and shopper product-list quantifiers such as `anyMatch`, `noneMatch`, and `stronglyPrefers`. These restrictions apply to single and batch create/update actions and to `update_config` global conditions. Use shopper targeting on a block or merchandising rule instead. ### Publishing product sequences Publishing a product sequence is two-phase. The `publish` action records intent immediately by setting `is_published`, but the sequence only starts serving after a background evaluation confirms it is eligible. A sequence needs at least two searchable products and must satisfy any configured conditions. The evaluation runs immediately after `publish`, `create`, `update`, and single-group `reevaluate` calls and normally settles within seconds. Read `activation_status` in the response instead of the raw `is_published` and `is_active` flags: | Status | Meaning | | - | - | | `active` | Live in search and browse now | | `pending` | Publish intent recorded, effective state not yet recomputed. Re-read with `get` to confirm | | `blocked` | Evaluated and held back. `inactive_reason` says why (`insufficient_active_products` or `conditions_unmet`). This does not clear on its own. Fix the underlying cause, then republish or `reevaluate` | | `unpublished` | No publish intent | For example, publishing a sequence returns its current state: ```json theme={null} { "tool": "product-sequences", "arguments": { "store": "my-store", "action": "publish", "group_id": 42 } } ``` ```json theme={null} { "message": "Product sequence published.", "sequence": { "group_id": 42, "is_published": true, "is_active": false, "activation_status": "pending", "inactive_reason": "pending_evaluation" } } ``` A `pending` response usually resolves within seconds; follow up with `get` to see the settled state. If a sequence was previously blocked, publishing preserves the blocking `inactive_reason` so an assistant can see why the sequence won't activate and fix the cause instead of retrying. `publish` and `unpublish` also accept a `group_ids` array to change many sequences in one call. Prefer this over one call per group when flipping publish intent across a batch: ```json theme={null} { "tool": "product-sequences", "arguments": { "store": "my-store", "action": "publish", "group_ids": [42, 57, 91] } } ``` The response returns a per-group `results` array plus rollup counts: ```json theme={null} { "results": [ { "index": 0, "success": true, "group_id": 42, "evaluation_queued": true }, { "index": 1, "success": true, "group_id": 57, "evaluation_queued": true }, { "index": 2, "success": false, "group_id": 91, "error": "Product sequence not found." } ], "published": 2, "failed": 1 } ``` Each write is its own transaction, so partial results are accurate. Check `results` for per-group errors instead of assuming success from the rollup. `evaluation_queued` reports whether the background eligibility job was dispatched; a `false` value with a `warning` means the status was saved but the evaluation didn't queue and you can retry with `reevaluate`. `unpublish` settles `is_active` synchronously and omits `evaluation_queued`. Call `reevaluate` with a `group_id` to re-run the eligibility check for one sequence; the response includes `evaluation_queued: true` plus the group's current payload. Omit `group_id` to queue a re-evaluation across every sequence in the store. The `list` action returns a slim projection for each group (ids, names, flags, `activation_status`, and `products_count`) without per-group `products` or `contextual_conditions`. Call `get` with a `group_id` when you need the full sequence payload. The `product-sequence-builder` prompt walks an assistant through creating groups in one batch call, setting `is_published` on the create/update payload (which already is the publish step), and verifying with `activation_status`. Select it from an MCP client that surfaces prompts (for example, Claude Desktop) before asking an agent to build sequences. ### Building blocks with the catalog Recommendation blocks combine anchor-dependent strategy types, strategy-specific configuration keys, and rollup-driven readiness. Call `blocks-catalog` before creating or updating a block so an assistant works from the real vocabulary instead of guessing: * **Anchors** — for each anchor type, the allowed `strategy_types` and every strategy key with its title, description, requirements, beta flag, `relationship` (`complement`, `substitute`, or `sequence`), readiness (`ready` and `data_computed_at`), and `config_schema`. The `config_schema` lists each accepted `strategy_config` key with its type, whether it's required, and any allowed values or limits. See [Strategy configuration keys](/platform/blocks/strategies#strategy-configuration-keys) for the current schema. * **Rules** — the block rule vocabulary: condition fields, their operators and allowed values, combinators, and the four action types. * **Fallback modes** — one-line definitions of `replace` and `fill` (see [Fallback chains](/platform/blocks/fallback-chains)). Pass `anchor_type` to scope the response to one anchor. A strategy key with `ready: false` is still computing its first data rollup; a block using it serves its fallback chain until `data_computed_at` is set. The default `detail: "summary"` response keeps payloads bounded. Without a strategy filter, each anchor includes only strategy type, key, requirements, and readiness; a filtered strategy also includes its title, description, and configuration field names. The summary lists only rule operators, combinators, and action names. Use `detail: "full"` for the complete configuration schemas and targeting rule vocabulary, or filter by `anchor_type`, `strategy_type`, or `strategy_key` to keep the response focused. `blocks-manage` validates writes against the same catalog. `strategy_type`, `strategy_key`, and rule action types are enums, and unknown `strategy_config` keys are rejected with a validation error that names the accepted keys and their allowed values. Cross-field errors list the strategy types allowed for the block's anchor, so an assistant can correct a payload in one retry. #### Fallback trees and block validation A block's `fallback_tree` has the shape `[{ id, conditions?, chain: [{ block_id, mode }] }]`. Each branch has an `id`, optional `conditions`, and an ordered `chain` of fallback blocks: ```json theme={null} [ { "id": "us-branch", "conditions": { "combinator": "and", "rules": [ { "field": "context.geo.country", "operator": "eq", "value": "US" } ] }, "chain": [ { "block_id": "01J8A1V2K3M4N5P6Q7R8S9T0VW", "mode": "replace" } ] }, { "id": "default-branch", "chain": [ { "block_id": "01J8B1V2K3M4N5P6Q7R8S9T0VX", "mode": "fill" } ] } ] ``` Use existing block IDs in `chain`. `replace` serves the fallback instead of the primary results; `fill` tops up the primary results with fallback products. For recommendation blocks, `validate_document` applies the same validation rules as publishing, including when it checks the current document without proposed patches. `apply_patch` validates the simulated result before writing and rejects a patch with 422 `InvalidField` when a top-level field touched by that patch is invalid. An unrelated pre-existing invalid field does not prevent a patch to another field. When a manual block uses collection mode, a non-collection anchor requires a non-empty `strategy_config.collection_handle`. A collection-anchored block uses its anchor collection and does not need this handle. ### Anchor-relative filter values In a block rule's `apply_filter`, `promote`, or `demote` action, a `filter_group` expression can take its values from the anchor product instead of a fixed `values` list. Set `value_source: "context"` and leave out `values`: | Field | Description | | :- | :- | | `value_source` | `"static"` (default) uses `values`. `"context"` reads values from the anchor product | | `value_property` | Anchor attribute to read, such as `vendor`, `product_type`, `tags`, or a `named_tags.*` / `metafields.*` path. Defaults to the expression's `property` | | `value_prefix` | Keep only anchor values that start with this string (case-insensitive), for example `season::` | When more than one anchor value resolves (several matching tags, or several cart items), Layers ORs them: `eq` becomes `in` and `neq` becomes `notIn`. If no value resolves, the expression is dropped for that request. `value_source: "context"` requires `anchor_type` `product` or `cart`. `blocks-manage` rejects it for any other anchor, and rejects `value_property` or `value_prefix` unless `value_source` is `"context"`. ```json theme={null} { "rules": [ { "conditions": [], "action": { "type": "apply_filter", "filter_group": { "conditional": "AND", "expressions": [ { "property": "vendor", "operator": "eq", "value_source": "context" }, { "property": "tags", "operator": "in", "value_source": "context", "value_prefix": "collection::" } ] } } } ] } ``` On a unisex anchor tagged `collection::women` and `collection::men`, the second expression matches products tagged with either, so the block returns women's, men's, and unisex products from the anchor's vendor. If you save with an incompatible anchor, `blocks-manage` returns a validation error keyed to the expression, for example `rules.0.action.filter_group.expressions.0.value_source`, and the message names the block's anchor type: `Anchor-relative filter values (value_source "context") read the anchor product, so they need a product or cart anchor; this block's anchor type is 'collection'.` To fix it, change `anchor_type` to `product` or `cart`, or replace the expression with static `values`. ### Previewing blocks `blocks-preview` runs a block's configuration against the live catalog and returns a compact product list without touching stored config. Provide exactly one of: * `block_id` — preview a saved block. This runs the full recommendation pipeline, including the block's [fallback chain](/platform/blocks/fallback-chains). * `data` — preview an inline block definition before saving it. Inline previews run only the primary configuration; `fallback_block_ids` are not executed. Optional parameters: | Parameter | Effect | | - | - | | `anchor_id` / `anchor_handle` | Anchor to preview against. `anchor_handle` resolves a product or collection handle to its ID | | `variant_id` | Anchor variant for variant-aware strategies | | `context` | The storefront-shaped context object, including fields such as `productsInCart`, `customer`, `geo`, and market data. Cart anchors and cart-based rules read `productsInCart` | | `filter_group` | Shopper-applied filter group, merged with filters produced by block rules | | `exclude_product_ids` | Product IDs to exclude from preview results | | `demo_profile_id` | Build context from a store [demo profile](/help/evaluate/test-text-search#create-a-demo-profile-persona) instead of passing raw `context`. Mutually exclusive with `context`; it can be combined with `filter_group` and `exclude_product_ids` | | `sample_anchors` | Run the preview against 1-10 random catalog anchors to sanity-check behavior across the catalog | | `explain` | Attach an execution trace to the response | Both saved and inline previews apply `filter_group` and `exclude_product_ids`. The shopper filter is combined with the block's rule filters rather than replacing them. ```json theme={null} { "tool": "blocks-preview", "arguments": { "store": "my-store", "block_id": "01JBLOCK", "anchor_handle": "classic-white-tee", "demo_profile_id": "01JPROFILE", "explain": true } } ``` The response returns each product as `{ id, handle, title, price, position }` plus the resolved configuration after rules ran (strategy, `strategy_config`, safeguards, and whether a rule hid the block). `processing: true` means the strategy's data rollup is still computing. With `explain: true`, the `trace` lists pipeline events in order: block selection, each rule evaluation and applied action, strategy resolution and readiness, strategy product counts, applied safeguards, exclusions, and fallback traversal with its result. Use the trace to answer "why did this block return these products", for example to spot a rule that unexpectedly matched or a fallback that replaced the primary strategy. ### Reading block performance `blocks-manage` with `action: "list"` returns rolling 7-day performance counters for each block: `impressions_7d`, `clicks_7d`, `ctr_7d`, `purchases_7d`, and `metrics_computed_at`. Pass `sort` (`ctr_7d`, `impressions_7d`, or the default `priority`) to rank blocks by performance, and `anchor_type` to filter the list. A published block with zero impressions usually means the block isn't wired into the theme. Rendering is theme-side, so Layers can't detect a missing Liquid binding. See [Rendering blocks in Liquid](/developers/rendering-blocks-in-liquid). For deeper analysis, query the `blocks` [LayersQL dataset](/platform/layersql/datasets/blocks) through `layersql-query`. ### Example: run an analytics query Analytics is exposed through LayersQL. Ask your assistant to inspect the schema first, then run a query: ```json theme={null} { "store": "my-store", "query": "FROM search_text SHOW COUNT(requests) WHERE num_results = 0 GROUP BY term SINCE -7d" } ``` Call `layersql-schema` to discover available datasets, metrics, and dimensions. Omit `dataset` to get a compact syntax cheat-sheet with clause order, operators, and two example queries. Pass `include_reference: true` for the full syntax reference. Call `layersql-validate-query` with the target `store` and the query to check it before you run it. Validation confirms every metric and dimension exists on the dataset, and errors list the available names so an assistant can correct the query without a retry loop. To render the result as a chart, include a [`VISUALIZE`](/platform/layersql/syntax#visualize-optional) clause in the query. `layersql-query` returns a `visualization` chart config alongside the rows, so an assistant can pick the chart type, x-axis, and series without a second call. `layersql-query` returns 50 rows by default and accepts up to 500 rows per call. Use `columns` to project the result to selected columns. When the row cap is hit, the response sets `"truncated": true` and includes `next_offset`. Pass that value back as `offset` on the next call to page through the remaining rows, or narrow `start_date` and `end_date` to shrink the result set: ```json theme={null} { "store": "my-store", "query": "FROM search_text SHOW COUNT(requests) GROUP BY term SINCE -30d", "limit": 500, "offset": 500 } ``` The `search-health-triage` prompt walks an assistant through triaging zero-result or unhealthy search traffic: discovering metrics with `layersql-schema`, ranking terms by the canonical [`zero_results`](/platform/layersql/datasets/search-text) measure, and splitting catalog-coverage misses (`identifier_lane_misses`) from relevance failures. Select it before asking an agent to investigate search health. The `request-transform-authoring` prompt covers the shape of a [request transform](/platform/request-transforms): `request_types`, the action types accepted by `request-transforms-manage` (`replace_query`, `modify_query`, `add_filter_group`, `set_default_selected_options`, `modify_tuning_parameters`, `override_sort_order`), and the targeting condition vocabulary (`context.*` for session context, `request.*` for the request itself). Select it before asking an agent to author or edit a transform. ### Managing saved reports and dashboards `analytics-manage` reads and writes the same saved reports and dashboards that appear in the Layers dashboard under **Analytics**. Use it when an assistant should turn an ad-hoc LayersQL query into something a merchant can revisit, or assemble a set of reports into a dashboard. * **`resource`** — either `report` (a saved LayersQL query) or `dashboard` (an ordered set of cards). * **`action`** — `list`, `get`, `create`, `update`, or `delete`. Preview a query with `layersql-query` before saving it. Once the rows and `visualization` look right, save the same query string as a report: ```json theme={null} { "store": "my-store", "resource": "report", "action": "create", "report_name": "Zero-result searches (last 7 days)", "report_query": "FROM search_text SHOW COUNT(requests) WHERE num_results = 0 GROUP BY term SINCE -7d VISUALIZE requests TYPE bar" } ``` The response includes the report's `columns`, `rows`, `visualization`, and a `url` deeplink that opens the report in the Layers dashboard. A dashboard is an ordered list of cards. Each card either references an existing report by `report_id` or creates one inline with `query` and `name`. Inline creation runs in a single transaction, so a bad later card leaves no orphan reports. Set each card's `width` to `full`, `half`, or `third`. Layers computes each card's position and size on a 12-column grid from those widths, so do not send raw coordinates: ```json theme={null} { "store": "my-store", "resource": "dashboard", "action": "create", "dashboard_name": "Search health", "is_default": true, "cards": [ { "report_id": "rep_abc123", "width": "half" }, { "query": "FROM search_text SHOW COUNT(requests) SINCE -30d TIMESERIES day VISUALIZE requests TYPE line", "name": "Searches per day (30d)", "width": "half" } ] } ``` `get`, `create`, and `update` responses return every card's rows, `visualization`, `position`, `size`, and per-card truncation flags, plus a `url` deeplink to the dashboard. `list` returns lightweight metadata for reports and dashboards. Setting `is_default: true` on a dashboard unsets the previous default for that store. `create`, `update`, and `delete` require the analytics edit permission on the store. `list` and `get` require the analytics read permission. Deleting a report that is referenced by a dashboard card returns an error. Remove or replace the card first. ### MCP audit log Every write action your assistant performs through the Layers MCP server is recorded alongside dashboard configuration changes in the store's Activity Log. Each MCP entry captures the tool, action, user, store, and timestamp. Review activity in the dashboard under **Settings** → **Access & Security** → **Activity Log**. MCP actions appear in the same feed as configuration edits, so you can see everything that changed in a store in one place. Filter by event, action, or free-text search, and open any entry to inspect its details. The operational context attached to an MCP call is only visible to users with API key management permissions. Lower-privilege users still see that an MCP action happened, but not its raw context. ## Storefront MCP server The Storefront MCP server exposes read-only storefront operations as MCP tools. It uses the same access token as the [Storefront REST API](/help/configuration/manage-api-access), so you can integrate AI assistants into customer-facing experiences. ### Connecting Configure your MCP client with the storefront endpoint and your API token: ``` https://app.uselayers.com/mcp/storefront/v1 ``` Authentication uses the same storefront access token you use for the REST API. Pass it as a bearer token in the authorization header. ### Available tools | Tool | Description | | - | - | | `search-text` | Semantic text search with query understanding and typo tolerance | | `browse` | Browse a collection with sort orders, merchandising, and faceted filtering | | `search-similar` | Find visually and semantically similar products | | `search-autocomplete` | Get predictive search query suggestions | | `facets-get` | Retrieve available filter facets for a collection | | `sort-orders-list` | List available sort orders | | `blocks-recommendations` | Get product recommendations from a configured block. Accepts an optional `variant_id` for variant-aware strategies | | `search-content` | Search non-product content (pages, articles, blogs) | ### Common parameters Most search and browse tools accept these optional parameters: | Parameter | Description | | - | - | | `filter_group` | Nested filter conditions (AND/OR with operators like `eq`, `in`, `gt`, `lt`, `between`, and the geo operators `geoRadius`, `geoPolygon`, `geoBoundingBox`; see [Geospatial filtering](/engine/geospatial-filtering)) | | `facets` | Array of attribute codes to retrieve facet values for | | `pagination` | `{ page, limit }` for paginated results | | `sort_order_code` | Sort order to apply (use `sort-orders-list` to see available codes) | | `attributes` | Array of attribute codes to include in the response | | `context` | Contextual data for personalization (geo, customer, cart, marketing channel) | | `identity` | Session, customer, and device identifiers for behavioral tracking | | `debug` | When `true`, includes the full `_meta` payload (scores, tuning, ranking signals, timings) on the response and each result. Defaults to `false`. Supported on `search-text` and `browse`. | > [!NOTE] > > By default, `search-text` and `browse` strip the `_meta` payload from responses to keep results compact. Pass `debug: true` when you need scoring diagnostics, for example when debugging why a product ranked where it did. > [!NOTE] > > `filter_group`, `facets`, and sort orders only accept scalar attribute codes. Group or container attribute codes are rejected with a validation error that lists the selectable child attributes when they're available. ### Market selection and pricing For `search-text` and `browse`, send market selection inside `context`. When Shopify Markets support is enabled, Layers resolves the market in this order: 1. An explicit `context.market` selector, such as a country code, market handle, numeric ID, or Shopify Market GID. 2. A `context.marketId` that identifies an active market in your store, only when you did not send an explicit selector. 3. The market for `context.geo.country`. 4. Your store's active primary market. An explicit selector takes precedence over `context.marketId`. If the selector does not resolve, Layers falls back to geography and then the primary market, not the supplied market ID. Layers resolves `pricingCountryCode` and `baseCurrencyCode` on the server. It strips client-supplied values before resolving them, so do not use them to override pricing. For the pricing country, an explicit country selector wins when it belongs to the selected market; otherwise Layers uses the shopper's country when the market covers it, then a region in that market. The base currency comes from the store's primary market. See [Shopify Markets](/shopify-integration/shopify-markets) for market settings and pricing behavior. ### Example: text search with debug ```json theme={null} { "query": "running shoes", "attributes": ["title", "handle", "featured_image", "first_or_matched_variant.price"], "pagination": { "page": 1, "limit": 20 }, "debug": true } ``` ## When to use each server * Use the **Layers MCP server** when you want an AI assistant to help manage your store: creating merchandising rules, tuning search behavior, building sort orders, or exploring analytics. * Use the **Storefront MCP server** when you want to integrate AI-powered product discovery into a customer-facing experience. It's also useful when building AI agents that need to search and browse your catalog. If you only need quick read-only answers inside Shopify (zero-result searches, how a product is indexed, a collection's rules or default sort), Shopify Sidekick can use the Layers tools bundled with the Shopify app without any MCP setup. See [Shopify admin extensions](/shopify-integration/shopify-admin-extensions#layers-tools-for-shopify-sidekick). ## Next steps * [Manage API access](/help/configuration/manage-api-access) to create storefront tokens * Learn about [request transforms](/platform/request-transforms) and [merchandising](/platform/merchandising) to understand what you can configure through MCP * Explore the [API reference](/api-reference/search) for the underlying REST endpoints # Layers developer tools and integration options Source: https://docs.uselayers.com/developers/overview Overview of Layers developer tools, including REST APIs, the JavaScript SDK, Liquid integration, and MCP servers for AI assistants. The Layers developer hub contains everything you need to integrate Layers into your commerce applications, from SDKs to AI-powered features. ## Developer resources > [card] [Theme implementation checklist](/developers/theme-implementation-checklist) > > Step-by-step plan for shipping a Layers integration in a Shopify theme. Covers the app embed, search, browse, blocks, banners, QA, and go-live. > [card] [What the app embed handles](/developers/app-embed) > > Reference for what the Layers theme app extension and the SDK manage automatically, so your theme code can focus on UI. > [card] [SDK reference](/sdk/overview) > > ES module SDK for Shopify storefronts with reactive state management and built-in caching. > [card] [MCP servers](/developers/mcp-servers) > > Connect AI assistants to manage stores and query storefronts through Model Context Protocol. > [card] [AI enablement](/platform/ai-enablement) > > Access Layers documentation through AI-friendly formats including llms.txt, markdown URLs, and MCP. ## Getting started Use these tools whether you're building a custom storefront or extending an existing Shopify theme. ### SDK integration The Layers SDK provides full access to the Layers APIs with reactive state management and built-in caching. ```typescript theme={null} import { createSDK } from '@commerce-blocks/sdk' const { data: sdk, error } = createSDK({ storefrontAccessToken: 'your-storefront-token', trackingToken: 'your-tracking-token', currencyCode: 'USD', }) if (error) { console.error('SDK init failed:', error.message) } else { const collection = sdk.collection({ collectionHandle: 'shirts' }) const { data } = await collection.get() if (data) { console.log(data.products) } collection.dispose() } ``` ### AI-assisted development Layers AI enablement provides tools to help you build integrations faster using AI assistants. Access the documentation through an MCP server, llms.txt, and markdown or text formats optimized for AI tools. ## Core capabilities * **SDK integration** — ES module SDK with reactive controllers and built-in caching * **AI-assisted development** — MCP server and AI-friendly documentation formats for faster integration * **Search and discovery** — Product search with autocomplete and predictive suggestions * **Collection merchandising** — Browse and filter products within merchandised collections * **Product recommendations** — Blocks API for personalized recommendations based on behavioral data and similarity * **Reactive state** — Built-in `subscribe()` and `state` for automatic UI updates ## Next steps > [card] [Install the SDK](/sdk/installation) > > Get started with the Layers SDK in your project. > [card] [SDK API reference](/sdk/api-reference) > > Explore the complete SDK API documentation. > [card] [API reference](/api-reference) > > Browse the complete REST API reference. > [card] [AI enablement](/platform/ai-enablement) > > Learn how to enable AI-powered features. > [card] [Error handling](/sdk/error-handling) > > Handle errors gracefully with the Result pattern. # Product schema Source: https://docs.uselayers.com/developers/product-schema Understand the standardized schema Layers expects for Shopify products to maximize search relevance, browsing efficiency, and merchandising precision. ## Product schema overview The product schema is a standardized format that transforms your Shopify product data into an optimized structure for the search and browse engine. ### Catalog scale and limits Layers has no hard limits on the number of products, variants, or SKUs that can be synced and indexed. Layers scales with your catalog and has handled catalogs with millions of SKUs. ## Schema fields The following table outlines the key fields in the product schema, along with their data types, descriptions, and example values: | Field Name | Type | Description | Example Value | | :- | :- | :- | :- | | id | Integer | Unique identifier for the product | `7003338965178` | | title | String | Title of the product | `"SUPREME SEALLINE SEE POUCH SMALL"` | | body\_html | String | HTML content describing the product | `"The Supreme Sealline See Pouch Small is a versatile and..."` | | vendor | String | The product's vendor | `"SUPREME"` | | product\_type | String | Type of the product | `"Accessories"` | | created\_at | DateTime | DateTime when the product was created | `"2022-02-05T01:22:27.000000Z"` | | handle | String | A unique human-friendly string for the product, used in the product's URL | `"supreme-pouch-44370ss18a32-sm"` | | category | Object | The category of a product from Shopify's Standard Product Taxonomy | `{"id": "gid://shopify/TaxonomyCategory/aa-1", "name": "Clothing", "is_leaf": false, "is_root": false, "full_name": "Apparel & Accessories > Clothing"}` | | combined\_listing\_parent\_product\_id | Integer | Product ID of the parent for combined listings | `7003338965178` | | combined\_listing\_role | String | Role in a combined listing | `"PARENT"` | | featured\_media | Object | The featured media. | `{"alt": "The top and bottom view of a snowboard. The top has view is turquoise and black with graphics of\n trees. The bottom view is turquoise with the word hydrogen written in cursive.", "src": "https://cdn.shopify.com/s/files/1/0630/8265/9999/files/Main.jpg?v=1736281499", "width": 1600, "height": 1600, "mediaContentType": "IMAGE"}` | | updated\_at | DateTime | DateTime when the product was last updated | `"2023-10-25T20:47:04.000000Z"` | | published\_at | DateTime | DateTime when the product was published | `"2022-02-05T01:22:27.000000Z"` | | tags | Array of Strings | Tags associated with the product | `["Collection: Best Seller", "Collection:Accessories", "Collection:Supreme Accessories"]` | | images | Array of Objects | Images related to the product. | `[{"alt": "SUPREME POUCH", "src": "https://cdn.shopify.com/", "width": 800, "height": 534, "variant_ids": []}]` | | metafields | Object | Configured metafields for the product | `{"product": {"alias": "SEALLINE SEE POUCH SMALL", "colorway": "BLACK", "styleCode": "SS18A30 BLACK", "yearOfRelease": 2018}}` | | available | Boolean | Availability status of the product | true | | is\_gift\_card | Boolean | Whether the product is a gift card | false | | has\_variants\_that\_require\_components | Boolean | Whether the product has variants that require bundle components (used for bundle products) | false | | published\_on\_web | Boolean | Whether the product is published to the Online Store sales channel | true | | published\_on\_app | Boolean | Whether the product is published to your storefront app sales channel | true | | available\_market\_ids | Array of Integers | Shopify Market IDs the product is currently available in. Populated when [markets sync](/shopify-integration/catalog-sync#markets-sync) is enabled. | `[2001, 2002]` | | price\_range | Object | Price range of the product, including from and to fields | `{"from": 7.97, "to": 7.97, "compare_at_price": 7.97}` | | total\_inventory | Integer | Sum of every variant's `inventory_quantity` across all variants and locations. Untracked variants contribute `0`. Negative values are not clamped. This is a product-level rollup and is not scoped to a location or market. | `42` | | options | Object | Dynamically created object from product options (can be an array of any type, depending on the product configuration). The key is case-sensitive. | `{"Size": ["S", "M", "L"]}` | | original\_options | Object | Dynamically created object from product options (can be an array of any type, depending on the product configuration). The key is case-sensitive. This set of options is unfiltered. | `{"Size": ["S", "M", "L"]}` | | options\_v2 | Array of Objects | Extended options array with swatch and linked metafield data. Preserves Shopify's option ordering and includes visual swatch information (color, image) and linked metafield values for each option value. | See [options\_v2 Structure](/developers/product-schema/variant-data#options_v2-structure) | | named\_tags | Object | Dynamically created object of 'key:value' tags on the product. Keys/values in this object are not included in the `tags` array | `{"YearOfRelease": 2016}` | | calculated | Object | Computed attributes defined in the Layers dashboard. Contains dynamic values from Functions, derived attributes, and legacy computed attributes. Attributes that evaluate to null or an empty string are excluded from this object. | `{"sku_coverage": 0.85, "days_available": 30}` | | selling\_plans | Object | Shopify selling plan groups the product is enrolled in, with a discount and category rollup. Deferred by default. Request it explicitly via `attributes`. See [Selling plans](/developers/product-schema/selling-plans). | `{"max_discount_percentage": 15.0, "categories": ["subscription"], "groups": [{"id": 78129334, "name": "Subscribe & Save", "merchant_code": "subscribe-and-save", "plans": [{"id": 3941002, "name": "Deliver every month", "category": "subscription"}]}]}` | > [!NOTE] > > You can provide type-hints to Named Tags by using the `{key}:{type}:{value}` tag format. Supported types: `number`, `boolean`, and `date`. ## King Linked Options groups Enable [King Linked Options](https://www.uselayers.com/integrations/king-linked-options?utm_source=docs\&utm_medium=referral\&utm_campaign=docs-to-site) and sync the catalog before using its product-card data. In search, browse, or block requests, include `external.king_linked_options.group` in `attributes` alongside the other fields your cards need. Read the group at `results[].external.king_linked_options.group`, not a top-level `linked_options` field. This follows the normal external-attribute projection: requesting the whole `external` object or using the default response also includes synced integration data. The group is an object or `null`; handle an absent integration or empty group without failing the rest of the product card. | Field | Meaning | | - | - | | `groupId` | King group identifier, returned as a string. | | `name` | Group title. | | `hideOnCards` | King's hide-on-collection-cards preference. Your renderer must honor it. | | `values` | Published sibling entries in King's stored order. It can be empty. | | `values[].productId` | Numeric Shopify product ID, or `null` if unavailable. | | `values[].handle` | Product handle used to build a product link. | | `values[].label` | Option label supplied by King. | | `values[].colors` | Zero, one, or two color values for the swatch. | | `values[].image` | Swatch image when no color values are present, otherwise `null`. | | `values[].available` | Availability derived from King's out-of-stock flag at sync time. | | `values[].current` | Whether the entry's product ID matches the product being returned. | Validate that a handle and usable label exist before rendering a link. Use colors when present, otherwise the swatch image or a text fallback. Treat availability as synced display data, not a checkout guarantee. This integration does not merge sibling products into a single result or add swatch UI automatically. Layers refreshes eligible storefront-sourced integration data every six hours, in addition to product resyncs. Missing, inactive, deleted, or invalid groups replace stale group data with `null`; incomplete or failed sync responses keep the previous data. Disabling the integration removes its external attributes through normal integration cleanup. ## API response type consistency The following fields are guaranteed to always be returned as JSON objects (or `null`) in API responses, never as empty arrays. This keeps types consistent for API consumers and prevents type mismatches in strongly-typed clients: * `metafields` - Always an object or `null` * `calculated` - Always an object or `null` * `named_tags` - Always an object or `null` * `category` - Always an object or `null` * `featured_media` - Always an object or `null` * `first_or_matched_variant` - Always an object or `null` * `price_range` - Always an object or `null` When these fields have no data, the API returns `{}` (empty object) or `null`, never `[]` (empty array). The API enforces this behavior at the response level to maintain consistent typing across all endpoints. > [!NOTE] > > Sequential array fields like `tags` and `images` are not affected by this enforcement and continue to return as arrays. ## Data types and formatting * **Integer**: Whole numbers without decimals. * **String**: Textual data, often used for titles or descriptions. * **Decimal**: Numbers with decimal points, typically used for prices. * **Array**: A list of values, used for tags or features. * **Boolean**: A true or false value, indicating binary states such as availability. ## See also * [Variant & Option Data](/developers/product-schema/variant-data) * [Metafields & References](/developers/product-schema/metafields) * [Catalog Sync](/shopify-integration/catalog-sync) # Available attributes for API requests Source: https://docs.uselayers.com/developers/product-schema/api-attributes Product attributes you can request from the Layers Search, Browse, Blocks, and Similar Products APIs, with field types and example values. When making requests to the Search, Browse, Blocks, or Similar Products API, you can use the `attributes` parameter to specify which product fields to include in the response. This lets you optimize response payload size by requesting only the data you need. > [!NOTE] > > Only attributes marked as visible on storefront can be requested in the `attributes` parameter or used in filters. Attributes marked as not visible, such as internal computed fields, will be rejected if included in API requests. See [Visible in API responses](/platform/attributes/attribute-options#visible-in-api-responses) for more details. ## Core product attributes The following attributes are available for all products and can be requested in the `attributes[]` parameter: | Attribute | Description | | :- | :- | | `id` | Unique product identifier (always included) | | `title` | Product title | | `handle` | URL-friendly product handle | | `body_html` | Product description HTML | | `vendor` | Product vendor/brand | | `product_type` | Product type classification | | `tags` | Array of product tags | | `images` | Array of product images | | `available` | Product availability status | | `created_at` | Product creation timestamp | | `updated_at` | Product last update timestamp | | `published_at` | Product publication timestamp | | `price_range` | Product price range object | | `total_inventory` | Sum of every variant's `inventory_quantity` across all variants and the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope) (all locations by default). Product-level rollup, not market-scoped. | | `options` | Available product options (filtered by availability) | | `original_options` | All product options (unfiltered) | | `options_v2` | Extended options array with swatch and linked metafield data | | `metafields` | Product metafields object | | `named_tags` | Parsed key:value tags object | | `calculated` | Computed attributes object | | `category` | Shopify Product Taxonomy category | | `featured_media` | Featured product media | | `is_gift_card` | Gift card indicator | | `has_variants_that_require_components` | Bundle product indicator | | `published_on_web` | Whether the product is published to the Online Store sales channel | | `published_on_app` | Whether the product is published to your storefront app sales channel | | `available_market_ids` | Shopify Market IDs the product is available in (requires markets sync) | | `combined_listing_parent_product_id` | Parent product ID for combined listings | | `combined_listing_role` | Role in combined listing (PARENT/CHILD) | ## Special attributes | Attribute | Description | | :- | :- | | `first_or_matched_variant` | Returns the first available variant or the variant matching applied filters. Must be explicitly requested. | | `variants` | Returns an array of all product variants ordered by position. Each variant has the same fields as `first_or_matched_variant`. Must be explicitly requested. | | `collection_titles` | Array of collection titles the product belongs to. Excluded by default to keep responses small. Must be explicitly requested. Supported by the [Search](/api-reference/search), [Browse](/api-reference/browse), and [Blocks](/api-reference/blocks) APIs. | | `selling_plans` | Selling plan groups the product is enrolled in, with the plans, billing and delivery policies, categories, and max discount percentage. Excluded by default. Must be explicitly requested. See [Selling plans](/developers/product-schema/selling-plans). | ## Example API request ```json theme={null} { "attributes": [ "id", "title", "handle", "images", "price_range", "vendor", "first_or_matched_variant" ], "sort_order_code": "best-selling" } ``` ## Example response with selected attributes ```json theme={null} { "results": [ { "id": 7003338965178, "title": "Premium Cotton T-Shirt", "handle": "premium-cotton-t-shirt", "images": [ { "alt": "Premium Cotton T-Shirt - Front", "src": "https://cdn.shopify.com/s/files/product-front.jpg", "width": 800, "height": 800, "variant_ids": [] } ], "price_range": { "from": 29.99, "to": 34.99, "compare_at_price": 39.99 }, "vendor": "Brand Name", "first_or_matched_variant": { "id": 41234567890123, "title": "Small / Blue", "price": "29.99", "sku": "TSHIRT-BLU-S", "compare_at_price": "39.99", "available": true, "position": 1, "selected_options": [ {"name": "Size", "value": "Small"}, {"name": "Color", "value": "Blue"} ] } } ], "totalResults": 150, "page": 1, "totalPages": 15 } ``` > [!NOTE] > > By default, if no `attributes` parameter is provided, all available attributes are included in the response. Specifying attributes helps reduce response payload size and improve performance. ## Selecting nested fields In addition to top-level attributes, the `attributes` parameter accepts dot-notation paths that let you trim nested objects, slice arrays, and filter collections to just the entries you need. This keeps responses small for storefront tiles and product detail views without making a separate request per shape. Selectors are scoped to the response shape. They do **not** change which products are returned. Use [filters](/engine/filtering) to control the product set; use field selection to control the payload per product. > [!NOTE] > > Field selection is a no-op for plain dotted paths (for example, `variants.price`), so existing integrations keep working. Modifiers (`[]`, `[n]`, `[start:end]`, `[key=value]`) opt you into the trimming behavior described below. ### Selector forms | Selector | What it does | | :- | :- | | `title` | Includes the top-level field. | | `seo.title` | Includes a single nested field on an object. | | `images[:2].src` | Slices the first two images and keeps only the `src` field on each. | | `images[0]` | Returns just the first image. | | `variants[]` | Includes the full array (equivalent to `variants` for the variants list). | | `variants[].id` | Trims every variant object to the listed leaf fields. Combine multiple leaf selectors to keep more than one field. | | `variants[sku=ABC123]` | Keeps only variants whose `sku` equals `ABC123`. | | `variants[sku=ABC,DEF]` | Keeps variants whose `sku` equals `ABC` **or** `DEF`. Values are comma-separated. | | `metafields[namespace=custom]` | Keeps only product metafields under the `custom` namespace. | | `metafields[namespace=custom,greyson]` | Keeps product metafields under any of the listed namespaces. | | `metafields.custom` | Dotted form of the whole-namespace selector. Returns everything under `custom`. | | `metafields.custom.color` | Returns a single metafield key inside a namespace. | | `variants[].inventory[location_id=123]` | Keeps inventory entries for the given location on every variant. | | `first_or_matched_variant.inventory[location_id=123]` | Alias for `first_or_matched_variant.inventory_levels[location_id=123]`. Keeps inventory for the given location on the matched variant while returning the trimmed `inventory_levels` object. | | `variants[].metafields.custom.color` | Keeps only the `custom.color` metafield record on every variant. | | `variants[].metafields[namespace=custom]` | Keeps variant metafield records under the `custom` namespace. | | `first_or_matched_variant.metafields.custom.color` | Keeps only the `custom.color` metafield record on the matched variant. | Multiple selectors that target the same collection are merged. For example, `variants[].id` plus `variants[].price` returns variants trimmed to `{id, price}`. ### Slicing and indexing * `[start:end]` returns the half-open slice, using zero-based positions. * `[n]` returns the single entry at that position, still wrapped in the array. * `[:n]` and `[n:]` are shorthand for "first `n`" and "from `n` onward". * Negative indexes are not supported. Slices and indexes for `variants` use the storefront-visible position order. Hidden variants (for example, B2B-only variants when the request is not B2B) are excluded before the slice is applied. ### Equality filters `[field=value]` keeps only the entries whose `field` equals `value`. Values can be unquoted, single-quoted, or double-quoted. Quote them when the value contains spaces or punctuation. Numeric values compare numerically, so `price=110` matches a stored `110.00`. Pass a comma-separated list to match any of several values: `variants[sku=ABC,DEF]` keeps variants whose `sku` equals `ABC` or `DEF`. Commas inside a quoted value are treated as part of the value, so `variants[sku="A,B"]` matches the single SKU `A,B`. Empty members and trailing commas (for example, `variants[sku=ABC,]`) are rejected as parse errors. Repeating the same filter across multiple selectors unions the value sets in request order. For example, requesting both `metafields[namespace=custom]` and `metafields[namespace=greyson]` returns metafields from both namespaces. Different filter keys on the same collection, or mixing a filter with a positional modifier, still conflict. * For arrays like `variants` and `images`, filtering trims the array in place. The parent product is still returned even if no entries match. * For map-shaped fields like product `metafields` (`{namespace: {key: value}}`) and variant `inventory_levels` (`{location_id: quantity}`), filtering trims the map while preserving its shape. * Filtering on a field that doesn't exist on the entries (or on a hidden internal column) is a no-op rather than an error, so the response shape stays consistent. Equality is the only supported operator. Comparison operators (`>`, `<`, `>=`, `<=`, `!=`), boolean combinators (`AND`/`OR`, `&&`/`||`), and `IN` lists are rejected at validation time. ### Trimming metafields Product `metafields` is a `{namespace: {key: value}}` map, and it accepts two selector spellings: * **Namespace set** — `metafields[namespace=custom,greyson]` returns only the listed namespaces. Use this when you want one or more whole namespaces in a single selector. * **Dotted path** — `metafields.custom` returns the whole `custom` namespace, and `metafields.custom.color` returns just the `color` key inside it. Use dotted form when you want individual keys. A whole-namespace selector subsumes a key selector for the same namespace, so requesting both `metafields.custom` and `metafields.custom.color` returns all of `custom`. Namespaces and keys must consist of letters, digits, `_`, `-`, or `.`. The bracket-then-dot spelling `metafields[namespace=custom].color` is rejected with a `400`. Use the dotted form to reach into a namespace. Products missing a requested namespace or key drop the entry rather than emit `null`, and a product with no metafields at all returns `metafields: {}`. ### Trimming variant metafields Variant `metafields` is a list of `{namespace, key, value, …}` records rather than a map. You can trim it on both `variants[]` and `first_or_matched_variant` with these selectors: | Selector | What it returns | | :- | :- | | `variants[].metafields..` | The single matching record on every variant. | | `variants[].metafields.` | Every record in the namespace on every variant. | | `variants[].metafields[namespace=custom,other]` | Every record in any of the listed namespaces on every variant. | | `variants[].metafields` | The full list on every variant. | | `first_or_matched_variant.metafields..` | The single matching record on the matched variant. | | `first_or_matched_variant.metafields.` | Every record in the namespace on the matched variant. | | `first_or_matched_variant.metafields[namespace=custom]` | Every record in the listed namespaces on the matched variant. | Keep these rules in mind: * Selectors on each root are independent. A `variants[].metafields.*` selector never trims `first_or_matched_variant`, and the reverse is also true. Request both when you need both trimmed. * The trimmed value stays a list with the original record shape. A variant with no matching records returns `metafields: []`. * Namespaces and keys must consist of letters, digits, `_`, `-`, or `.`. Hyphenated and digit-leading keys such as `shopify.color-pattern` are supported. * The `variants[]` form requires the `[]` modifier. A plain dotted path such as `variants.metafields.custom.color` is a no-op and returns the full list, matching the behavior of other plain dotted paths. * You can combine metafield selectors with other variant leaf selectors, such as `variants[].id`. These selectors return a `400` with the [field selector error shape](#validation-and-errors): * Chains deeper than `.`. * Any filter other than `[namespace=…]`, such as `[key=…]`. Keys repeat across namespaces, so a key alone does not identify a record. * Positional modifiers such as `[0]` or `[:2]` on `metafields`, and modifiers on the namespace or key segment. * A dotted path after `[namespace=…]`, such as `variants[].metafields[namespace=custom].color`. Use `variants[].metafields.custom.color` instead. The same selectors work in browse, search, and blocks responses. ### `first_or_matched_variant` and field selection `first_or_matched_variant` is a single object, not a list, so it doesn't accept a bracket modifier of its own. Selectors such as `first_or_matched_variant[sku=SHIRT-RED].price` or `first_or_matched_variant[0].title` return a `400`: ```json theme={null} { "error": "Invalid field selector", "message": "Unsupported modifier on `first_or_matched_variant`. It is a single object, not a list — use the dotted form `first_or_matched_variant.` to select its fields.", "path": "first_or_matched_variant[sku=SHIRT-RED].price" } ``` Use the dotted form, such as `first_or_matched_variant.price`, to select its fields. To read a specific variant by SKU, filter the `variants` list instead (for example, `variants[sku=SHIRT-RED].price`). Modifiers on the supported sub-paths, `first_or_matched_variant.metafields[namespace=…]` and `first_or_matched_variant.inventory[location_id=…]`, keep working as described above. Selecting or filtering which variants appear in `variants` does not change which variant `first_or_matched_variant` chooses. A `variants[].inventory` selector also trims the matched variant's inventory map as a fallback. An explicit `first_or_matched_variant.inventory` selector takes precedence for that map. These inventory selectors do not change which variant is matched, and metafield selectors on `variants[]` and `first_or_matched_variant` remain independent. If a `variants` selector matches no variants, the response can still include the normally matched `first_or_matched_variant`. Its `inventory_levels` value remains an object; when no inventory locations are present, the value is `{}`. ### Validation and errors Each collection may carry only one array modifier across all selectors in a single request. Mixing two modifiers on the same collection (for example, `variants[:2]` and `variants[sku=ABC]` in the same request) returns a `400` with a structured body: ```json theme={null} { "error": "Invalid field selector", "message": "Conflicting modifiers on `variants`. A collection may use only one array modifier (slice, index, `[]`, or filter) across all selectors.", "path": "variants[sku=ABC]" } ``` The same error shape is returned for malformed paths, unsupported operators, negative indexes, and selectors the projection layer cannot execute. Examples include a positional modifier on `metafields` and a dotted chain after `metafields[namespace=…]`. The response points you at the equivalent dotted form that the projection layer can honor. Rejecting these up front avoids silently returning the untrimmed payload. A bracket modifier on a sub-path segment of a map column (for example, `selling_plans.groups[name=Subscribe].plans` or `metafields.custom[key=color]`) is a special case. It does not return a `400`. The predicate is dropped and the request is served as the equivalent dotted form (for example, `selling_plans.groups.plans`), which returns the full set of entries rather than a filtered subset. Use the dotted form directly when you want that behavior, and filter the extra entries client-side if you need to narrow the result. ### Examples Return product tiles with the first two images, only the matched variant's price, and metafields from the `custom` namespace: ```json theme={null} { "attributes": [ "id", "title", "handle", "images[:2].src", "price_range", "variants[sku=TSHIRT-BLU-S].price", "metafields[namespace=custom,greyson]" ] } ``` Return a single metafield key using the dotted form: ```json theme={null} { "attributes": [ "id", "title", "metafields.custom.color" ] } ``` Return one metafield from each variant and a different metafield from the matched variant: ```json theme={null} { "attributes": [ "id", "variants[].id", "variants[].metafields.custom.bucket_listing", "first_or_matched_variant.metafields.other.bucket_listing" ] } ``` Each variant keeps only its `custom.bucket_listing` record, and the matched variant keeps only its `other.bucket_listing` record. Return inventory at a single location for every variant: ```json theme={null} { "attributes": [ "id", "variants[].id", "variants[].inventory[location_id=123]" ] } ``` > [!NOTE] > > Field selection respects [API visibility](/platform/attributes/attribute-options#visible-in-api-responses). Attributes hidden from storefront responses are rejected the same way they would be in a plain `attributes` request. Selectors can never re-expose a hidden field. ## See also * [Product Schema](/developers/product-schema) * [Metafields](/developers/product-schema/metafields) * [Variant & Option Data](/developers/product-schema/variant-data) * [Selling plans](/developers/product-schema/selling-plans) * [Attributes (platform)](/platform/attributes) # Supported Shopify metafield types and access patterns Source: https://docs.uselayers.com/developers/product-schema/metafields Supported Shopify metafield types in Layers, their structure, namespace conventions, and how to access metafield values as searchable product attributes. Metafields extend products with custom structured data. Layers supports the standard Shopify metafield types and provides predictable access patterns for using metafield values as searchable, filterable, and sortable attributes. This page covers the core metafield contract. See these related pages for deeper topics: * [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) — metaobject resolution, nested references, and normalized reference shapes. * [Automatic sequences from metafields](/developers/product-schema/metafields/automatic-sequences) — turn `list.product_reference` metafields into product sequences. * [Available attributes for API requests](/developers/product-schema/api-attributes) — the full list of attributes you can request from the Search, Browse, and Blocks APIs. ## Supported metafield types The product schema supports the following Shopify metafield data types. Layers handles each type correctly for display and filtering: | Type | Description | Example | | :- | :- | :- | | single\_line\_text\_field | A single line of text used for titles, names, or other short descriptions. | `"Limited Edition"` | | multi\_line\_text\_field | Multiple lines of text, typically used for long descriptions or instructions. | `"Care instructions: Machine wash cold, tumble dry low."` | | boolean | True or false value indicating binary states such as availability or inclusion. | `true` | | number\_integer | Whole numbers used for inventory counts, order limits, or other quantities. | `150` | | number\_decimal | Numbers with decimal places, often used for prices, weights, or measurements. | `29.99` | | json | JSON objects used to store structured data such as configurations, specifications, or dynamic content. | `{"alias": "SEALLINE SEE POUCH SMALL", "colorway": "BLACK"}` | | date | Date values formatted as YYYY-MM-DD, often used for production dates, release dates, or promotional periods. | `"2023-09-30"` | | date\_time | DateTime values formatted as ISO 8601, used for time-based events like product launches or sales end times. | `"2024-01-01T00:00:00.000Z"` | | color | Color values formatted as hexadecimal strings, used for product colors or UI elements. | `"#FF5733"` | | file\_reference | Links to file assets, including images, PDFs, or other documents that can be referenced in product displays or additional resources. | `"https://cdn.shopify.com/files/myfile.pdf"` | | product\_reference | Links to other product IDs, allowing cross-referencing of related items. | `"gid://shopify/Product/123456789"` | | variant\_reference | References to specific product variants, allowing differentiation between product options like size or color. | `"gid://shopify/ProductVariant/987654321"` | | collection\_reference | References to collections, used for categorization and dynamic grouping of products. | `"gid://shopify/Collection/456789123"` | | page\_reference | Links to Shopify pages, typically used for additional information or storytelling about a product. | `"gid://shopify/Page/654321987"` | | metaobject\_reference | References to custom metaobjects that can extend product data with additional attributes or structured information. | `"gid://shopify/Metaobject/321654987"` | | url | URLs pointing to external resources, used for additional product details or external documentation. | `"https://example.com/extended-warranty"` | For a complete list of supported metafield types and their properties, refer to the official [Shopify Metafield Data Types documentation](https://shopify.dev/docs/apps/build/custom-data/metafields/list-of-data-types). ## Metafield structure and examples Metafields are organized by namespace and key in a nested object structure. The namespace groups related metafields together, and each key within a namespace contains the metafield value. ### Metafield structure ```json theme={null} { "metafields": { "{namespace}": { "{key}": "{value}" } } } ``` ### Example: custom product metafields ```json theme={null} { "metafields": { "custom": { "material": "100% Organic Cotton", "care_instructions": "Machine wash cold, tumble dry low", "country_of_origin": "USA", "weight_kg": 0.25 }, "product": { "colorway": "Midnight Blue", "style_code": "SS24-TSHIRT-001", "release_date": "2024-03-15", "is_limited_edition": true }, "seo": { "meta_title": "Premium Organic Cotton T-Shirt | Brand Name", "meta_description": "Shop our premium organic cotton t-shirt..." } } } ``` ### Accessing metafields in attributes To create a catalog attribute from a metafield, use dot notation with the full path: | Metafield path | Attribute code | | :- | :- | | `metafields.custom.material` | `metafields.custom.material` | | `metafields.product.colorway` | `metafields.product.colorway` | | `metafields.seo.meta_title` | `metafields.seo.meta_title` | ### Accessing nested metafield object keys When a metafield value is a JSON object, you can create attributes that access nested object keys using dot notation. Shopify namespace and key names can include letters, numbers, underscores, and hyphens; **object keys can contain spaces and special characters**. **Format:** `metafields.{namespace}.{key}.{object_key}` **Example metafield value:** ```json theme={null} { "metafields": { "custom": { "color_family": { "dark orange": "orange", "light blue": "blue", "forest green": "green" } } } } ``` **Attribute codes for nested object keys:** | Object key | Attribute code | | :- | :- | | `dark orange` | `metafields.custom.color_family.dark orange` | | `light blue` | `metafields.custom.color_family.light blue` | | `forest green` | `metafields.custom.color_family.forest green` | **Use cases:** * **Filtering:** Create filterable attributes for nested metafield values to enable faceted navigation (e.g., filter by color family values) * **Faceting:** Display facet counts for nested object values in browse and search results * **Sorting:** Sort products by nested metafield object values * **Merchandising:** Use nested metafield values in collection rules and merchandising logic > [!NOTE] > > Nested object key access supports both `metafields` and `variant_metafields` with the same syntax. Variant metafield example: `variant_metafields.custom.size_details.extra large` ### Structured metafield subfield leaves Shopify's structured metafield types (`money`, `weight`, `volume`, `dimension`, and `rating`, plus their `list.*` variants) decode into JSON objects, not scalars. The parent attribute code is not directly filterable or sortable. You address the scalar leaves inside the object instead. Layers indexes numeric leaves with numeric semantics, so filters and sort orders compare `19.90 < 100.00` correctly. Without this, string ordering would put `"100.00"` before `"19.90"`. The available leaves per type: | Metafield type | Numeric leaves | String leaves | | :- | :- | :- | | `money` | `amount` | `currency_code` | | `weight` | `value` | `unit` | | `volume` | `value` | `unit` | | `dimension` | `value` | `unit` | | `rating` | `value`, `scale_min`, `scale_max` | — | **Example:** a `custom.price` `money` metafield exposes these attribute codes: * `metafields.custom.price.amount`: numeric. Use for range filters and sort orders. * `metafields.custom.price.currency_code`: string. Use as a facet. Filter by amount on a Search or Browse request: ```json theme={null} { "property": "metafields.custom.price.amount", "operator": "gte", "values": [19.9] } ``` Sort by amount ascending: ```json theme={null} { "property": "metafields.custom.price.amount", "direction": "asc" } ``` ### Attribute paths for reference metafields When a metafield is a reference type (such as `metaobject_reference`, `file_reference`, or `taxonomy`), Layers discovers curated nested attribute paths instead of the base metafield code. This gives you access to the specific values within the normalized reference structure that are useful for filtering, sorting, and display. See [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) for the full normalized shapes and every supported attribute path. **Metaobject reference attributes:** For metaobject references, the available attribute paths target the base reference (the metaobject handle), the display name, and individual fields: | Attribute path | Description | | :- | :- | | `metafields.{namespace}.{key}` | The referenced metaobject's handle. Available for `metaobject_reference` and `list.metaobject_reference` definitions where every reference targets a single metaobject definition type. Use this as a facet or filter value to group products by which metaobject they reference. `mixed_reference` is not supported because handles are only unique within one definition type. | | `metafields.{namespace}.{key}.display_name` | The display name of the metaobject | | `metafields.{namespace}.{key}.fields.{field_key}` | A specific field value within the metaobject | **Example:** If you have a `custom.specification` metaobject reference with fields `material` and `finish`, Layers discovers these attribute codes: * `metafields.custom.specification` (the handle of the referenced specification metaobject) * `metafields.custom.specification.display_name` * `metafields.custom.specification.fields.material` * `metafields.custom.specification.fields.finish` > [!TIP] > > When you use the base metaobject-reference path (`metafields.{namespace}.{key}`) as a facet, filter UIs receive raw handles. Set [`enrichFacetMetaobjects`](/api-reference/facets) to `true` on your facet, search, or browse request to also receive a `facetDisplay` map with each handle's `display_name` and `fields` for labels and swatch data. **Media and file reference attributes:** For image and file references, the available paths are: | Attribute path | Description | | :- | :- | | `metafields.{namespace}.{key}.url` | The CDN URL of the referenced file | | `metafields.{namespace}.{key}.alt` | The alt text of the referenced image | **Taxonomy reference attributes:** For taxonomy value references, the available path is: | Attribute path | Description | | :- | :- | | `metafields.{namespace}.{key}.name` | The display name of the taxonomy value | > [!NOTE] > > For `file_reference` and `taxonomy` metafields, the base metafield code (for example, `metafields.custom.hero_image`) is not available as an attribute. Use one of the nested paths (`.url`, `.alt`, or `.name`) instead. For metaobject references, the base code is available as a single-value handle attribute only when every reference targets one metaobject definition type. `mixed_reference` remains unavailable. Layers always excludes transport-only paths such as `__typename`, `.type`, and `.handle` on nested references from attribute creation. ### Example: list-type metafields List metafields (e.g., `list.single_line_text_field`, `list.product_reference`) are stored as arrays: ```json theme={null} { "metafields": { "custom": { "related_colors": ["Red", "Blue", "Green"], "compatible_products": [7003338965178, 7003338965179, 7003338965180], "size_chart": [ {"size": "S", "chest": 36, "length": 27}, {"size": "M", "chest": 38, "length": 28}, {"size": "L", "chest": 40, "length": 29} ] } } } ``` ## See also * [Metaobjects and reference metafields](/developers/product-schema/metafields/metaobjects-and-references) * [Automatic sequences from metafields](/developers/product-schema/metafields/automatic-sequences) * [Available attributes for API requests](/developers/product-schema/api-attributes) * [Product schema](/developers/product-schema) * [Variant & option data](/developers/product-schema/variant-data) * [Catalog sync](/shopify-integration/catalog-sync) # Automatic families from metafields Source: https://docs.uselayers.com/developers/product-schema/metafields/automatic-families Use Shopify product-list or collection reference metafields to automatically create and maintain product families in Layers without curating them in the dashboard. Layers can build [product families](/platform/product-families) automatically from Shopify metafields. Configure which metafields to watch, and Layers groups eligible products into families during catalog sync. Use this when an existing Shopify metafield already encodes "these products belong together". Two metafield types are supported: | Metafield type | How products are grouped | Typical use | | - | - | - | | `list.product_reference` | The product that owns the metafield and the products it lists form one family | A *Related styles* or *Color siblings* list maintained on each product | | `collection_reference` | Every product that points at the same collection forms one family | A *Style* metafield where each product references a collection that represents its style | A collection reference works as a shared style key. Layers groups the products whose metafield points at the same collection. It does not add every product inside that collection to the family. ## How it works ### Product list metafields 1. You configure one or more metafield namespace/key pairs in **Settings → Product Families**. 2. During a bulk catalog import or a product webhook sync, Layers reads the configured metafields on each product. 3. Layers starts with the product that owns the metafield and the products it references. 4. Products already assigned to a manual or attribute-driven family, or to a metafield family from a different key, stay in their existing family. 5. Layers creates or updates the family named `Auto: {namespace}.{key}` only when at least two eligible products remain. 6. Layers sorts eligible product IDs before building the family, so the same set of products always maps to the same family regardless of metafield ordering. ### Collection reference metafields 1. You configure the metafield in **Settings → Product Families**, the same way as a product list metafield. 2. During catalog sync, Layers reads the referenced collection on each product. 3. Products that reference the same collection join one family named `Auto: {namespace}.{key} (Collection {collection ID})`. Products that reference a different collection join a different family. 4. The family becomes active once at least two products belong to it. A family with a single product stays in draft. 5. Products already assigned to a manual or attribute-driven family, or to a metafield family from a different key, stay in their existing family. When you change a product's collection reference in Shopify, Layers moves only that product to the family for the new collection. When you clear the value, Layers removes the product from its family. A family left with one product returns to draft, and an empty family is deleted. ## Configure family metafields 1. Go to **Settings → Product Families**. 2. In the **Family Metafields** card, click **Add Metafield**. 3. Select the metafield from the combobox. Only `list.product_reference` and `collection_reference` metafields produce families; other types are ignored. 4. Click **Save**. 5. Layers backfills families from existing metafield values as soon as you save. You don't need to trigger a catalog resync. You can configure multiple metafields. Each is handled as a separate source, and can create families from products that are not already assigned to a higher-priority family. ## Examples ### Product list example Given a `custom.related_styles` metafield on three products that all reference each other: | Product | `custom.related_styles` value | | - | - | | `1001` | `[1002, 1003]` | | `1002` | `[1001, 1003]` | | `1003` | `[1001, 1002]` | Assuming none of these products already belongs to another family source, Layers creates a single family **Auto: custom.related\_styles** containing products `1001`, `1002`, and `1003`. The owning product is included, and the sorted product IDs collapse to one family regardless of which product is being processed. ### Collection reference example Given a `custom.style` metafield that references a collection on four products: | Product | `custom.style` value | | - | - | | `1001` | Collection `501` | | `1002` | Collection `501` | | `1003` | Collection `501` | | `1004` | Collection `502` | Layers creates an active family for collection `501` containing products `1001`, `1002`, and `1003`. Product `1004` is the only product that references collection `502`, so its family stays in draft until another product references the same collection. Other products that belong to collection `501` in Shopify but don't reference it in `custom.style` are not added. ## Conflict resolution * If a product is moved into a new metafield-driven family for the same `namespace.key`, Layers removes it from any older metafield family for that same key. A family left with fewer than two products is deleted. * A product already assigned to a manual or attribute-driven family stays in that family. * If a product is already assigned to a metafield family from a different key, the first key to claim it keeps the product. Other keys can still create families from their remaining eligible products when at least two products remain. ## Removing metafields from the config When you remove a metafield from the **Family Metafields** config (or clear it entirely), Layers cleans up the families it previously produced: * Memberships in metafield-sourced families for the removed `namespace.key` are deleted. * Families left with no members are deleted. * Families left with only one member are demoted to draft. * Manual and attribute-sourced families are not touched. Cleanup runs as part of the same backfill job that reconciles attribute-driven families. Removing a metafield entry reclaims its families immediately, without waiting for the next product sync. ## Limitations * Only Shopify metafields of type `list.product_reference` or `collection_reference` produce families. * A family must contain at least two unique products to be created. * Metafield-driven families are read-only in the Product Families dashboard. To change their membership, edit the underlying metafield values on your products in Shopify. ## See also * [Product families](/platform/product-families) * [Create a product family](/help/product-families/create-product-family) * [Automatic sequences from metafields](/developers/product-schema/metafields/automatic-sequences) * [Metafields](/developers/product-schema/metafields) # Automatic sequences from metafields Source: https://docs.uselayers.com/developers/product-schema/metafields/automatic-sequences Use Shopify list.product_reference metafields to automatically create and maintain product sequences in Layers without manual configuration in the dashboard. Layers can create product sequences automatically from Shopify metafields. You configure which metafields trigger automatic sequence creation in the dashboard at **Settings > Sequences**. ## Configuration options Each sequence metafield configuration requires: * **Namespace**: The metafield namespace (e.g., `layers`, `custom`) * **Key**: The metafield key (e.g., `global_sequence`, `related_products`) * **Type**: Must be `list.product_reference` in Shopify * **Includes current product**: Whether the metafield value already contains the current product ## Default configuration By default, Layers recognizes the `layers.global_sequence` metafield: ``` Namespace: layers Key: global_sequence Type: list.product_reference Includes current product: Yes ``` When the `layers.global_sequence` metafield is present on products, Layers creates a global sequence named "Auto: layers.global\_sequence" during bulk data synchronization. The metafield value should contain an array of product references that should be grouped together in the sequence. Only active products are added to automatic sequences. Archived, draft, and unlisted products in a metafield list are skipped, and a product that isn't active doesn't create or change a sequence from its own metafield. A status change alone doesn't immediately update an existing sequence; membership is reconciled when a catalog sync processes the configured metafield. A product can belong to only one global sequence, and the first sequence to claim it keeps it. If a metafield list names a product that already belongs to another global sequence, Layers leaves that product where it is and builds the new sequence from the remaining products. A sequence needs at least two products, so a list that doesn't have two available products creates no sequence. When several active products in the same sequence carry the configured metafield, the one with the lowest Shopify product ID owns the sequence. A lower-ID member that doesn't carry the configured metafield isn't an owner. The owner's list sets the members and their order, and lists on other carriers don't change the sequence. If the owner is archived, the next eligible carrier can take over when a catalog sync processes the change. To change a sequence, update the owner's list. ## Custom configurations You can add more sequence metafield configurations for different use cases. For example, a "related products" metafield: ``` Namespace: custom Key: related_products Type: list.product_reference Includes current product: No ``` When "includes current product" is disabled, Layers prepends the current product to the metafield value when creating the sequence. This is useful when the metafield contains only related products, not the product itself. When this setting is enabled, Layers also prepends the current product to any nonempty list that omits it. When disabled, Layers continues to prepend the current product even when the list is empty. Each configured metafield creates sequences named as `Auto: {namespace}.{key}` (e.g., "Auto: custom.related\_products"). > [!NOTE] > > Automatic sequence creation via metafields only processes during bulk operations, not during incremental product updates. ## See also * [Product sequences](/platform/sequences) * [Create a product sequence](/help/sequences/create-product-sequence) * [Metafields](/developers/product-schema/metafields) # Metaobjects & reference metafields Source: https://docs.uselayers.com/developers/product-schema/metafields/metaobjects-and-references How Layers resolves metaobject references, media references, taxonomy values, and nested reference chains into a normalized shape. Layers supports Shopify metaobjects, so you can use the custom data structures defined in your Shopify admin. When a product metafield references a metaobject, Layers automatically resolves the complete metaobject data from a local cache. This gives you access to all fields defined on the metaobject, including nested metaobject references up to 5 levels deep. All reference-type metafields are normalized into a consistent, predictable structure. You always receive the same shape of data regardless of how Shopify returns the raw reference. ## Supported reference types The schema supports the following reference types with full data normalization: | Reference Type | Description | | :- | :- | | `metaobject_reference` | Single reference to a custom metaobject | | `list.metaobject_reference` | List of references to custom metaobjects | | `file_reference` | Reference to a file asset (image, video, or document) | | `product_reference` | Single reference to another product | | `list.product_reference` | List of references to other products | | `variant_reference` | Single reference to a product variant | | `collection_reference` | Single reference to a collection | | `page_reference` | Single reference to a Shopify page | ## Normalized reference shapes Each reference type is normalized into a small, consistent object. Transport-only fields like `__typename` are always removed. The shape you receive depends on the type of referenced resource. **Metaobject references** are resolved into a structure with the metaobject's core identifiers and a key-value map of its fields: | Field | Type | Description | | :- | :- | :- | | `id` | String | The Shopify GID of the metaobject | | `type` | String | The metaobject definition type | | `handle` | String | The metaobject handle | | `display_name` | String or null | The display name of the metaobject | | `fields` | Object | Key-value map of resolved field data | **Media image references** (including `file_reference` metafields that point to images) are normalized to: | Field | Type | Description | | :- | :- | :- | | `id` | String | The Shopify GID of the media image | | `url` | String | The CDN URL of the image | | `alt` | String or null | The alt text for the image | **Taxonomy value references** are normalized to: | Field | Type | Description | | :- | :- | :- | | `id` | String | The Shopify GID of the taxonomy value | | `name` | String | The display name of the taxonomy value | **Video references** are normalized to: | Field | Type | Description | | :- | :- | :- | | `id` | String | The Shopify GID of the video | | `url` | String | The URL of the first video source | ## Structured metaobject field leaves When a metaobject field uses one of Shopify's structured types (`money`, `weight`, `volume`, `dimension`, or `rating`), Layers exposes the field's scalar leaves as attribute paths instead of the raw object. Numeric leaves are indexed with numeric semantics, so filters and sort orders on them compare values as numbers. The same leaves are available whether the metaobject field is a single value (`money`, `weight`, `volume`, `dimension`, `rating`) or a list (`list.money`, `list.weight`, `list.volume`, `list.dimension`, `list.rating`). The leaf path is identical in both cases. | Field type | Leaf path suffix | Value type | | :- | :- | :- | | `money`, `list.money` | `.fields.{field_key}.amount` | number | | `weight`, `volume`, `dimension` (and their `list.*` variants) | `.fields.{field_key}.value` | number | | `rating`, `list.rating` | `.fields.{field_key}.value` | number | **Example:** a `custom.badge` metaobject reference with a `price` money field on the metaobject exposes: * `metafields.custom.badge.fields.price.amount`: filterable and sortable as a number. Filter products whose badge price is at least 20: ```json theme={null} { "property": "metafields.custom.badge.fields.price.amount", "operator": "gte", "values": [20] } ``` ### List-valued leaves For `list.*` structured fields, a single metaobject holds an array of values on that field. Filters match when any value in the list satisfies the condition. Facet counts include every value across the list. Sort orders collapse a product's list to its minimum value in both `asc` and `desc` directions; use single-valued structured fields when you need a strict descending order. ## Nested metaobject resolution When a metaobject field references another metaobject (via `metaobject_reference` or `list.metaobject_reference`), Layers automatically resolves the nested reference from its local cache. This happens recursively up to 5 levels deep, with circular reference protection to prevent infinite loops. Nested resolution is useful for data models where metaobjects reference other metaobjects. For example, a "Product Spec" metaobject that references a "Material" metaobject, which in turn references a "Certification" metaobject. Non-reference fields are returned as their plain values (strings, numbers, etc.). If a referenced metaobject is not found in the cache, the reference data from Shopify is still normalized into the standard shape. ## Example: metaobject reference response ```json theme={null} { "metafields": { "custom": { "color_swatch": { "id": "gid://shopify/Metaobject/123456", "type": "color_swatch", "handle": "midnight-blue", "display_name": "Midnight Blue", "fields": { "color": "#191970", "name": "Midnight Blue", "hex_code": "#191970" } } } } } ``` ## Example: list metaobject reference response ```json theme={null} { "metafields": { "custom": { "available_colors": [ { "id": "gid://shopify/Metaobject/111", "type": "color_swatch", "handle": "red-swatch", "display_name": "Red", "fields": { "color": "#FF0000", "name": "Red" } }, { "id": "gid://shopify/Metaobject/222", "type": "color_swatch", "handle": "blue-swatch", "display_name": "Blue", "fields": { "color": "#0000FF", "name": "Blue" } } ] } } } ``` ## Example: media image reference response ```json theme={null} { "metafields": { "custom": { "hero_image": { "id": "gid://shopify/MediaImage/123456", "url": "https://cdn.shopify.com/s/files/hero-image.jpg", "alt": "Product hero image" } } } } ``` ## Example: nested metaobject reference response In this example, a product has a "material" metafield that references a Material metaobject, which itself has a "certification" field referencing a Certification metaobject: ```json theme={null} { "metafields": { "custom": { "material": { "id": "gid://shopify/Metaobject/500", "type": "material", "handle": "organic-cotton", "display_name": "Organic Cotton", "fields": { "name": "Organic Cotton", "weight": "150gsm", "certification": { "id": "gid://shopify/Metaobject/600", "type": "certification", "handle": "gots-certified", "display_name": "GOTS Certified", "fields": { "name": "Global Organic Textile Standard", "level": "Grade A", "url": "https://example.com/gots" } } } } } } } ``` > [!NOTE] > > Metaobject data is resolved from a local cache that is kept in sync with Shopify via webhooks. If a referenced metaobject is not found in the cache, Layers normalizes the original reference data from Shopify's GraphQL response into the standard shape, or falls back to the numeric ID if no reference data is available. ## See also * [Metafields](/developers/product-schema/metafields) * [Metaobjects & Metafields cache and access](/shopify-integration/metaobjects-metafields/cache-and-access) * [Available attributes for API requests](/developers/product-schema/api-attributes) # Selling plans Source: https://docs.uselayers.com/developers/product-schema/selling-plans How Shopify selling plan groups are synced onto Layers products, the shape of the selling_plans attribute, and the filters they enable. Layers syncs each product's Shopify [selling plan groups](https://shopify.dev/docs/api/admin-graphql/latest/objects/SellingPlanGroup) into a single `selling_plans` attribute on the product. Use it to display subscription, pre-order, and try-before-you-buy offers alongside product data, and to filter or facet by the plans a product is enrolled in. ## When to use selling plans Request `selling_plans` when you need to: * Show subscribe-and-save, pre-order, or try-before-you-buy badges on product tiles or PDPs. * Display billing intervals, discounts, and plan options next to a product's price. * Restrict a search, browse, or block to products enrolled in a specific plan group or category. The `selling_plans` attribute is **deferred**: it is only included in API responses when you explicitly list it in the `attributes` array. See [Available attributes for API requests](/developers/product-schema/api-attributes). ## Structure `selling_plans` is an object with a top-level rollup and a `groups` array. Products with no selling plans return an empty block: `{"max_discount_percentage": null, "categories": [], "groups": []}`. | Field | Type | Description | | :- | :- | :- | | `max_discount_percentage` | Number \| null | Highest percentage discount across all plans on the product. `null` when no plan uses a percentage adjustment. | | `categories` | Array of Strings | Sorted, deduplicated list of humanized categories across every group (for example, `subscription`, `pre-order`, `try before you buy`). | | `groups` | Array of Objects | One entry per selling plan group the product is enrolled in. | ### Group fields | Field | Type | Description | | :- | :- | :- | | `id` | Integer | Numeric Shopify `SellingPlanGroup` id. | | `name` | String | Merchant-facing group name. | | `merchant_code` | String | Stable code merchants use to reference the group. | | `app_id` | String \| null | Identifier of the Shopify app that owns the group (for example, `shopify_subscriptions`). | | `summary` | String \| null | Short group summary. | | `options` | Array of Strings | Option labels shown on the storefront (for example, `["Delivery every"]`). | | `categories` | Array of Strings | Humanized categories present on the group's plans. | | `max_discount_percentage` | Number \| null | Highest percentage discount across the group's plans. | | `plans` | Array of Objects | Individual selling plans in the group. | ### Plan fields | Field | Type | Description | | :- | :- | :- | | `id` | Integer | Numeric Shopify `SellingPlan` id. | | `name` | String | Plan name shown to customers. | | `description` | String \| null | Plan description. | | `category` | String \| null | Humanized category (`subscription`, `pre-order`, `try before you buy`, or another humanized value). | | `options` | Array of Strings | Option values shown on the storefront (for example, `["1 month"]`). | | `billing` | Object \| null | Billing policy. See [Billing and delivery policies](#billing-and-delivery-policies). | | `delivery` | Object \| null | Delivery policy. Same shape family as `billing`. | | `pricing` | Object \| null | First pricing policy applied from the initial cycle: `{adjustment_type, adjustment_value}`. Later `afterCycle` adjustments are handled by Shopify at checkout and are not surfaced. | | `inventory_reserve` | String \| null | Lowercased inventory reservation strategy from Shopify (for example, `on_sale`, `on_fulfillment`). | ### Billing and delivery policies Each policy has a `type` of `recurring` or `fixed`. For `recurring` policies: | Field | Type | Description | | :- | :- | :- | | `interval` | String | Lowercased interval (`day`, `week`, `month`, `year`). | | `interval_count` | Integer | Number of intervals between cycles. | | `min_cycles` | Integer \| null | Minimum cycles the customer must complete. | | `max_cycles` | Integer \| null | Maximum cycles before the plan ends. | | `cutoff` | Integer \| null | Cutoff, in intervals, for changing an upcoming cycle. | For `fixed` policies, Layers surfaces the fields Shopify returns for that policy shape, such as `fulfillment_trigger`, `fulfillment_exact_time`, `cutoff`, `remaining_balance_charge_trigger`, `remaining_balance_charge_exact_time`, `remaining_balance_charge_time_after_checkout`, and a `checkout_charge` object with `{type, value}`. ## Requesting selling plans Add `selling_plans` to the `attributes` array on any Search, Browse, Blocks, or Similar Products request. You can also request nested paths via [field projection](/developers/product-schema/api-attributes#field-projection). ```json theme={null} { "attributes": [ "id", "title", "price_range", "selling_plans" ] } ``` Return only the rollup and each group's name and discount: ```json theme={null} { "attributes": [ "id", "title", "selling_plans.max_discount_percentage", "selling_plans.categories", "selling_plans.groups.name", "selling_plans.groups.max_discount_percentage" ] } ``` ### Example response ```json theme={null} { "id": 7003338965178, "title": "Premium Coffee Beans", "selling_plans": { "max_discount_percentage": 15.0, "categories": ["subscription"], "groups": [ { "id": 78129334, "name": "Subscribe & Save", "merchant_code": "subscribe-and-save", "app_id": "shopify_subscriptions", "summary": "Save on every order", "options": ["Delivery every"], "categories": ["subscription"], "max_discount_percentage": 15.0, "plans": [ { "id": 3941002, "name": "Deliver every month", "description": "Cancel any time", "category": "subscription", "options": ["1 month"], "billing": { "type": "recurring", "interval": "month", "interval_count": 1, "min_cycles": null, "max_cycles": null }, "delivery": { "type": "recurring", "interval": "month", "interval_count": 1, "cutoff": null }, "pricing": { "adjustment_type": "percentage", "adjustment_value": 15.0 }, "inventory_reserve": "on_sale" } ] } ] } } ``` ## Filterable attributes Every store is seeded with the following attributes so you can filter and facet by selling plans without any dashboard setup. Storefront faceting on these attributes is disabled by default. Enable it in the dashboard when you want to expose a plan filter to shoppers. | Attribute | Type | Description | | :- | :- | :- | | `selling_plans.group` | String | Selling plan group `name`. | | `selling_plans.category` | String | Humanized plan category (`subscription`, `pre-order`, `try before you buy`, or another humanized value). | | `selling_plans.merchant_code` | String | Group `merchant_code`. | | `variants.has_selling_plan` | Boolean | Variant is enrolled in at least one selling plan group. Set per variant. | | `variants.requires_selling_plan` | Boolean | Variant can only be purchased through a selling plan. Set from the product-level `requiresSellingPlan` value on Shopify. | Filter example: return only products enrolled in a specific group: ```json theme={null} { "filters": { "conditional": "and", "expressions": [ { "property": "selling_plans.group", "operator": "eq", "values": ["Subscribe & Save"], "type": "string" } ] } } ``` ## Sync behavior * Selling plan groups sync per product. When a product's `sellingPlanGroupsCount` is greater than zero, or the product already has stored groups that need to be pruned, Layers pages through `product.sellingPlanGroups` and merges each page into the product's `selling_plans` attribute. * Groups with more than one page of plans are followed to completion so the stored block is never truncated. * Existing stores pick up selling plan data on each product's next sync. There is no one-time backfill. * `variants.requires_selling_plan` mirrors the product-level `requiresSellingPlan` value from Shopify. `variants.has_selling_plan` is written per variant from Shopify's `ProductVariant.sellingPlanGroupsCount`, and is cleared when the product has no groups. ## MCP access The [MCP `product` resource](/developers/mcp-servers) includes `selling_plans` for every product. Products with no plans return the empty block `{"max_discount_percentage": null, "categories": [], "groups": []}`. ## See also * [Product schema](/developers/product-schema) * [Available attributes for API requests](/developers/product-schema/api-attributes) * [Variant and option data](/developers/product-schema/variant-data) # Variant & option data Source: https://docs.uselayers.com/developers/product-schema/variant-data Understand variant-level data fields including first_or_matched_variant, the full variants array, and the options_v2 structure. ## Variant data with first\_or\_matched\_variant The `first_or_matched_variant` field provides variant-level data in search and browse responses. Use it to display variant-specific information like the matched variant's price, SKU, or selected options. ### When to use first\_or\_matched\_variant `first_or_matched_variant` returns the most relevant variant for the current request. The system selects a variant using the following priority: 1. **Explicit variant filters** — If option or variant filters are applied, the filtered variant is returned. When an `available` filter is combined with option or variant filters, the returned variant is one that matches those filters and is in stock. See [Variant-level conditions](/engine/filtering#variant-level-conditions). 2. **Keyword-matched variant** — During text search, if keyword features target variant-scoped attributes (options, variant metafields, or variant fields), the variant with the highest keyword relevance score is returned. To prevent false matches, variant selection requires keyword scores to exceed a minimum relevance threshold. 3. **Pin-level default variant** — If the product is pinned (via a merchandising rule or a ranking rule) and the pin has default variant options configured, the variant matching those options is returned. See [default variant for pins](/platform/ranking-relevancy#default-variant-for-pins). 4. **Default selected options** — If `defaultSelectedOptions` is specified, the first matching variant is returned. 5. **Confident semantic match** — If semantic search matched a specific variant and the match is confident, that variant is returned. A match is confident when the variant is meaningfully more relevant to the query than the product as a whole, compared within the same match type (text-to-text or image-to-image). When multiple variants score similarly, or when there is no product-level match of the same type to compare against, the system falls through to the position fallback. 6. **Position fallback** — The first available variant by position is returned. Common use cases include: * Displaying the correct variant image when filtering by color * Showing the matched variant's price when filtering by size * Surfacing the keyword-relevant variant when searching for a specific option value * Accessing variant-specific metafields See [Keyword-matched variant selection](/platform/ranking-relevancy#keyword-matched-variant-selection) for more details. ### Variant schema fields | Field Name | Type | Description | | :- | :- | :- | | id | Integer | Unique identifier for the variant | | title | String | Title of the variant (typically the option values combined) | | price | String | Price of the variant | | sku | String | SKU of the variant | | barcode | String | Barcode of the variant (typically UPC, EAN, or ISBN). Returns an empty string when the variant has no barcode. | | compare\_at\_price | String | Compare at price of the variant (original price before discount) | | available | Boolean | Availability status of the variant. Calculation can be configured at the store level. See [Variant Availability Calculation](/shopify-integration/catalog-sync#variant-availability-calculation) for details. | | in\_stock\_location\_ids | Array of Integers | **Sort-only field.** Array of location IDs where the variant has available inventory (available > 0). This field can be used in sort orders for location-based product demotion but is not filterable and is not included in API responses. | | position | Integer | Position of the variant in the product's variant list | | selected\_options | Array of Objects | The selected options for this variant (e.g., Size: "M", Color: "Blue") | | featured\_media | Object | The featured media for this variant (if variant-specific media exists) | | created\_at | DateTime | DateTime when the variant was created | | updated\_at | DateTime | DateTime when the variant was last updated | | requires\_selling\_plan | Boolean | Whether the variant requires a selling plan (subscription) | | has\_selling\_plan | Boolean | Whether the variant has an associated selling plan | | inventory\_quantity | Integer | Total inventory quantity across the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope), which is all locations by default (only included when Expose Variant Inventory is enabled) | | inventory\_policy | String | Inventory policy for the variant: `DENY` (stop selling when out of stock) or `CONTINUE` (allow overselling). Variants with inventory tracking disabled in Shopify are always reported as `CONTINUE`. Only included when Expose Variant Inventory is enabled. | | inventory\_levels | Object | Object mapping location IDs to available inventory quantities (e.g., `{"1001": 5, "1002": 10}`). Returns empty object `{}` when no inventory data exists. Only included when Expose Variant Inventory is enabled. | > [!NOTE] > > The `inventory_quantity`, `inventory_policy`, and `inventory_levels` fields only appear in variant data when the store has the **Expose Variant Inventory** setting enabled. Location IDs in `inventory_levels` are returned as string keys. The inventory location scope narrows aggregate `inventory_quantity`, not the `inventory_levels` map. The map includes every location unless an explicit field projection trims it. It remains an object. If none of the requested locations has inventory data for the variant, `inventory_levels` is `{}`. ### Example first\_or\_matched\_variant response ```json theme={null} { "first_or_matched_variant": { "id": 41234567890123, "title": "Medium / Blue", "price": "49.99", "sku": "TSHIRT-BLU-M", "barcode": "0123456789012", "compare_at_price": "59.99", "available": true, "position": 2, "selected_options": [ { "name": "Size", "value": "Medium" }, { "name": "Color", "value": "Blue" } ], "featured_media": { "alt": "Blue T-Shirt", "src": "https://cdn.shopify.com/s/files/variant-image.jpg", "width": 800, "height": 800, "mediaContentType": "IMAGE" }, "created_at": "2024-01-15T10:30:00.000000Z", "updated_at": "2024-03-20T14:45:00.000000Z", "requires_selling_plan": false, "has_selling_plan": false, "inventory_quantity": 15, "inventory_policy": "DENY", "inventory_levels": { "1001": 5, "1002": 10 } } } ``` > [!NOTE] > > To include `first_or_matched_variant` in API responses, you must explicitly request it in the `attributes` array parameter. See the [Available Attributes for API Requests](/developers/product-schema/api-attributes) section. > [!WARNING] > > When combining `price_range` with option filters in search or browse operations, `price_range.from` and `price_range.to` represent the minimum and maximum prices across all variants of a product. They do not reflect the price of the variant matching your selected options. For accurate price-based sorting and filtering with option filters, use `variants.price` instead, which selects the appropriate variant based on applied filters. ## All variants with variants The `variants` attribute provides access to all product variants in a single API response. This field returns an array of all variants for a product, ordered by position. Use it to display complete variant selection interfaces or build custom product pages. ### When to use variants Use the `variants` attribute when you need to display all available options for a product at once. For example, build a variant selector with all sizes and colors, show a complete price range, or create custom comparison interfaces. The `variants` attribute is most useful on product detail pages. ### How variants differs from first\_or\_matched\_variant While `first_or_matched_variant` returns a single variant (either the first available or the one matching applied filters), the `variants` attribute returns **all variants** for the product as an array. Both attributes return the same field structure for each variant, but `variants` gives you complete visibility into all product options. | Feature | first\_or\_matched\_variant | variants | | :- | :- | :- | | Return Type | Single variant object | Array of variant objects | | Use Case | Display matched/default variant | Display all available variants | | Ordering | N/A (single variant) | Ordered by position | | Fields | Variant schema fields | Same variant schema fields | ### Variants array structure The `variants` attribute returns an array of variant objects, each containing the same fields as `first_or_matched_variant`: | Field Name | Type | Description | | :- | :- | :- | | id | Integer | Unique identifier for the variant | | title | String | Title of the variant (typically the option values combined) | | price | String | Price of the variant (includes discount entitlements when applicable) | | sku | String | SKU of the variant | | barcode | String | Barcode of the variant (typically UPC, EAN, or ISBN). Returns an empty string when the variant has no barcode. | | compare\_at\_price | String | Compare at price of the variant (original price before discount) | | available | Boolean | Availability status of the variant | | in\_stock\_location\_ids | Array of Integers | **Sort-only field.** Array of location IDs where the variant has available inventory (available > 0). This field can be used in sort orders for location-based product demotion but is not filterable and is not included in API responses. | | position | Integer | Position of the variant in the product's variant list | | selected\_options | Array of Objects | The selected options for this variant (e.g., Size: "M", Color: "Blue") | | featured\_media | Object | The featured media for this variant (if variant-specific media exists) | | created\_at | DateTime | DateTime when the variant was created | | updated\_at | DateTime | DateTime when the variant was last updated | | requires\_selling\_plan | Boolean | Whether the variant requires a selling plan (subscription) | | has\_selling\_plan | Boolean | Whether the variant has an associated selling plan | | inventory\_quantity | Integer | Total inventory quantity across the locations in the store's [inventory location scope](/shopify-integration/catalog-sync#inventory-location-scope), which is all locations by default (only included when Expose Variant Inventory is enabled) | | inventory\_policy | String | Inventory policy for the variant: `DENY` (stop selling when out of stock) or `CONTINUE` (allow overselling). Variants with inventory tracking disabled in Shopify are always reported as `CONTINUE`. Only included when Expose Variant Inventory is enabled. | | inventory\_levels | Object | Object mapping location IDs to available inventory quantities (e.g., `{"1001": 5, "1002": 10}`). Returns empty object `{}` when no inventory data exists. Only included when Expose Variant Inventory is enabled. | ### Example variants response ```json theme={null} { "id": 7003338965178, "title": "Premium Cotton T-Shirt", "handle": "premium-cotton-t-shirt", "variants": [ { "id": 41234567890123, "title": "Small / Blue", "price": "29.99", "sku": "TSHIRT-BLU-S", "barcode": "0123456789013", "compare_at_price": "39.99", "available": true, "position": 1, "selected_options": [ { "name": "Size", "value": "Small" }, { "name": "Color", "value": "Blue" } ], "featured_media": { "alt": "Blue T-Shirt", "src": "https://cdn.shopify.com/s/files/variant-blue.jpg", "width": 800, "height": 800, "mediaContentType": "IMAGE" }, "created_at": "2024-01-15T10:30:00.000000Z", "updated_at": "2024-03-20T14:45:00.000000Z", "requires_selling_plan": false, "has_selling_plan": false, "inventory_quantity": 8, "inventory_policy": "DENY", "inventory_levels": { "1001": 3, "1002": 5 } }, { "id": 41234567890124, "title": "Medium / Blue", "price": "29.99", "sku": "TSHIRT-BLU-M", "barcode": "0123456789012", "compare_at_price": "39.99", "available": true, "position": 2, "selected_options": [ { "name": "Size", "value": "Medium" }, { "name": "Color", "value": "Blue" } ], "featured_media": { "alt": "Blue T-Shirt", "src": "https://cdn.shopify.com/s/files/variant-blue.jpg", "width": 800, "height": 800, "mediaContentType": "IMAGE" }, "created_at": "2024-01-15T10:30:00.000000Z", "updated_at": "2024-03-20T14:45:00.000000Z", "requires_selling_plan": false, "has_selling_plan": false, "inventory_quantity": 15, "inventory_policy": "DENY", "inventory_levels": { "1001": 5, "1002": 10 } }, { "id": 41234567890125, "title": "Large / Red", "price": "32.99", "sku": "TSHIRT-RED-L", "barcode": "0123456789014", "compare_at_price": "42.99", "available": true, "position": 3, "selected_options": [ { "name": "Size", "value": "Large" }, { "name": "Color", "value": "Red" } ], "featured_media": { "alt": "Red T-Shirt", "src": "https://cdn.shopify.com/s/files/variant-red.jpg", "width": 800, "height": 800, "mediaContentType": "IMAGE" }, "created_at": "2024-01-15T10:30:00.000000Z", "updated_at": "2024-03-20T14:45:00.000000Z", "requires_selling_plan": false, "has_selling_plan": false, "inventory_quantity": 22, "inventory_policy": "CONTINUE", "inventory_levels": { "1001": 12, "1003": 10 } } ] } ``` > [!NOTE] > > To include `variants` in API responses, you must explicitly request it in the `attributes` array parameter. The variants array is always ordered by the variant's position field. When discount entitlements are configured, the price field reflects the discounted price for each variant. ## options\_v2 structure The `options_v2` field provides option data with swatch and linked metafield information from Shopify's product option values. Use `options_v2` to display visual swatches (colors or images) for product options or access linked metafield data associated with specific option values. ### options\_v2 schema fields | Field Name | Type | Description | | :- | :- | :- | | name | String | The option name (e.g., "Color", "Size") | | code | String | A normalized, URL-friendly version of the option name (e.g., "color", "size") | | values | Array of Objects | Array of unique option values with their associated swatch and metafield data | ### Option value schema fields | Field Name | Type | Description | | :- | :- | :- | | value | String | The option value (e.g., "Red", "Medium") | | swatch | Object or null | Swatch data containing color and/or image information | | linked\_metafield\_value | Mixed or null | The linked metafield value associated with this option value in Shopify | ### Swatch object schema | Field Name | Type | Description | | :- | :- | :- | | color | String or null | Hex color code (e.g., "#FF0000") | | image | Object or null | Image object with `alt` and `url` properties | ### Example options\_v2 response ```json theme={null} { "options_v2": [ { "name": "Color", "code": "color", "values": [ { "value": "Red", "swatch": { "color": "#FF0000", "image": null }, "linked_metafield_value": null }, { "value": "Blue", "swatch": { "color": "#0000FF", "image": null }, "linked_metafield_value": null }, { "value": "Pattern A", "swatch": { "color": null, "image": { "alt": "Pattern A swatch", "url": "https://cdn.shopify.com/s/files/pattern-a.jpg" } }, "linked_metafield_value": "organic-cotton-blend" } ] }, { "name": "Size", "code": "size", "values": [ { "value": "Small", "swatch": null, "linked_metafield_value": null }, { "value": "Medium", "swatch": null, "linked_metafield_value": null }, { "value": "Large", "swatch": null, "linked_metafield_value": null } ] } ] } ``` > [!NOTE] > > The `options_v2` field preserves Shopify's option ordering and includes option values from all variants regardless of stock status, aligning with `original_options` behavior. When the same option value appears on multiple variants with different swatch or metafield data, the first non-null value is used. ### Example product (JSON) ```json theme={null} { "id": 7002787512506, "tags": [ "Active22", "New Arrivals", "top1", "topmost" ], "title": "LOUIS VUITTON\/SUPREME BOX LOGO", "category": null, "combined_listing_parent_product_id": null, "combined_listing_role": null, "featured_media": { "alt": "SUPREME T-SHIRT", "src": "https:\/\/cdn.shopify.com\/s\/files\/1\/0588\/3677\/9194\/products\/supreme_lv_tee_white_2-2.jpg?v=1644024149", "width": 940, "height": 627, "mediaContentType": "IMAGE" }, "handle": "supreme-t-shirty92wjc8-001", "images": [ { "alt": "SUPREME T-SHIRT", "src": "https:\/\/cdn.shopify.com\/s\/files\/1\/0588\/3677\/9194\/products\/supreme_lv_tee_white_2-2.jpg?v=1644024149", "width": 940, "height": 627, "variant_ids": [] } ], "vendor": "SUPREME", "available": true, "body_html": "The Supreme Louis Vuitton Monogram box logo shirt represents a historic partnership between two fashion giants, boasting meticulous craftsmanship and attention to detail. Crafted from the finest materials, the shirt showcases Louis Vuitton's timeless monogram pattern as the background, with Supreme's unmistakable red box logo boldly and tastefully placed at its center. This unique collaboration item is not just a shirt; it's a symbol of the convergence of streetwear culture and high-end luxury, making it an icon of the fashion world. With limited availability and an aura of exclusivity, it has become a grail for collectors and enthusiasts, embodying a blend of urban style and opulence that continues to captivate fashion-conscious individuals worldwide.", "created_at": "2022-02-05T01:22:27.000000Z", "metafields": { "product": { "alias": "LOUIS VUITTON MONOGRAM BOX LOGO T-SHIRT", "colorway": "WHITE", "condition": "New", "styleCode": "Y92WJC8-001", "searchColor": [ "white" ], "yearOfRelease": "S\/S 2017" } }, "named_tags": { "Datahub": "Synced", "ColorWay": "WHITE", "AliasName": "LOUIS VUITTON MONOGRAM BOX LOGO T-SHIRT", "Condition": "New", "StyleCode": "Y92WJC8-001", "Collection": [ "Designer", "Apparel", "Louis Vuitton", "Supreme", "T-Shirts" ], "SearchColor": "white", "YearOfRelease": "S\/S 2017", "ProductSubType": "T-Shirt", "SearchKeyword1": "SUPREME\/LOUIS VUITTON MONOGRAM BOX LOGO T-SHIRT", "SearchKeyword2": "S\/S 2017", "SearchKeyword3": "WHITE" }, "updated_at": "2024-04-02T21:31:39.000000Z", "price_range": { "to": 1500, "from": 1500, "compare_at_price": 0 }, "options": { "Size": [ "XS", "S", "M", "L", "XL", "2XL" ] }, "product_type": "Apparel", "published_at": "2022-02-05T01:22:27.000000Z" } ``` ## See also * [Product Schema](/developers/product-schema) * [Metafields & References](/developers/product-schema/metafields) * [Available Attributes for API Requests](/developers/product-schema/api-attributes) # Rendering banners in Liquid Source: https://docs.uselayers.com/developers/rendering-banners-in-liquid Render merchandising banners from the browse response in a Shopify Liquid theme — hero rows above the grid and inline overtake or inject tiles. ## Overview A [merchandising rule](/platform/merchandising/banners) can attach up to 50 banners as a consequence. When one or more rules match a browse request, the response carries a top-level `banners` array that is flat, already merged across every applied rule, and sorted. Your theme is responsible for placing each banner into the grid. A banner is either: * A **hero** horizontal banner that spans the entire product grid above the first product row, or * An **inline** banner that spans one or more columns at a specific position in the grid, either `overtake` (replacing products) or `inject` (inserting alongside products and optionally wrapped in a link). Inline layout dimensions are grid-cell spans, not required image dimensions in pixels. Width is bounded by the grid, not limited to one or two columns. The editor can resize inline banners across columns and up to four rows; render the saved row span as well as the column span. Hero banners ignore cell spans and use the full grid width; your theme controls their height and image cropping. Use this version when you're scripting against the storefront API directly with `fetch`. For the SDK version, see [Rendering banners with the SDK](/developers/rendering-banners-with-the-sdk). ## Prerequisites * The Layers Shopify app installed and configured. See [Liquid integration](/developers/liquid-integration). * A working browse implementation that reads from the Layers [Browse API](/api-reference/browse), such as the patterns shown in [Rendering facets in Liquid](/developers/rendering-facets-in-liquid). * At least one merchandising rule with banners attached. See [Add a banner to a rule](/help/merchandising/add-banner-to-rule). ## The banner payload Banners ship as a top-level `banners` array on the browse response. Each banner carries the `rule_id` of the [merchandising rule](/platform/merchandising) that produced it, and `_meta.appliedRules` lists every applied rule ID. ```json theme={null} { "results": [ /* ... */ ], "banners": [ { "id": "01KWD5S5R50690NXFW32PXM0V2", "rule_id": "bd2d34eb-0d87-4299-90ee-ffeb572a12f6", "name": "Willie Nelson Flannel", "mode": "inject", "link": null, "type": "link", "data": {}, "sort_index": 0, "web_media": { "id": "gid://shopify/MediaImage/30292299612213", "alt": null, "src": "https://cdn.shopify.com/.../banner-web.jpg", "width": 750, "height": 1100, "source": "store_file", "mediaContentType": "IMAGE" }, "mobile_media": { "id": "gid://shopify/MediaImage/30292299612213", "alt": null, "src": "https://cdn.shopify.com/.../banner-mobile.jpg", "width": 750, "height": 1100, "source": "store_file", "mediaContentType": "IMAGE" }, "web_layout": { "placement": "inline", "width": 1, "height": 1, "position": 1 }, "mobile_layout": { "placement": "inline", "width": 1, "height": 1, "position": 1 } } ], "_meta": { "appliedRules": ["bd2d34eb-0d87-4299-90ee-ffeb572a12f6"] } } ``` Four parts of the banner payload matter for rendering: * **Per-device media and layout.** Pick `web_media` + `web_layout` on desktop and `mobile_media` + `mobile_layout` on mobile. They're independent. A hero on web can be an inline tile on mobile. * **Mode.** `overtake` replaces the product card at `position`. `inject` inserts the banner at `position` and shifts trailing products by one cell. * **Link.** On the built-in `link` type, only `inject` banners can carry a top-level `link`. Wrap inject banners in an anchor; render overtake banners as plain media. Custom [banner types](/platform/merchandising/banner-types) put their click-through URL inside `data` instead. * **Type and data.** `type` is the banner type slug: `"link"` for the built-in type, or the slug of one of your custom types. `data` carries the values of that type's field schema. Switch renderers on `type` and read fields out of `data`. ## Step 1: Read banners from the browse response The `banners` array is already flat and pre-sorted by `sort_index`. Guard against a missing array. ```js theme={null} function collectBanners(browseResponse) { return browseResponse.banners ?? [] } ``` ## Step 2: Pick the right layout for the device A banner only has a usable layout when both the media slot **and** the layout for the active device are present. Skip banners that don't have both filled. ```js theme={null} function isMobile() { return window.matchMedia('(max-width: 749px)').matches } function layoutForDevice(banner) { const media = isMobile() ? banner.mobile_media : banner.web_media const layout = isMobile() ? banner.mobile_layout : banner.web_layout if (!media?.src || !layout) return null return { media, layout, mode: banner.mode, link: banner.link, id: banner.id } } ``` ## Step 3: Render hero banners above the grid Hero banners (`placement: "hero"`) render full-width above the first product row. They never displace products, so `position` is not meaningful for them. Do not apply inline `width` and `height` cell spans to heroes. Render heroes in `sort_index` order. ```js theme={null} function renderHero(host, picked) { const wrapper = picked.mode === 'inject' && picked.link ? `` : `' host.insertAdjacentHTML( 'afterbegin', `${wrapper}${picked.media.alt ?? ''}${closing}`, ) } ``` `host` is the container that wraps the grid section. Render hero banners on the outside, before the product grid. ## Step 4: Slot inline banners into the grid Inline banners take a `position` (row-major, 0-indexed) and span `width × height` grid cells. Walk the products and insert banners at their target index. For `overtake`, replace the product at `position`. For `inject`, splice the banner in at `position` and let trailing products shift. ```js theme={null} function buildGridCells(products, banners) { const cells = products.map((p) => ({ type: 'product', product: p })) // Inline banners only. The response already sorts by sort_index. const inline = banners .map((b) => ({ banner: b, picked: layoutForDevice(b) })) .filter(({ picked }) => picked && picked.layout.placement === 'inline') for (const { picked } of inline) { const position = picked.layout.position ?? 0 const cell = { type: 'banner', mode: picked.mode, link: picked.link, media: picked.media, width: picked.layout.width, height: picked.layout.height, id: picked.id, } if (picked.mode === 'overtake') { // Replace the product at this position (no shift). if (position < cells.length) { cells[position] = cell } else { cells.push(cell) } } else { // inject - insert and shift trailing products. cells.splice(Math.min(position, cells.length), 0, cell) } } return cells } function renderGrid(grid, cells) { grid.innerHTML = cells .map((cell) => { if (cell.type === 'product') return renderProductCell(cell.product) const inner = `${cell.media.alt ?? ''}` const style = `--span-x:${cell.width};--span-y:${cell.height}` const classes = `layers-banner layers-banner--inline layers-banner--${cell.mode}` if (cell.mode === 'inject' && cell.link) { return `${inner}` } return `
    ${inner}
    ` }) .join('') } ``` Use the `--span-x` / `--span-y` custom properties (or `grid-column: span 2; grid-row: span 2`) in your CSS so 2×2 inline banners actually cover four grid cells. ## Putting it together The end-to-end flow on a collection page: ```js theme={null} async function loadCollection() { const response = await fetch( `${window.layersConfig.apiBase}/browse/${COLLECTION_HANDLE}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': window.layersConfig.storefrontApiToken, }, body: JSON.stringify({ pagination: { page: 1, limit: 24 } }), }, ) const browse = await response.json() const banners = collectBanners(browse) // Hero banners - render above the grid. for (const banner of banners) { const picked = layoutForDevice(banner) if (picked?.layout.placement === 'hero') { renderHero(document.querySelector('.collection'), picked) } } // Inline banners - combined with products into grid cells. const cells = buildGridCells(browse.results ?? [], banners) renderGrid(document.querySelector('.collection__grid'), cells) } ``` ## Custom banner types The rendering steps on this page work unchanged for the built-in **Link** type. If you've defined [custom banner types](/platform/merchandising/banner-types), each banner also carries a `type` slug and a `data` object with the type's saved field values. Switch renderers on `type` and read fields out of `data`. The envelope (media, layout, mode) is the same across all types. ```js theme={null} function renderBannerBody(picked, data) { switch (picked.type) { case 'link': // Built-in type: plain image, optionally wrapped in an anchor. return `${picked.media.alt ?? ''}` case 'countdown_promo': // Custom type: image + headline + countdown target. return ` ${picked.media.alt ?? ''}

    ${escapeHtml(data.headline ?? '')}

    ` case 'spotlight_product': // Custom type with a product_reference field, already resolved to { id, handle }. return ` ${picked.media.alt ?? ''} ${escapeHtml(data.overlay_label ?? '')} ` default: // Unknown type - fall back to the media so a newly-added type still renders. return `${picked.media.alt ?? ''}` } } ``` Pass `banner.type` and `banner.data` through to your `layoutForDevice` return value so each render path has them available: ```js theme={null} function layoutForDevice(banner) { const media = isMobile() ? banner.mobile_media : banner.web_media const layout = isMobile() ? banner.mobile_layout : banner.web_layout if (!media?.src || !layout) return null return { media, layout, mode: banner.mode, link: banner.link, type: banner.type, data: banner.data ?? {}, id: banner.id, } } ``` Reference fields (`product_reference`, `collection_reference`, `variant_reference`) arrive pre-resolved to `{ id, handle }`. Unpublished references are dropped from the payload, so you don't need to guard against dead handles. Retyped or removed fields on the banner type are dropped too. Treat any field on `data` as optional and fall back cleanly. ## Fallback rules Per [Banner Injection](/platform/merchandising/banners#limits-and-behavior): * A banner without **both** the device's media slot and layout is treated as disabled: `layoutForDevice` returns `null` and you skip it. * A banner without `web_media` **or** `mobile_media` filled is never enabled by Layers, so it won't appear in the payload in the first place. * Banners with `mode: "overtake"` ignore any `link` value. Only `inject` banners are clickable. ## What the app embed handles for you The Layers theme app extension does **not** render banners. That's your theme's responsibility. The embed *does* handle: * Authenticating the browse request (the embed forwards the storefront token and identity). * Sending the [storefront pixel](/shopify-integration/storefront-pixel) events that track shopper engagement on the underlying collection grid. The storefront pixel also tracks `banner_impression` and `banner_click` events automatically for any rendered element whose `data-banner-id` matches a banner `id` from the Layers response, as in the examples above. Keep that attribute on your banner markup so these events fire. ## Troubleshooting **Banners never appear.** Confirm the rule is active, both `web_media` and `mobile_media` are filled, and the rule's contextual conditions match the request. In the [dashboard rule preview](/platform/merchandising/banners#scheduling-and-targeting), banners are shown regardless of contextual conditions. A banner that appears in preview but not on the storefront usually means a condition didn't match. **Inline banner is at the wrong cell.** `position` is row-major and 0-indexed. Verify the device's `*_layout.position` matches the cell index you expect when the grid has been flattened to a single array. **Overtake banner dropped a product.** That's by design: `overtake` replaces the product at `position`. Use `inject` if you want to keep all products and shift the trailing ones. **2×2 inline tile renders as a 1×1.** Your CSS isn't honoring `width`/`height`. Apply `grid-column: span ; grid-row: span ` (or the `--span-x`/`--span-y` properties from the Step 4 snippet) on banner cells. ## Grid-aware pagination (optional) The default banner flow on this page splices banners into a page of products after the browse response returns. This works, but paginated collections can end up with a short last row. A page-2 request asks for `limit` products, and if page 1 had banners, page 2 restarts the product cursor as if page 1 had none. To page products *around* banner cells, send an optional `grid` block on the browse request: ```js theme={null} const response = await fetch(`${apiBase}/browse/${COLLECTION_HANDLE}`, { method: 'POST', headers: { /* ... */ }, body: JSON.stringify({ pagination: { page: 1, limit: 24 }, grid: { columns: 4, device: isMobile() ? 'mobile' : 'desktop', }, }), }) ``` When `grid` is present, the response includes a top-level `grid` block and each anchored inline banner gets a page-local `placement`: ```json theme={null} { "grid": { "columns": 4, "device": "desktop", "cellsPerPage": 24, "rows": 6, "bannerCells": 5 }, "banners": [ { "id": "01KWD5S5R50690NXFW32PXM0V2", "web_layout": { "placement": "inline", "width": 1, "height": 1, "position": 1 }, "placement": { "page": 1, "row": 0, "colStart": 1, "colSpan": 1, "rowSpan": 1 } } ] } ``` With `grid` set: * `results` contains only the products for the *available* cells on this page (`cellsPerPage - bannerCells`), so you never over- or under-fill a page. * `totalPages` accounts for banner cells across the collection. * Anchored inline banners carry a `placement` with page-local `row`, `colStart`, `colSpan`, and `rowSpan`. Render them with `grid-column: / span ` and `grid-row: / span ` instead of using the raw `position`. * Render hero banners above the grid on every page. They never carry `placement`. * Inline banners that could not be anchored (missing device layout, no saved position, or no fit on this page) are returned without `placement`. Fall back to your normal `overtake`/`inject` splicing for those. ## See also * [Banner Injection](/platform/merchandising/banners) — payload reference and dashboard model. * [Banner Types](/platform/merchandising/banner-types) — define the typed field schemas banners can use. * [Rendering banners with the SDK](/developers/rendering-banners-with-the-sdk) — SDK equivalent. * [Add a banner to a rule](/help/merchandising/add-banner-to-rule) — merchandiser walkthrough. * [Browse API](/api-reference/browse) — request and response reference. # Rendering banners with the SDK Source: https://docs.uselayers.com/developers/rendering-banners-with-the-sdk Render merchandising banners with the Layers SDK by reading data.banners from the collection controller. Hero rows and inline tiles overtake or inject products. ## Overview This guide is the SDK equivalent of [Rendering banners in Liquid](/developers/rendering-banners-in-liquid). The browse payload, layout selection, and grid math are identical. With `@commerce-blocks/sdk`, `sdk.collection()` makes the HTTP call, deduplicates requests, caches the response, and exposes `data.banners` on reactive state you can subscribe to. Use this version when you have already installed [`@commerce-blocks/sdk`](/sdk/installation) in your theme. For a no-dependencies version, see the [Liquid + Fetch guide](/developers/rendering-banners-in-liquid). **Hero banners** are horizontal banners spanning the entire product grid above the first product row. They are not restricted to inline tile sizes. **Inline banners** can span one or more columns, bounded by the grid rather than a fixed 1×1 or 2×2 preset. Inline sizes are grid-cell spans, not image dimensions in pixels. The editor can resize inline banners across columns and up to four rows. ## Prerequisites * The Layers Shopify app installed and the theme app extension enabled in **Online Store → Themes → Customize → App embeds**. * The SDK installed and initialized in your theme. See [SDK installation](/sdk/installation). * At least one merchandising rule with banners attached. See [Add a banner to a rule](/help/merchandising/add-banner-to-rule). ## The banner payload Banners ship as a top-level, pre-sorted array on the collection controller's `data`: ```ts theme={null} data.banners // → Array<{ // id: string, // rule_id: string | null, // ID of the merchandising rule that produced the banner // name: string, // mode: 'overtake' | 'inject', // link: string | null, // type: string, // 'link' for the built-in type, or your custom type's slug // data: Record,// values for that type's field schema // sort_index: number, // web_media: { id, src, alt, width, height, source, mediaContentType }, // mobile_media: { id, src, alt, width, height, source, mediaContentType }, // web_layout: { placement: 'hero' | 'inline', width, height, position }, // mobile_layout:{ placement: 'hero' | 'inline', width, height, position }, // }> ``` Each banner carries the `rule_id` of the [merchandising rule](/platform/merchandising) that produced it. `data._meta.appliedRules` (a flat array of rule ID strings) still lists every applied rule. Four parts of the banner payload matter for rendering: * **Per-device media and layout.** Pick `web_*` on desktop and `mobile_*` on mobile. They're independent. A hero on web can be an inline tile on mobile. * **Mode.** `overtake` replaces the product card at `position`. `inject` inserts the banner and shifts trailing products by one cell. * **Link.** On the built-in `link` type, only `inject` banners can carry a top-level `link`. Wrap them in an anchor. Render overtake banners as plain media. Custom [banner types](/platform/merchandising/banner-types) put their click-through URL inside `data` instead. * **Type and data.** `type` is the banner type slug: `'link'` for the built-in type, or the slug of one of your custom types. `data` carries the values of that type's field schema. Switch renderers on `type` and read fields out of `data`. ## Step 1: Subscribe to the collection controller `sdk.collection()` returns a reactive controller. Subscribe once and read `data.products` and `data.banners` from the same payload. ```js theme={null} import { getSDK } from '@commerce-blocks/sdk' const { data: sdk, error: sdkError } = getSDK() if (sdkError) { console.error('SDK not initialized:', sdkError.message) } const collection = sdk.collection({ collectionHandle: COLLECTION_HANDLE }) collection.subscribe(({ data, loading, error }) => { if (loading || error || !data) return render({ products: data.products ?? [], banners: data.banners ?? [], }) }) collection.get({ pagination: { page: 1, limit: 24 } }) ``` The SDK dedupes identical requests and caches responses in memory for the life of the page. It re-runs the subscriber whenever you call `get()` with new filter or pagination args. ## Step 2: Pick the layout for the current device A banner only has a usable layout when both the media slot and the layout for the active device are present. Skip banners that don't have both. ```js theme={null} const mql = window.matchMedia('(max-width: 749px)') const isMobile = () => mql.matches function layoutForDevice(banner) { const media = isMobile() ? banner.mobile_media : banner.web_media const layout = isMobile() ? banner.mobile_layout : banner.web_layout if (!media?.src || !layout) return null return { media, layout, mode: banner.mode, link: banner.link, id: banner.id } } ``` > [!TIP] > > Listen for `mql.addEventListener('change', ...)` and re-render when the breakpoint flips. Banners can have completely different layouts per device. A `2×2` web tile may be a hero on mobile. ## Step 3: Place banners around the products Hero banners render across the full grid width above the products. Ignore their inline `width` and `height` cell spans; your theme controls the hero's height and image cropping. Inline banners slot into the product grid by `position` (row-major, 0-indexed). `overtake` replaces the product at that index; `inject` splices the banner in and shifts trailing products. The response is already sorted by `sort_index`, so no extra sort is needed. ```js theme={null} function render({ products, banners }) { const host = document.querySelector('.collection') const grid = document.querySelector('.collection__grid') // Clear previously rendered hero banners. host.querySelectorAll('.layers-banner--hero').forEach((el) => el.remove()) // Hero banners - render above the grid. for (const banner of banners) { const picked = layoutForDevice(banner) if (picked?.layout.placement === 'hero') renderHero(host, picked) } // Inline banners - combined with products into grid cells. const cells = buildGridCells(products, banners) grid.innerHTML = cells.map(renderCell).join('') } function buildGridCells(products, banners) { const cells = products.map((p) => ({ type: 'product', product: p })) const inline = banners .map((b) => ({ banner: b, picked: layoutForDevice(b) })) .filter(({ picked }) => picked && picked.layout.placement === 'inline') for (const { picked } of inline) { const position = picked.layout.position ?? 0 const cell = { type: 'banner', mode: picked.mode, link: picked.link, media: picked.media, width: picked.layout.width, height: picked.layout.height, id: picked.id, } if (picked.mode === 'overtake') { if (position < cells.length) cells[position] = cell else cells.push(cell) } else { cells.splice(Math.min(position, cells.length), 0, cell) } } return cells } function renderCell(cell) { if (cell.type === 'product') return renderProductCell(cell.product) const inner = `${cell.media.alt ?? ''}` const style = `--span-x:${cell.width};--span-y:${cell.height}` const classes = `layers-banner layers-banner--inline layers-banner--${cell.mode}` if (cell.mode === 'inject' && cell.link) { return `${inner}` } return `
    ${inner}
    ` } function renderHero(host, picked) { const wrapper = picked.mode === 'inject' && picked.link ? `` : `' host.insertAdjacentHTML( 'afterbegin', `${wrapper}${picked.media.alt ?? ''}${closing}`, ) } ``` Use `grid-column: span ; grid-row: span ` (or the `--span-x` / `--span-y` properties) on banner cells so `2×2` tiles actually cover four grid cells. ```js theme={null} function renderProductCell(product) { return `

    ${product.title}

    ${product.price?.formatted ?? ''}
    ` } ``` ## Re-running on filter or pagination changes Reuse the same collection controller and subscriber, and call `get()` with new args. Layers recomputes the banner payload on every request, so banners are always in sync with the current filter set. ```js theme={null} collection.get({ filterGroup: activeFilters, pagination: { page, limit: 24 }, }) ``` ## Custom banner types The rendering steps on this page work unchanged for the built-in **Link** type. If you've defined [custom banner types](/platform/merchandising/banner-types), each banner also carries a `type` slug and a `data` object with the type's saved field values. Switch renderers on `type` and read fields out of `data`. The envelope (media, layout, mode) is the same across all types. ```ts theme={null} type PickedBanner = ReturnType function layoutForDevice(banner) { const media = isMobile() ? banner.mobile_media : banner.web_media const layout = isMobile() ? banner.mobile_layout : banner.web_layout if (!media?.src || !layout) return null return { media, layout, mode: banner.mode, link: banner.link, type: banner.type, data: banner.data ?? {}, id: banner.id, } } function renderBannerBody(picked: NonNullable) { const { type, data } = picked switch (type) { case 'link': return `${picked.media.alt ?? ''}` case 'countdown_promo': return ` ${picked.media.alt ?? ''}

    ${escapeHtml(String(data.headline ?? ''))}

    ` case 'spotlight_product': // product_reference fields arrive pre-resolved to { id, handle }. return ` ${picked.media.alt ?? ''} ${escapeHtml(String(data.overlay_label ?? ''))} ` default: // Unknown type - fall back to the media so a newly-added type still renders. return `${picked.media.alt ?? ''}` } } ``` Reference fields (`product_reference`, `collection_reference`, `variant_reference`) arrive pre-resolved to `{ id, handle }`. Unpublished references are dropped from the payload, so you don't need to guard against dead handles. Retyped or removed fields on the banner type are dropped too. Treat any field on `data` as optional and fall back cleanly. ## Fallback rules Per [Banner Injection](/platform/merchandising/banners#limits-and-behavior): * A banner without both the device's media slot and layout is treated as disabled. `layoutForDevice` returns `null` and you skip it. * A banner without `web_media` or `mobile_media` filled is never enabled by Layers, so it won't appear in the payload in the first place. * Banners with `mode: 'overtake'` ignore any `link` value. Only `inject` banners are clickable. ## What the app embed handles for you The Layers theme app extension does **not** render banners. Your theme owns that. The embed does handle: * Authenticating the browse request (token, cart context, identity). * Sending the [storefront pixel](/shopify-integration/storefront-pixel) events that track shopper engagement on the underlying grid. The storefront pixel also tracks `banner_impression` and `banner_click` events automatically for any rendered element whose `data-banner-id` matches a banner `id` from the Layers response, as in the examples above. Keep that attribute on your banner markup so these events fire. ## Why the SDK over Fetch | Concern | Fetch version | SDK version | | :- | :- | :- | | Driving the request | `fetch` to `/browse/{handle}` | `collection.get()` | | Re-renders | DIY DOM updates | `subscribe()` callback | | Caching during the page | DIY | In-memory cache and request deduplication | | Re-rendering on filter change | Manual orchestration | Same controller, call `get()` again | | Banner placement | Same: your theme owns the grid math | Same: your theme owns the grid math | ## Troubleshooting **`data.banners` is empty.** No merchandising rule matched the request, or every matching rule had no enabled banners. Confirm at least one active rule on this collection has banners attached and both media slots filled. **Banners only appear on first load, not after filtering.** Your subscriber probably re-renders products but not banners. Re-read `data.banners` from the same payload on every state update. They ship together. **Inline banner is at the wrong cell.** `position` is row-major and 0-indexed. Verify the device's `*_layout.position` matches the cell index you expect after flattening the grid to a single array. **`2×2` inline tile renders as a `1×1`.** Your CSS isn't honoring `width`/`height`. Apply `grid-column: span ; grid-row: span ` on banner cells. ## See also * [Rendering banners in Liquid (Fetch)](/developers/rendering-banners-in-liquid) — the no-dependency equivalent. * [Banner Injection](/platform/merchandising/banners) — payload reference and dashboard model. * [Banner Types](/platform/merchandising/banner-types) — define the typed field schemas banners can use. * [Add a banner to a rule](/help/merchandising/add-banner-to-rule) — merchandiser walkthrough. * [Client methods — collection](/sdk/api-reference/client-methods). * [Browse API](/api-reference/browse) — request and response reference. # Rendering blocks in Liquid Source: https://docs.uselayers.com/developers/rendering-blocks-in-liquid Render Layers recommendation blocks in a Shopify theme as a Liquid section with a block picker setting, cart context, product deduplication, and pagination. ## Overview A recommendation block in a Shopify theme is a Liquid section with a single setting: which Layers block to render. Your section fetches the products. The Layers app embed handles the cross-cutting work on that request: adding shopper identity and cart context, excluding products already shown on the page so blocks don't repeat each other, and tracking clicks on the results. You only need to: 1. Add a `metaobject` section setting so merchandisers pick a Layers block by name, not by typing an ID. 2. Render a placeholder element with the selected block's ID. 3. Call the [Blocks API](/api-reference/blocks) to fill it with products. > [!WARNING] > > A block metaobject's system handle is **not** the block ID the Blocks API expects. Layers generates handles as `layers-` (for example, `layers-01j8abcd1234xyz`), and the raw block ID is not stored in any metaobject field. Derive the ID in Liquid: > > ```liquid theme={null} > {{ block.system.handle | remove_first: 'layers-' | upcase }} > ``` > > Passing the raw `system.handle` as `blockId` silently returns no products. `layers-01j...` never matches a block ID, so the request misses the block without an error you can trace to it. Use this version when you're scripting against the storefront API directly with `fetch`. For the SDK version, see [Rendering blocks with the SDK](/developers/rendering-blocks-with-the-sdk). ## Prerequisites * The Layers Shopify app installed with the app embed enabled. The app embed adds cart context, cross-block deduplication, and click attribution to your requests automatically. Your section only needs to fetch products. * A storefront token. The app embed emits it on every page as a ` ``` ## The section Create `sections/layers-recommendations.liquid`. The recommended block picker is a native Shopify `metaobject` setting that points at the Layers block metaobject definition. The theme editor then lists every Layers block by name, with no option list to maintain. ```liquid theme={null} {% assign layers_block = section.settings.layers_block %} {% if layers_block != blank %} {% assign selected_block_id = layers_block.system.handle | remove_first: 'layers-' | upcase %}
    {% if section.settings.heading != blank %}

    {{ section.settings.heading }}

    {% endif %}
      {% endif %} {% schema %} { "name": "Layers Recommendations", "settings": [ { "type": "text", "id": "heading", "label": "Heading", "default": "You may also like" }, { "type": "metaobject", "id": "layers_block", "label": "Block", "info": "Choose a Layers recommendation block.", "metaobject_type": "app--278936322049--block" } ], "presets": [{ "name": "Layers Recommendations" }] } {% endschema %} ``` `metaobject_type` takes the Layers block definition's type, `app----block`. For the Layers app that's `app--278936322049--block`, the same type you read with `shop.metaobjects['app--278936322049--block']`. Use the full string in a theme schema, not the app-scoped `$app:block` shorthand. The setting returns the selected metaobject, not a block ID. Derive the ID from its system handle with `remove_first: 'layers-' | upcase`, as in the section above. When no block is selected, the setting is blank and the section renders nothing. ### Generating block options in the theme editor Use one of these alternatives only if your theme can't use a `metaobject` setting. Both generate options from the same block metaobjects. **`select` setting.** Shopify schema is static JSON, so a `select` setting can't list blocks inline. Most themes that use one update the section schema through the Shopify Admin API when the app is installed, with option values already converted to block IDs: ```json theme={null} { "type": "select", "id": "block_id", "label": "Block", "info": "Choose a Layers recommendation block.", "options": [ { "value": "", "label": "Select a block" } ] } ``` **`datalist` with a `text` setting.** For a Liquid-only path, render a `` from the metaobjects and use a `text` setting with `id` `block_id`. The value is already a block ID, so read it with `{% assign selected_block_id = section.settings.block_id %}` instead of the handle transform: ```liquid theme={null} {% comment %} snippets/layers-blocks-datalist.liquid {% endcomment %} {% assign layers_blocks = shop.metaobjects['app--278936322049--block'] %} {% for block in layers_blocks %} {% endfor %} ``` With any of the three, the merchandiser selects from the live list of Layers blocks instead of pasting a ULID. ## Fetching products The section renders an empty placeholder with the block ID and the current page's anchor. A small script fetches products for each placeholder and hydrates it. ```js theme={null} async function hydrate(section) { const blockId = section.dataset.blockId const anchorId = section.dataset.anchorId const response = await fetch( `${window.layersConfig.apiBase}/blocks/${blockId}/products`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Storefront-Access-Token': window.layersConfig.storefrontApiToken, }, body: JSON.stringify({ ...(anchorId ? { anchor_id: anchorId } : {}), pagination: { page: 1, limit: 12 }, }), }, ) if (!response.ok) { section.hidden = true return } const { results } = await response.json() if (!results.length) { section.hidden = true return } renderProducts(section.querySelector('.layers-recommendations__products'), results) } document.querySelectorAll('.layers-recommendations').forEach(hydrate) ``` ```js theme={null} function renderProducts(list, products) { list.removeAttribute('data-loading') list.innerHTML = products .map( (p) => `
    1. ${p.title}

      ${p.price_range?.min_variant_price ?? ''}
    2. `, ) .join('') } ``` ## Anchors The section reads the right anchor automatically based on `template`: | Template | `anchor_id` sent | | :- | :- | | `product` | `{{ product.id }}` | | `collection` | `{{ collection.handle }}` | | Anything else | omitted (cart-anchored and global blocks resolve without one) | The Layers theme app extension supplies cart context and shopper identity to **every** Blocks request on the storefront, so cart-anchored blocks work without your section reading `/cart.js` or wiring up `productsInCart`. ## What the app embed handles for you Once the Layers theme app extension is installed and enabled, you do **not** need to: * Send `context.productsInCart` for cart-anchored blocks. The embed injects it. * Pass `excludeProductIds` between blocks. The embed adds its IDs to any `excludeProductIds` you send on every Blocks request, keeping your IDs and including products already on the page: results from other blocks, items in the cart, the product being viewed, and products from the search or collection grid. To turn this off, check **Disable block deduplication** in the Layers app embed settings in the theme editor. * Wire up click attribution or feedback. The embed listens for clicks on rendered cards and submits feedback automatically. * Provide identity (`deviceId`, `sessionId`). The storefront pixel manages it. Your section only renders the placeholder and issues the products request. ## Empty blocks and fallbacks The Blocks API runs the block's [fallback chain](/platform/blocks/fallback-chains) server-side. If the chain doesn't produce results, the response is `{ results: [] }`. Hide the section (as the `hydrate` function in [Fetching products](#fetching-products) does) rather than rendering an empty heading. ## Troubleshooting **The section is empty in the theme editor.** Make sure the merchandiser has selected a block in the section's settings. The section hides itself when no block is selected. **The block fetches but renders nothing.** The block fell through its fallback chain. Review configuration in the [dashboard](/platform/blocks/fallback-chains). **Cart recommendations look stale after `/cart` updates.** The app embed keeps its cart context up to date when the Shopify cart changes, but it doesn't re-request blocks that are already on the page. Call your `hydrate` function again after a cart change (for example, when your cart drawer updates) so the block is fetched with the new cart. If the new request still shows old cart contents, confirm the Layers theme app extension is enabled in **Online Store → Themes → Customize → App embeds**. ## See also * [Rendering blocks with the SDK](/developers/rendering-blocks-with-the-sdk) — SDK equivalent * [Blocks API](/api-reference/blocks) — request and response reference * [Blocks](/platform/blocks) and [Fallback chains](/platform/blocks/fallback-chains) — dashboard configuration * [Liquid integration](/developers/liquid-integration) # Rendering blocks with the SDK Source: https://docs.uselayers.com/developers/rendering-blocks-with-the-sdk Render Layers recommendation blocks in a Shopify theme as a Liquid section, hydrated by the @commerce-blocks/sdk blocks controller with cart context. ## Overview This guide is the SDK equivalent of [Rendering blocks in Liquid](/developers/rendering-blocks-in-liquid). The shape of the section is the same: one Liquid section, one merchandiser-facing block-picker setting. The SDK's `blocks()` controller does the HTTP call, deduplicates in-flight requests, caches responses in memory for the life of the page, and exposes the products on reactive state. The SDK itself sends only the values your code supplies and returns results with an `attributionToken` for tracking. With the app embed enabled, the storefront pixel adds identity, cart context, and cross-block deduplication to those requests. See [Identity, context, and attribution](#identity-context-and-attribution). Use this version when you have already installed [`@commerce-blocks/sdk`](/sdk/installation) in your theme. For a no-dependencies version, see the [Liquid + Fetch guide](/developers/rendering-blocks-in-liquid). ## Prerequisites * The Layers Shopify app installed and the theme app extension enabled in **Online Store → Themes → Customize → App embeds**. * The SDK installed and initialized in your theme. See [SDK installation](/sdk/installation). ## The section `sections/layers-recommendations.liquid` is the same Liquid scaffold as the Fetch version: a section with a native `metaobject` block-picker setting and a single placeholder element carrying the selected block ID. ```liquid theme={null} {% assign layers_block = section.settings.layers_block %} {% if layers_block != blank %} {% assign selected_block_id = layers_block.system.handle | remove_first: 'layers-' | upcase %}
      {% if section.settings.heading != blank %}

      {{ section.settings.heading }}

      {% endif %}
        {% endif %} {% schema %} { "name": "Layers Recommendations", "settings": [ { "type": "text", "id": "heading", "label": "Heading", "default": "You may also like" }, { "type": "metaobject", "id": "layers_block", "label": "Block", "info": "Choose a Layers recommendation block.", "metaobject_type": "app--278936322049--block" } ], "presets": [{ "name": "Layers Recommendations" }] } {% endschema %} ``` `metaobject_type` is the Layers block definition type, `app--278936322049--block`. The theme editor lists Layers blocks by name. If your theme can't use a `metaobject` setting, see the [`select` and `datalist` alternatives](/developers/rendering-blocks-in-liquid#generating-block-options-in-the-theme-editor). > [!WARNING] > > A block metaobject's system handle is **not** the value to pass as `blockId`. Layers generates handles as `layers-` (for example, `layers-01j8abcd1234xyz`), and the raw block ID is not stored in any metaobject field. Derive the ID in Liquid: > > ```liquid theme={null} > {{ block.system.handle | remove_first: 'layers-' | upcase }} > ``` > > Passing the raw `system.handle` silently returns no products. The handle never matches a block ID. ## Hydrating the section For each rendered section, create an `sdk.blocks()` controller with the selected block ID and the page anchor. Subscribe to the state and render on `data` changes. ```js theme={null} import { getSDK } from '@commerce-blocks/sdk' const { data: sdk, error: sdkError } = getSDK() if (sdkError) { console.error('SDK not initialized:', sdkError.message) } function hydrate(section) { const blockId = section.dataset.blockId const anchorId = section.dataset.anchorId || undefined const list = section.querySelector('.layers-recommendations__products') const blocks = sdk.blocks({ blockId, anchorId }) blocks.subscribe(({ data, error }) => { if (error || (data && !data.products.length)) { section.hidden = true return } if (data) renderProducts(list, data.products) }) blocks.get({ pagination: { limit: 12 } }) } document.querySelectorAll('.layers-recommendations').forEach(hydrate) ``` ```js theme={null} function renderProducts(list, products) { list.removeAttribute('data-loading') list.innerHTML = products .map( (p) => `
      1. ${p.title}

        ${p.price?.formatted ?? ''}
      2. `, ) .join('') } ``` That is the whole integration. Multiple sections on the same page each get their own controller, run independently, and reuse the SDK's cache and dedup machinery. ## Rendering cards with your theme's own Liquid snippets A client-side card renderer drifts out of sync with the theme's product card (badges, ratings, swatches, variant logic). The more durable pattern is Shopify's [Section Rendering API](https://shopify.dev/docs/api/ajax/section-rendering): create one thin section per surface that renders your existing card snippet for a single product, then fetch it once per result handle. ```liquid theme={null} {% comment %} sections/layers-card-search.liquid {% endcomment %} {% render 'product-card', product: product, current_variant: product.selected_or_first_available_variant, show_rating: section.settings.show_rating %} ``` ```js theme={null} async function fetchCards(products, sectionId) { const results = await Promise.allSettled( products.map((p) => { // Pass the matched variant through as a product-page ?variant= param so // the section renders the variant Layers selected, not the default const variantId = p.selectedVariant?.numericId const variantParam = variantId ? `?variant=${variantId}&` : '?' return fetch(`/products/${p.handle}${variantParam}sections=${sectionId}`) .then((r) => (r.ok ? r.json() : null)) .then((json) => json?.[sectionId] ?? '') }) ) // Order follows `products` exactly; failed or empty cards drop out return results .map((r) => (r.status === 'fulfilled' ? r.value : '')) .filter((html) => html.trim()) } ``` Each request returns `{ "": "" }`, a map of section ID to its HTML fragment. A missing product or a section that renders nothing produces an empty string or a missing key, which is why the helper filters blank cards. * One request per result, fired in parallel. A failed fetch drops that card instead of breaking the rail. * Pass the product's `selectedVariant.numericId` as the product-page `variant` parameter so the section renders the variant Layers selected (filters, ranking, variant breakouts). Without it, Shopify renders `first_available_variant` and two breakout tiles of one product collapse into identical cards. The SDK always requests the matched variant and exposes it as `selectedVariant`; use `numericId`, because `id` is the `layers-`-prefixed SDK ID. If you call the API with Fetch instead, the raw result carries it as `first_or_matched_variant.id`. * `?sections=` accepts up to 5 comma-separated section IDs per request, so distinct surfaces can share a round trip. * Keep the section's card arguments in sync with the native grid (rating settings, `hide`-tag skips, favorite button). The section is the single place that mapping lives. * Grid markup still comes from the Liquid section wrapping the rail; only the tile HTML is fetched. ## Identity, context, and attribution The app embed loads the storefront pixel, which watches the page's requests to the Layers API, including the ones the SDK sends, and fills in what your block requests need: * **Identity:** If a request has no `identity`, the pixel adds the shopper's device ID, session ID, and customer ID. If you pass `identity` to `createSDK()` (as a static object or a resolver that runs on every request), your values are used instead and the pixel doesn't add any of its own. * **Cart context:** The pixel adds `productsInCart` and the rest of the shopper context to every request, so cart-anchored blocks work without reading `/cart.js`. Any `context` fields you pass yourself take priority over the pixel's. * **Cross-block deduplication:** On every Blocks request, the pixel adds its IDs to any `excludeProductIds` you pass, keeping your IDs and including products already on the page: results from other blocks, items in the cart, the product being viewed, and products from the search or collection grid. To turn this off, check **Disable block deduplication** in the Layers app embed settings in the theme editor. * **Click attribution:** Results carry an `attributionToken`. The storefront pixel covers standard themes. For custom-rendered cards, forward `attributionToken` on your click and add-to-cart tracking. The pixel only sees requests made after it loads. Create the SDK in a script that runs after the app embed's script in the ``, such as a ` ``` The CDN build is an ES module, so use `type="module"`. Module scripts defer automatically; you do not need to add `defer`. Once the script loads, you can add the custom elements where you want the entry points and preview to appear. See [Image search](#image-search-toggle), [Shop similar](#similar-products-toggle), and [Similar-products preview](#similar-products-preview). ### Script attributes Put these attributes on the script element with `id="layers-script"`. | Attribute | Type and values | Default | Description | | :- | :- | :- | :- | | `data-api-key` | String | No value | Storefront access token. If present when the widget initializes, it becomes the configured key. If no key was configured at initialization, the widget also checks the current attribute value for each API request. | | `data-hide-branding` | String: `"true"` | Unset | Set to `"true"` to hide the **Powered by Layers** footer in the image-search and similar-products modals. A boolean `hideBranding` value set through `configure()` overrides this attribute. | | `data-debug` | String: `"true"` or `"false"` | `"false"` | Enables widget debug logging when the script initializes. The widget reads this attribute at initialization; use `configure({ debug: true })` to change debug logging later. | ### API key resolution and load order The widget resolves its access token whenever it makes an API request, in this order: 1. `widgetManager.config.apiKey`, set with `setApiKey()`, `configure({ apiKey })`, or by a non-empty `data-api-key` value read when the widget initializes. 2. The current non-empty `data-api-key` value on `#layers-script`. 3. The `storefrontApiToken` value in the app embed's ` ``` `configure()` accepts these options: | Option | Type | Default | Description | | :- | :- | :- | :- | | `apiKey` | String | Unset | Sets the highest-priority storefront access token. | | `debug` | Boolean | `false` | Enables or disables debug logging. | | `showInstructions` | Boolean | `true` | Shows or hides the image-search instructions by default. | | `hideBranding` | Boolean | Unset | When set, overrides `data-hide-branding` for both modals. | | `currencyFormat` | Object | See below | Sets price formatting. `configure()` merges this object with the existing currency format instead of replacing it. | | `translations` | Object keyed by `"image-search"` and `"similar-products"` | Unset | Overrides widget copy. Each value is deep-merged over that widget's built-in text. See [Translations](#translations). | The `currencyFormat` object accepts: | Property | Type and values | Default | Description | | :- | :- | :- | :- | | `currency` | ISO currency code, such as `"EUR"` | Unset | Explicit currency override. | | `locale` | Locale string, such as `"de-DE"` | Unset | Explicit locale override. | | `style` | `"currency"` or `"decimal"` | `"currency"` | Selects currency or decimal number formatting. | | `currencyDisplay` | `"symbol"`, `"code"`, or `"name"` | `"symbol"` | Controls how the currency appears when `style` is `"currency"`. | | `showSymbol` | Boolean | `true` | Legacy configuration field. The current formatter uses `currencyDisplay` to choose the currency representation. | For example, `configure({ currencyFormat: { currency: 'EUR' } })` keeps the default `style: 'currency'` and `currencyDisplay: 'symbol'`. You can also use `updateCurrencyFormat()` to merge currency-format properties. Other available methods include: * `setApiKey(apiKey)` and `getApiKey()` to set or resolve the storefront access token. * `createImageSearchToggle(options)`, `createSimilarProductsToggle(options)`, and `createSimilarProductsPreview(options)` to add widgets from JavaScript. * `updateTheme(properties)` to set CSS custom properties at runtime. * `updateTranslations(widgetType, translations)` to merge translations for `image-search` or `similar-products`. * `debugTheme()` to log the theme values the widget manager tracks. ## Image search toggle Use `` to add a button that opens the image-search modal. ```html theme={null} ``` | Attribute | Type and values | Default | Description | | :- | :- | :- | :- | | `template-id` | String | Unset | ID of a `