# AGENTS
Source: https://docs.virtual.fit/AGENTS
> For Mintlify product knowledge (components, configuration, writing standards),
> install the Mintlify skill: `npx skills add https://mintlify.com/docs`
# Documentation project instructions
## About this project
* This is a documentation site built on [Mintlify](https://mintlify.com)
* Pages are MDX files with YAML frontmatter
* Configuration lives in `docs.json`
* Use the Mintlify MCP server, `https://mcp.mintlify.com`, to edit content and settings via MCP
* Use the Mintlify docs MCP server, `https://www.mintlify.com/docs/mcp`, to query information about using Mintlify via MCP
## Terminology
* Write the product name as `virtual.fit`.
* Use **virtual.fit** or **dashboard** for the merchant experience.
* Use **fitting room** for the storefront experience and **try-on** for one generated preview.
* Use **shopper** for the merchant's customer.
* Preserve `window.bitstudio`, `window.BitStudio`, and `bitstudio-*` as compatibility identifiers.
* Do not use `bitStudio` as the product name in new prose.
## Style preferences
* Use active voice and second person ("you")
* Keep sentences concise — one idea per sentence
* Use sentence case for headings
* Bold for UI elements: Click **Settings**
* Code formatting for file names, commands, paths, and code references
## Content boundaries
* Document merchant-facing Shopify and Custom JavaScript integration workflows.
* Document public storefront behavior and supported browser APIs.
* Do not document internal admin tools, deployment scripts, private credentials, or implementation-only endpoints.
* Treat virtual.fit as the source of truth for product availability, access limits, and shopper settings.
# Browser API
Source: https://docs.virtual.fit/custom-js/browser-api
Reference the virtual.fit initialization, context, identity, consent, and tracking commands.
The hosted loader exposes a command API through `window.virtualfit`. Define the queue before loading the script so early commands replay in order.
```javascript theme={null}
window.virtualfit = window.virtualfit || function () {
(window.virtualfit.q = window.virtualfit.q || []).push(arguments);
};
```
## `init`
Initialize one storefront configuration.
```javascript theme={null}
virtualfit('init', {
siteKey: 'site_pub_your_key',
mount: '.product-media'
});
```
`siteKey` is required. Calling `init` starts product matching and keeps it current as the page URL changes. See [Loader configuration](/custom-js/configuration) for all fields.
## `setContext`
Patch multiple parts of the active configuration.
```javascript theme={null}
virtualfit('setContext', {
product: {
id: 'sku-10042',
handle: 'linen-midi-dress'
},
customer: {
id: 'customer-8421'
}
});
```
Use `setContext` when a single application state update changes both product and customer context.
## `setProduct`
Set or replace the current product and optional exact variant context.
```javascript theme={null}
virtualfit('setProduct', {
id: 'dress-10042',
handle: 'linen-midi-dress',
title: 'Linen Midi Dress',
imageUrl: 'https://cdn.example.com/linen-midi-dress.jpg'
});
```
```javascript theme={null}
virtualfit('setProduct', {
id: 'dress-10042',
handle: 'linen-midi-dress',
title: 'Linen Midi Dress',
imageUrl: 'https://cdn.example.com/linen-midi-dress.jpg',
variantId: 'linen-black-petite-2',
variantImageUrl: 'https://cdn.example.com/linen-black.jpg'
});
```
Provide `id` or `handle`. The value must resolve to a synced, enabled product with usable garment images.
Stable product ID used during catalog sync.
Synced product handle. Provide `id` or `handle`; providing both is recommended.
Current shopper-facing product title.
Display fallback for the current product. It does not override prepared catalog media.
Exact `source_variant_id` synced under this product. Use it when the shopper has selected a specific variant.
Optional display hint for the selected variant. virtual.fit verifies the variant against the synced product and uses canonical prepared variant media for try-on.
Call `setProduct` after an SPA commits a product route when URL detection cannot identify the product. Call it again when the product or selected variant changes.
Keep `id` stable across all variants of one product. Use `variantId` for the exact color, style, fit, and size combination. A size-only variant can reuse the product's shared prepared media. A color or pattern variant uses its own prepared media when you synced it.
A variant ID must belong to the supplied product and must be available when availability is known. An unknown, mismatched, or unavailable variant fails with an actionable error instead of silently using the wrong garment.
## `setCustomer`
Update shopper identity after login, logout, or account switching.
```javascript theme={null}
virtualfit('setCustomer', {
id: 'customer-8421',
email: 'shopper@example.com'
});
```
Clear identity on logout:
```javascript theme={null}
virtualfit('setCustomer', {
id: '',
email: ''
});
```
Set customer context as early as possible so try-on and commerce events join to the same shopper journey.
## `setConsentMode`
Choose whether analytics may include shopper identity.
```javascript theme={null}
virtualfit('setConsentMode', 'cookieless');
```
Supported values:
| Value | Behavior |
| ------------ | ----------------------------------------------------------------- |
| `consented` | Analytics may include the resolved shopper identity. |
| `cookieless` | Analytics omits shopper identity and uses cookieless measurement. |
Call this when your consent manager initializes and whenever the shopper changes analytics consent.
```javascript theme={null}
consentManager.onChange(({ analyticsAllowed }) => {
virtualfit(
'setConsentMode',
analyticsAllowed ? 'consented' : 'cookieless'
);
});
```
See [Privacy and consent](/operations/privacy-and-consent).
## `recommend`
Request hydrated products for a storefront placement:
```javascript theme={null}
const result = await virtualfit('recommend', {
intent: 'likely_purchases',
excludeProductIds: ['sold-out-belt'],
limit: 8
});
renderRecommendations(result.items);
```
Use `similar` for same-category alternatives, `complete_the_look` for the next category in an outfit, and `likely_purchases` for general “You may also like” or cart recommendations. If `intent` is omitted, the browser API defaults to `likely_purchases`.
The hosted browser API supplies shopper identity automatically and keeps the existing merchant order if a recommendation request is rate-limited. See the [Recommendations API rate limits](/recommendations/api#rate-limits) for backend integrations.
virtual.fit automatically uses the active product and products selected in the
fitting room. `likely_purchases` can return products from categories already
represented in the context.
Pass the latest cart contents as `cartProductIds`. This augments the
automatically resolved current product and fitting-room selection:
```javascript theme={null}
const result = await virtualfit('recommend', {
intent: 'likely_purchases',
cartProductIds: ['linen-shirt', 'tailored-trousers'],
excludeProductIds: ['sold-out-belt']
});
```
Send the complete current cart, including an empty array after the shopper
removes its last item. An explicit `cartProductIds` value is authoritative for
that call.
On a single-page storefront, you may call `recommend` immediately after `setProduct` or a product-bearing `setContext` call. The loader waits for the newest product resolution, so the request cannot fall back to the previously mounted product.
To replace all automatically resolved context instead, pass `productIds`:
```javascript theme={null}
const result = await virtualfit('recommend', {
intent: 'complete_the_look',
productIds: ['linen-shirt', 'tailored-trousers'],
excludeProductIds: ['sold-out-belt', 'hidden-accessory']
});
```
`productIds` must contain one to five outfit IDs for `complete_the_look` and
exactly one ID for `similar`. For `likely_purchases`, it may contain zero to
five IDs: `productIds: []` deliberately suppresses automatic page and
fitting-room context so a supplied `cartProductIds` array can be the entire
request context. A non-array value is rejected. `selectedProductIds`,
`cartProductIds`, and `excludeProductIds` must also be arrays when supplied.
`excludeProductIds` is a hard per-request override and accepts up to 500 IDs.
Context products are always excluded automatically.
## Copy-paste recommendation placements
Call `recommend` after the hosted loader is ready. Giving the loader script an ID makes that easy on a server-rendered storefront:
```html theme={null}
```
Keep the queued `virtualfit('init', ...)` block before the loader, as shown in the [Custom JavaScript quickstart](/custom-js/quickstart).
### Product page: similar products
The current synced product is supplied automatically. This example renders a basic accessible row and leaves the placement hidden if recommendations are unavailable:
```html theme={null}
```
### Cart drawer: likely purchases
Always read the full live cart after an add, removal, quantity change, or checkout. `productIds: []` makes this a cart-only request instead of also using the product page behind the drawer:
```javascript theme={null}
let cartRecommendationRequest = 0;
async function refreshCartRecommendations(cart) {
const request = ++cartRecommendationRequest;
const cartProductIds = cart.items.map((item) => String(item.productId));
if (cartProductIds.length === 0) {
renderCartRecommendations([]);
return;
}
try {
const result = await window.VirtualFit.recommend({
intent: 'likely_purchases',
productIds: [],
cartProductIds,
excludeProductIds: unavailableProductIds,
limit: 8
});
if (request !== cartRecommendationRequest) return;
renderCartRecommendations(
result.fallbackUsed ? existingMerchandisingFallback : result.items
);
} catch (error) {
if (request !== cartRecommendationRequest) return;
renderCartRecommendations(existingMerchandisingFallback);
}
}
whenVirtualFitReady(() => {
cartStore.subscribe((cart) => {
refreshCartRecommendations(cart);
});
});
```
Omit `productIds: []` when you want the current product or fitting-room selection to augment the cart instead. The request counter prevents a slower response for an older cart from replacing recommendations for the latest cart.
### Custom outfit builder: complete the look
Send the complete current outfit whenever a shopper adds or removes an item. The first product is treated as the primary outfit item and all supplied products are excluded from results automatically:
```javascript theme={null}
let outfitRecommendationRequest = 0;
async function refreshOutfitRecommendations(selectedProducts) {
const request = ++outfitRecommendationRequest;
const productIds = selectedProducts
.map((product) => String(product.id))
.slice(0, 5);
if (productIds.length === 0) {
renderOutfitRecommendations([]);
return;
}
try {
const result = await window.VirtualFit.recommend({
intent: 'complete_the_look',
productIds,
excludeProductIds: hiddenOrUnavailableProductIds,
limit: 8
});
if (request !== outfitRecommendationRequest) return;
renderOutfitRecommendations(result.items);
} catch (error) {
if (request !== outfitRecommendationRequest) return;
renderOutfitRecommendations([]);
}
}
```
An empty `items` array is a valid result when there is no compatible open outfit category. Hide the row instead of replacing it with unrelated products.
### Load another page
Pass the returned cursor with the same context and intent:
```javascript theme={null}
const firstPage = await window.VirtualFit.recommend({
intent: 'likely_purchases',
cartProductIds: currentCartProductIds,
limit: 8
});
if (firstPage.nextCursor) {
const nextPage = await window.VirtualFit.recommend({
intent: 'likely_purchases',
cartProductIds: currentCartProductIds,
cursor: firstPage.nextCursor,
limit: 8
});
appendRecommendationCards(nextPage.items);
}
```
The promise resolves to:
```javascript theme={null}
{
items: [
{
product_id: 'leather-loafer',
target_type: 'variant',
variant_id: 'leather-loafer-black-38',
rank: 1,
score: 1.274,
title: 'Leather Loafer',
preview_image_url: 'https://cdn.example.com/loafer.jpg'
}
],
nextCursor: null,
fallbackUsed: false
}
```
Items are in display order, and `rank` is authoritative. `score` is optional and meaningful only within that response. Do not re-sort items by score or compare scores across requests.
A recommendation may target the whole product, a visual choice, or one exact variant. Render one card per product. When `variant_id` is present, use it to preselect the recommended variant or pass it as `variantId` after navigation. virtual.fit does not return several cards for different variants of the same product.
Keep your existing merchandising order as the placement fallback when a request fails.
An empty successful `complete_the_look` response is valid when the outfit has no compatible open slot or no eligible product is available for that slot. Hide the empty row instead of filling it with unrelated products.
## `track`
Send a commerce event.
```javascript theme={null}
virtualfit('track', 'product_added_to_cart', {
cartId: 'cart-123',
quantity: 1,
totalAmount: 79,
currency: 'USD',
productId: 'sku-10042',
productHandle: 'linen-midi-dress',
productTitle: 'Linen Midi Dress'
});
```
virtual.fit adds the current product context when it is available. Explicit payload fields take precedence.
Only call `track` after storefront analytics has initialized. Events sent before analytics is ready are not queued and may be dropped with a console warning.
[See the commerce event reference →](/custom-js/commerce-events)
## Object-style alias
The loader also exposes `window.VirtualFit`:
```javascript theme={null}
window.VirtualFit.setProduct({
id: 'sku-10042',
handle: 'linen-midi-dress'
});
```
Available methods are `init`, `setContext`, `setProduct`, `setCustomer`, `setConsentMode`, `recommend`, and `track`. Prefer the queued `virtualfit(...)` form for commands that do not return a value. Call `recommend` after the hosted loader has initialized because it returns a promise with the ranked products.
## SPA integration pattern
```javascript theme={null}
router.afterEach((route) => {
if (route.type !== 'product') return;
virtualfit('setProduct', {
id: route.product.id,
handle: route.product.handle,
title: route.product.title,
imageUrl: route.product.featuredImage,
variantId: route.selectedVariant?.id || '',
variantImageUrl: route.selectedVariant?.featuredImage || ''
});
});
```
Keep one loader and one initialization per page. Update context instead of injecting another script after each route or variant change.
# Sync the catalog
Source: https://docs.virtual.fit/custom-js/catalog
Sync custom storefront products, variants, prices, inventory, media, and size charts.
virtual.fit resolves storefront products from your synced catalog. Use the management API for continuous server-to-server sync. Use CSV for scheduled or manual imports.
The current contract is schema version 2. Omit `schema_version` for all new integrations. Send `schema_version: 1` only from an existing image-only integration that needs legacy update behavior.
Send management API requests to `https://api.virtual.fit`.
## Choose a sync method
Push changes as they happen. This is the best option when your backend knows the current variants, prices, or inventory.
```bash theme={null}
curl --request PUT \
"https://api.virtual.fit/vfr/manage/sites/$SITE_ID/products/$PRODUCT_ID" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY" \
--header "Content-Type: application/json" \
--data @product.json
```
Keep the API key on your server. Never include it in storefront JavaScript.
Import a file where each row describes a product-level update or one exact variant. Repeat `product_id` for each additional variant.
```csv theme={null}
product_id,title,product_image_url,variants_complete,variant_id,option_values_json,variant_available,inventory_quantity,variant_price,currency
dress-10042,Floral Midi Dress,https://cdn.example.com/floral-front.jpg,true,floral-petite-2,"{""color"":""Floral"",""fit"":""Petite"",""size"":""2""}",true,4,79.00,USD
```
Omitted `schema_version` also means version 2 in CSV.
## Find your site ID
In virtual.fit, open **Custom JS → Sync Products** and copy the **Storefront Site ID** from the
Storefront Credentials section. The site ID is a UUID used in the `site_id` path parameter. It is
different from the public site key, your workspace ID, and any ID from your commerce platform.
For server-side discovery, call the current-site endpoint with your API key and store the returned
`site.id` value for later requests:
```bash theme={null}
curl --request GET \
"https://api.virtual.fit/vfr/manage/sites/current" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY"
```
## Start with the smallest useful product
You can send the title and image first. Add variants, stock, prices, options, and size charts later under the same product ID.
```json theme={null}
{
"title": "Floral Midi Dress",
"images": [
{
"url": "https://cdn.example.com/floral-front.jpg"
}
]
}
```
For a new product, include:
* A stable product ID in the request URL or `product_id` CSV column.
* `title`.
* At least one public product image.
Omitted fields stay unchanged on later updates. This lets a feed publish the
essentials quickly and enrich the product progressively.
### Choose a durable product ID
`product_id` is the permanent identity of the product inside one site. It is
case-sensitive and can be a numeric ID, UUID, or URL-safe string.
* Prefer an immutable catalog or database ID.
* Keep one ID for the product when prices, images, options, or variants change.
* Do not derive it from the title, URL, handle, or current variant combination.
* Keep it within 255 UTF-8 bytes and URL-encode it in API paths.
A product can begin without variants and gain them later under the same
`product_id`. This does not create a second product or require a migration.
## Send products with variants
A product holds shared merchandising data. A variant holds one exact purchasable combination, such as `Floral / Petite / 2`.
```json theme={null}
{
"title": "Floral Midi Dress",
"handle": "floral-midi-dress",
"canonical_url": "https://shop.example/products/floral-midi-dress",
"brand": "Example Fashion",
"price": {
"amount": "79.00",
"currency": "USD"
},
"compare_at_price": {
"amount": "99.00",
"currency": "USD"
},
"images": [
{
"external_media_id": "floral-front",
"url": "https://cdn.example.com/floral-front.jpg",
"position": 0
}
],
"options": [
{
"key": "color",
"source_name": "Colour",
"kind": "visual",
"presentation_role": "include",
"position": 0,
"values": [
{
"source_value": "Floral",
"display_label": "Floral",
"swatch": {
"image_url": "https://cdn.example.com/floral-swatch.jpg"
}
}
]
},
{
"key": "fit",
"source_name": "Fit",
"kind": "fit",
"presentation_role": "exclude",
"position": 1,
"values": [
{
"source_value": "Petite",
"display_label": "Petite"
}
]
},
{
"key": "size",
"source_name": "US Size",
"kind": "size",
"presentation_role": "exclude",
"size_system_code": "us",
"size_audience_code": "womens",
"size_category_code": "apparel",
"position": 2,
"values": [
{
"source_value": "2",
"display_label": "2"
}
]
}
],
"variants_complete": true,
"variants": [
{
"source_variant_id": "floral-petite-2",
"title": "Floral / Petite / 2",
"sku": "FLORAL-P-2",
"canonical_url": "https://shop.example/products/floral-midi-dress?variant=floral-petite-2",
"option_values": {
"color": "Floral",
"fit": "Petite",
"size": "2"
},
"available": true,
"inventory_quantity": 4,
"inventory_observed_at": "2026-07-25T10:00:00Z",
"price": {
"amount": "79.00",
"currency": "USD"
},
"compare_at_price": {
"amount": "99.00",
"currency": "USD"
},
"media": [
{
"external_media_id": "floral-front"
}
]
}
],
"size_charts": [
{
"external_id": "womens-petite",
"url": "https://shop.example/pages/womens-petite-size-chart",
"applies_to": {
"fit": "Petite"
},
"size_system_code": "us",
"size_audience_code": "womens",
"size_category_code": "apparel"
}
],
"enabled": true
}
```
Send only combinations that shoppers can actually select. Option values describe available choices; they do not create a Cartesian product of variants.
## Send stock updates
Use the same product upsert endpoint when stock changes. For an existing product,
send only the changed variants. You do not need to resend the title, images,
prices, or unchanged variants.
Identify each variant by the same `source_variant_id` used during the initial
sync.
```bash theme={null}
curl --request PUT \
"https://api.virtual.fit/vfr/manage/sites/$SITE_ID/products/dress-10042" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"variants": [
{
"source_variant_id": "floral-petite-2",
"available": false,
"inventory_quantity": 0,
"inventory_observed_at": "2026-08-01T09:30:00Z"
}
]
}'
```
Send product-level `available` when your source has no exact variants. A
product-level update cannot include an inventory quantity.
```bash theme={null}
curl --request PUT \
"https://api.virtual.fit/vfr/manage/sites/$SITE_ID/products/dress-10042" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"available": false
}'
```
If the product gains variants later, send stock on each exact variant.
Variant availability takes precedence over product-level availability.
For exact variants:
* Send `available: true` when the variant can be purchased and `false` when it is sold out.
* Send `inventory_quantity` when your source provides an exact count. Quantity alone does not set `available`.
* Send `inventory_observed_at` as the RFC 3339 time when your source reported the stock. If you omit it, virtual.fit uses the request time.
* Keep the timestamp from the source. An older observation does not replace newer stock for the same variant.
* Omit `variants_complete` from a targeted stock update. Set it to `true` only when the request contains the complete authoritative variant list.
* Refresh stock regularly. virtual.fit treats stale inventory as unknown instead of claiming that a variant is in stock.
`enabled` controls whether the product can use the fitting room. It is not a
stock field. Keep `enabled` unchanged when only inventory changes. For an
existing product, omitting it from an upsert preserves the current state; use
the dedicated enable-state endpoint when changing availability by itself.
## Field reference
Fields are ordered by how commonly a new integration needs them. **Auto-detected
when omitted** means virtual.fit derives the value from the supplied variants,
option names, swatches, or media.
Stable product ID in the request URL. Keep it unchanged when variants,
prices, inventory, or media change.
Shopper-facing product name. Required when creating a product.
Shared product media. A new product needs at least one public image. See
the [image object reference](/reference/schemas/catalog-image).
Public HTTP or HTTPS image URL.
Stable media ID from your source. Use it to reference this image from
variant `media`.
Source alt text.
Source-defined role. Prefer `front`, `back`, or `side` for those
views. `featured`, `primary`, and `gallery` are also accepted.
Zero-based display order.
Optional source width in pixels.
Optional source height in pixels.
**Required for most Custom JavaScript storefronts.** Send the stable
storefront slug when the site resolves product URLs by handle. You may
omit it only when URL resolution uses `product_id`.
Public canonical product URL. Must use HTTP or HTTPS.
Whether the product is enabled in the fitting room. This is separate from upstream sale availability.
Current source-reported sale availability when it is known. Omit or send
`null` when unknown. Usually derived from exact variants or synced from the
source; variant availability is more precise when variants exist.
Current overall customer rating on a 0–5 scale. Omit when the source does
not expose an aggregate rating.
Number of customer reviews included in the current overall rating. Must
be zero or greater.
Product-level selling price. A variant price overrides it for that
variant. Expand for the exact object shape.
Decimal amount as a string, such as `"79.00"`.
Three-letter ISO 4217 currency code, such as `USD` or `EUR`.
Product-level original or pre-sale price. Uses the same `amount` and
`currency` shape as `price`.
Exact purchasable combinations. An empty array is valid. Expand for
variant identity, selections, inventory, pricing, and media fields, or
open the [variant object reference](/reference/schemas/catalog-variant).
Stable source ID for this exact combination. Required unless
`option_values` uniquely identifies the variant.
Shopper-facing variant label, such as `Floral / Petite / 2`.
Merchant SKU.
Public URL that opens this exact variant. When omitted,
recommendations use the product `canonical_url`.
Exact option key-to-value selection, for example
`{"color":"Floral","fit":"Petite","size":"2"}`. Keys and values must
match declared options when `options` is supplied.
Whether this exact variant can currently be purchased. Omit or send
`null` when unknown.
Known inventory quantity. Omit when the source does not expose it.
RFC 3339 timestamp for the inventory observation.
Unmodified inventory policy from the source system.
Stable source inventory-item ID.
Variant selling price. Uses `amount` as a decimal string and
`currency` as a three-letter ISO 4217 code.
Variant original or pre-sale price. Uses the same shape as
`variants[].price`.
Public primary image for this variant.
Variant-specific media. Reference a shared image by
`external_media_id`, or provide a public `url`.
ID of an item in product `images`.
Public HTTP or HTTPS URL when the media is not already in product
`images`.
Source-defined role such as `primary`, `front`, or `back`.
Zero-based display order.
When `true`, the supplied variant list is authoritative. Omitted variants become inactive. Send `true` with `variants: []` for a genuinely variantless product.
Choice axes, labels, swatches, and size metadata. **Auto-detected when
omitted:** virtual.fit derives the minimum option structure from
`variants[].option_values`. Send `options` when you have source labels,
ordering, swatches, or explicit size metadata. See the
[option object reference](/reference/schemas/catalog-option).
Stable machine key such as `color`, `fit`, or `size`. Variant
`option_values` must use the same key.
Merchant label such as `Colour` or `US Size`. **Auto-detected when
omitted:** defaults to `key`.
**Auto-detected when omitted.** Accepted values:
* `visual` — color, pattern, print, wash, or finish.
* `style` — another choice that changes the visible garment shape or design.
* `size` — numeric, alpha, or shoe size.
* `fit` — petite, regular, tall, body type, or fit family.
* `length` — length or inseam.
* `width` — footwear or garment width.
* `other` — a source-specific choice that does not match the above.
Accepted values:
* `auto` — infer visual identity from the option kind, swatches, and variant media.
* `include` — always treat the option as changing the visible product.
* `exclude` — never split visual identity on this option.
Option display order.
Normalized system for a sizing option. Use one of:
* Geographic systems: `us`, `eu`, `uk`, `au`, `jp`, `cn`, `kr`.
* International letters: `intl_alpha`.
* Measurements: `inch`, `cm`, `mondopoint`.
* Special cases: `brand_specific`, `one_size`, `unknown`.
Who the sizing is designed for. Use `womens`, `mens`, `unisex`,
`kids`, `youth`, `baby`, or `unknown`.
What kind of sizing the values describe. Use `apparel`, `footwear`,
`denim`, `bra`, `hosiery`, `accessories`, or `unknown`.
Original source label when it does not map cleanly to a normalized
size system.
Declared values for this option.
Exact value used by variant `option_values`.
Shopper-facing label. **Auto-detected when omitted:** defaults to
`source_value`.
Optional normalized value when the source value is unusual.
Value display order.
Optional color, multi-color, or image swatch. Image swatches support
patterns and textures.
Primary CSS color value.
Ordered CSS color values for a multi-color swatch.
Public HTTP or HTTPS swatch image for a pattern or texture.
Optional source CSS value when a color or image is insufficient.
Accessible swatch label. Defaults to the option value label.
Product-wide or option-scoped size chart references. Stored now for
future size-aware recommendations; they do not change today's visual
recommendation ranking. See the
[size-chart reference](/reference/schemas/catalog-size-chart).
Stable chart ID from the source.
Public HTTP or HTTPS size chart page or asset. A URL alone is valid
and allows a later enrichment step to add structured data.
Optional structured chart data when the source already provides it.
Option key-to-value selector, for example `{"fit":"Petite"}`. Omit
when the chart applies to the whole product.
BCP 47 locale such as `en-US` or `de-DE`.
Normalized size system. Uses the same accepted values as
`options[].size_system_code`.
Sizing audience. Uses the same accepted values as
`options[].size_audience_code`.
Sizing category. Uses the same accepted values as
`options[].size_category_code`.
Optional measured garment dimensions by size. Use canonical dimension
names such as `bust`, `chest`, `waist`, `hips`, `shoulder_width`,
`sleeve_length`, `total_length`, `inseam`, `front_rise`, `back_rise`,
`thigh`, or `leg_opening`. Use `cm` or `in`.
Canonical dimension name.
Non-negative measured value.
`cm` or `in`. virtual.fit normalizes length internally.
Source size this measurement describes, such as `Petite / 4`.
Short source label such as `merchant`.
Optional confidence from `0` to `1`.
Optional product-page model or mannequin fit facts. Send the worn size
and any source-reported body measurements. These fields can improve
future size recommendations and remain optional.
Brand or designer name.
Merchant-facing product type. Usually populated automatically when the
source exposes it.
Optional plain-text product description. Useful enrichment, but not
required for fitting-room product matching.
Optional product-specific try-on guidance.
Optional concise garment naming override used to describe the item during
try-on. **Auto-detected when omitted.**
Whether the product still exists and is active in the source catalog.
Send `false` for archived or removed products.
Optional unmodified status from the source system, such as `ACTIVE`,
`ARCHIVED`, or `DRAFT`. It is preserved for diagnostics and is not a
normalized enum.
RFC 3339 timestamp for the source record. Usually populated automatically.
Omit for the current contract. The only accepted explicit values are `1`
for a legacy image-only request and `2` for the current contract.
Optional ordering and idempotency metadata for multi-worker progressive syncs.
Use `ingest` only when several workers may update one product or events
may arrive out of order.
Unique event ID. Reusing it with a different payload is rejected.
ID shared by events from one sync run.
Positive sequence number within the run.
Stable name for the worker or feed.
RFC 3339 time when the source was observed.
Fields represented by this event.
Collections complete in this event. Accepted values are `images`,
`options`, `variants`, and `size_charts`. A completed `variants`
collection also requires `variants_complete: true`.
## Variant and media behavior
* A product may have no variants. Send `variants_complete: true` with `variants: []`.
* If variants appear later, keep the same product ID and send the new variant list.
* Size-only variants normally share product media.
* Color, pattern, material, and style variants can reference distinct media.
* Shared media is stored and prepared once even when several variants reference it.
* A swatch image represents the selector. Variant media represents the garment used for display and try-on.
virtual.fit recommends at most one result per product. A result may identify the best exact variant or the best visual choice within the product. When fresh inventory is known, exact variant results must be available. When availability is unknown, virtual.fit does not claim that a variant is in stock.
## Visual choices
You do not create presentation IDs. virtual.fit derives visual choices from option meaning, swatches, and variant media.
Use:
* `presentation_role: "include"` when an option changes the visible garment.
* `presentation_role: "exclude"` for size, fit, length, and other non-visual choices.
* `presentation_role: "auto"` when virtual.fit should infer the behavior.
If variant media clearly changes with an option such as color, virtual.fit can infer that the option is visual. Explicit roles remain useful when source media is incomplete or ambiguous.
## Size charts
Use one chart without `applies_to` when it applies to every variant. Use a selector when petite, regular, tall, or another option value uses a different chart.
A chart may contain:
* A public `url`.
* Extracted structured `content`.
* Both a URL and structured content.
If you omit size metadata, virtual.fit preserves the source size values but
does not guess their geographic system, audience, or category. These three
fields are independent: for example, `us` + `womens` + `footwear` is different
from `us` + `youth` + `footwear`. Petite, regular, and tall remain option values
such as `fit`, and `applies_to` selects the chart for each fit.
Reusing the same chart URL or stable `external_id` across products allows
virtual.fit to share the stored chart document while keeping each product's
`applies_to` selector.
## Optional review evidence
You do not need to send reviews. virtual.fit can collect public review evidence
when it prepares a product.
If your backend already receives complete review records, you can sync them
after creating the product. The optional review endpoint accepts each review's
stars, full text, purchased variant, customer photos or videos, and
source-reported measurements or fit votes. virtual.fit analyzes review text
asynchronously, so review enrichment never blocks the product from becoming
ready.
Use a stable source review ID whenever one exists. Send each review as its
complete current record so removing media or structured evidence is
unambiguous. See [Sync product reviews](/reference/catalog-reviews).
The storefront can request the compact
[fit summary](/reference/storefront-fit-evidence) for fast product display and
load [full paginated reviews](/reference/storefront-product-reviews) only when
the shopper asks to inspect the evidence.
## Partial updates and clearing data
For an existing product:
* An omitted field stays unchanged.
* An explicit `null` clears a supported field or collection.
* `variants_complete: true` makes the supplied variant list authoritative.
* A plain partial variant update does not remove omitted variants.
You may clear `handle`, `preview_image_url`, `brand`, `description`,
`product_type`, prices, availability, rating, review count, custom
instructions, images, options, variants, size charts, garment measurements, or
model observations.
```json theme={null}
{
"description": null,
"size_charts": null,
"garment_measurements": null
}
```
Clearing `options` removes your supplied labels and swatches. If active variants remain, virtual.fit retains the minimum option structure required to describe them.
### Order updates from multiple workers
Add `ingest` metadata when several workers may update one product or when events
may arrive out of order. The event and sequence fields make the complete update
idempotent and ordered.
```json theme={null}
{
"variants": [
{
"source_variant_id": "floral-petite-2",
"available": false,
"inventory_quantity": 0,
"inventory_observed_at": "2026-07-25T11:00:00Z"
}
],
"ingest": {
"event_id": "inventory-4281",
"run_id": "catalog-sync-2026-07-25",
"sequence": 12,
"producer": "inventory-sync",
"observed_at": "2026-07-25T11:00:00Z",
"observed_fields": ["variants"]
}
}
```
## Delete catalog data
Use `DELETE` when the product should be removed from the synced catalog. This
permanently removes the synced product record and its managed product images:
```bash theme={null}
curl --request DELETE \
"https://api.virtual.fit/vfr/manage/sites/$SITE_ID/products/dress-10042" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY"
```
The canonical catalog retains a deletion tombstone so a stale source snapshot
cannot serve the product again. Syncing the same product ID later creates it
again and clears the tombstone.
Use the enable-state endpoint when you only want to hide a product temporarily
or preserve its diagnostic history. Deletion removes the synced record and
managed images.
To keep the product and its images while removing it from the fitting room, set
its enabled state:
```bash theme={null}
curl --request PUT \
"https://api.virtual.fit/vfr/manage/sites/$SITE_ID/products/dress-10042/enabled" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY" \
--header "Content-Type: application/json" \
--data '{"enabled":false}'
```
Send `{"enabled":true}` to re-enable it. Disabled products remain in the
product count, but do not consume enabled-product slots.
Delete one variant:
```bash theme={null}
curl --request DELETE \
"https://api.virtual.fit/vfr/manage/sites/$SITE_ID/products/dress-10042/variants/floral-petite-2" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY"
```
The variant path accepts the stable source variant ID used during sync.
## CSV format
Each CSV upload is a synchronous import of at most 1,000 rows. Split larger
catalogs into multiple files. Product and variant upserts are idempotent, so it
is safe to retry a file; if an infrastructure failure occurs after processing
starts, rows already saved remain saved.
Omit `schema_version`; version 2 is the default. Repeat the product ID on
each variant row. Blank product-level cells on later rows inherit the first
row for that product.
```csv theme={null}
product_id,title,handle,canonical_url,product_image_url,rating,review_count,options_json,variants_complete,variant_id,variant_canonical_url,option_values_json,variant_image_url,variant_available,inventory_quantity,inventory_observed_at,variant_price,variant_compare_at_price,currency,size_chart_url
dress-10042,Floral Midi Dress,floral-midi-dress,https://shop.example/products/floral-midi-dress,https://cdn.example.com/floral-front.jpg,4.7,128,"[{""key"":""color"",""source_name"":""Colour"",""kind"":""visual"",""presentation_role"":""include"",""values"":[{""source_value"":""Floral"",""display_label"":""Floral"",""swatch"":{""image_url"":""https://cdn.example.com/floral-swatch.jpg""}}]}]",true,floral-petite-2,https://shop.example/products/floral-midi-dress?variant=floral-petite-2,"{""color"":""Floral"",""fit"":""Petite"",""size"":""2""}",https://cdn.example.com/floral-front.jpg,true,4,2026-07-25T10:00:00Z,79.00,99.00,USD,https://shop.example/pages/size-chart
```
Include `operation`.
* `operation=delete` with an empty `variant_id` deletes the product.
* `operation=delete` with `product_id` and `variant_id` deletes that variant.
```csv theme={null}
operation,product_id,variant_id,title,product_image_url
delete,dress-10042,floral-petite-2,,
```
Existing image-only importers can set `schema_version` to `1`. Version 1 supports product identity, titles, handles, enabled state, preview images, prompt fields, and product image URLs.
```csv theme={null}
schema_version,product_id,title,handle,product_image_url,enabled
1,dress-10042,Floral Midi Dress,floral-midi-dress,https://cdn.example.com/floral-front.jpg,true
```
Version 1 does not accept variants, options, prices, inventory, size charts, or delete rows. If those fields are present, the import explains which fields require the current contract.
## Legacy JSON compatibility
Use an explicit legacy version only while an existing image-only integration is being migrated:
```json theme={null}
{
"schema_version": 1,
"title": "Floral Midi Dress",
"handle": "floral-midi-dress",
"product_image_url": "https://cdn.example.com/floral-front.jpg",
"enabled": true
}
```
Do not add current fields to a version 1 request. If virtual.fit detects fields such as `options`, `variants`, prices, inventory, or size charts, it returns a message that lists the incompatible fields and tells you to omit `schema_version`.
## Image requirements
Image URLs must be reachable without shopper cookies, expiring browser sessions, or IP-bound authorization.
Use stable HTTPS CDN URLs and clear, high-resolution JPEG, PNG, or WebP images up to 64 MB. Avoid short-lived signed URLs unless they remain available during preparation and later refreshes.
Prefer images that show the complete sold product on a model or mannequin.
When available, send front, back, and side views. These views provide a more
useful fit reference than a flat lay or isolated ghost image and generally
produce more accurate try-on results.
Flat-lay, ghost, and product-only images are still accepted. virtual.fit
automatically analyzes, deduplicates, and selects the strongest prepared views
without modifying the originals. When a photo contains several garments, also
include a view where the sold item is unambiguous.
## Input limits
Limits are intentionally generous enough for large catalogs while preventing a
single malformed request from consuming unbounded memory or database space.
Limits apply equally to JSON and CSV values.
| Input | Limit |
| ----------------------------------------------- | -------------------------------------------- |
| JSON product body | 4 MiB |
| CSV file | 32 MiB and 1,000 rows per synchronous import |
| Product IDs, handles, variant IDs, SKUs, labels | 255 UTF-8 bytes each |
| Product title | 500 UTF-8 bytes |
| Description | 64 KiB |
| Custom instructions | 4 KiB |
| URL | 8 KiB |
| Images per product | 500 |
| Options per product | 20 |
| Values per option | 1,000 |
| Variants per product | 5,000 |
| Media references per variant | 100 |
| Size-chart references per product | 50 |
| Structured size-chart content | 256 KiB each |
| Garment measurements per product | 250 |
| Model observations per product | 50 |
A request that exceeds a byte or collection limit returns `413` with the field
that must be reduced. Invalid values within the limits return `400`.
## Common sync failures
| Failure | Fix |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Missing values on a new product | Include a title and at least one product image. |
| A version 1 request contains current fields | Remove `schema_version` to use the current contract, or remove the listed unsupported fields. |
| Image preparation never completes | Confirm the URL is public, stable, no larger than 64 MB, and returns an image content type. |
| A variant is rejected | Declare matching option keys and values, or send the variant without conflicting option definitions. |
| A variant disappears unexpectedly | Use `variants_complete: true` only when the supplied list is authoritative. |
| URL matching finds no product | Keep the product ID and handle aligned with your configured URL resolution. |
Never call the management API from browser JavaScript. Its API key can modify catalog data and must remain server-side.
# Commerce events
Source: https://docs.virtual.fit/custom-js/commerce-events
Track cart, checkout, and purchase outcomes for Custom JavaScript storefront analytics.
Custom storefronts must send commerce events so virtual.fit can connect fitting-room usage to cart and purchase outcomes. Try-on views, opens, uploads, starts, completions, and failures are recorded automatically.
## Event reference
| Event | Send when | Product fields | Amount |
| ---------------------------- | --------------------------------------- | --------------------------------- | --------------------------------- |
| `product_added_to_cart` | A product is successfully added to cart | Required | Line total for the added quantity |
| `checkout_started_line_item` | Checkout starts | One event per line item | Line total |
| `checkout_completed` | The order or checkout completes | Not required | Full order total |
| `purchase_line_item` | The order completes | One event per purchased line item | Line total |
Do not send one aggregate product event for a multi-item checkout. Send one line-item event per product, then one checkout-level completion event.
## Set shopper identity
Attach customer context before sending commerce events:
```javascript theme={null}
virtualfit('setCustomer', {
id: currentCustomer?.id || '',
email: currentCustomer?.email || ''
});
```
For logged-out shoppers, omit the fields or pass empty strings. virtual.fit maintains anonymous journey context according to the active consent mode.
## Add to cart
Send after your cart API confirms success, not when the shopper merely clicks the button.
```javascript theme={null}
virtualfit('track', 'product_added_to_cart', {
cartId: 'cart-123',
quantity: 2,
totalAmount: 158,
currency: 'USD',
productId: 'sku-10042',
productHandle: 'linen-midi-dress',
productTitle: 'Linen Midi Dress'
});
```
Before adding manual tracking, check whether a successful add-to-cart already appears in virtual.fit. Do not send a duplicate event.
## Checkout started
Send one event for each checkout line item.
```javascript theme={null}
checkout.lineItems.forEach((lineItem) => {
virtualfit('track', 'checkout_started_line_item', {
cartId: checkout.cartId,
checkoutId: checkout.id,
quantity: lineItem.quantity,
totalAmount: lineItem.lineTotal,
currency: checkout.currency,
productId: lineItem.productId,
productHandle: lineItem.productHandle,
productTitle: lineItem.productTitle
});
});
```
## Purchase completed
Send one checkout-level completion, followed by one event per purchased line item.
```javascript theme={null}
virtualfit('track', 'checkout_completed', {
cartId: order.cartId,
checkoutId: order.checkoutId,
orderId: order.id,
currency: order.currency,
totalAmount: order.total
});
order.lineItems.forEach((lineItem) => {
virtualfit('track', 'purchase_line_item', {
cartId: order.cartId,
checkoutId: order.checkoutId,
orderId: order.id,
quantity: lineItem.quantity,
totalAmount: lineItem.lineTotal,
currency: order.currency,
productId: lineItem.productId,
productHandle: lineItem.productHandle,
productTitle: lineItem.productTitle
});
});
```
## Payload fields
| Field | Type | Description |
| --------------- | -------- | -------------------------------------------------------------- |
| `cartId` | `string` | Stable cart identifier shared across cart and checkout events. |
| `checkoutId` | `string` | Stable checkout identifier. |
| `orderId` | `string` | Completed order identifier. |
| `quantity` | `number` | Quantity represented by this line-item event. |
| `totalAmount` | `number` | Numeric line or order total, without a currency symbol. |
| `currency` | `string` | Uppercase ISO 4217 code such as `USD` or `EUR`. |
| `productId` | `string` | Same external product ID synced to virtual.fit. |
| `productHandle` | `string` | Same handle synced to virtual.fit. |
| `productTitle` | `string` | Display title at the time of the event. |
## Correctness rules
* Send events only after the business action succeeds.
* Use stable IDs across the whole journey.
* Use line totals for line-item events and order totals for `checkout_completed`.
* Keep amounts in the stated currency; do not send formatted strings.
* Avoid duplicate events from click handlers, cart callbacks, and tag managers.
* Call `setCustomer` after identity changes.
* Respect analytics consent before including identity.
## Verify events
1. Use a unique test product and cart.
2. Complete one try-on.
3. Add the product to cart.
4. Start checkout.
5. Complete a test order if your environment supports it.
6. Open **Virtual Fitting Room → Analytics** and confirm each funnel stage increments once.
If a stage is missing, verify that the event is sent only after the corresponding cart, checkout, or order action succeeds and that its product ID matches the synced catalog record.
# Loader configuration
Source: https://docs.virtual.fit/custom-js/configuration
Configure placement, product context, customer access, terms, and data attributes.
Initialize virtual.fit before loading the hosted script. The queue preserves commands until the loader is ready.
## Complete example
```html theme={null}
```
## Initialization fields
| Field | Type | Default | Description |
| ----------------------- | ------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------- |
| `siteKey` | `string` | Required | Public key shown in virtual.fit. |
| `mount` | CSS selector or `Element` | Automatic | Main product media host. Set this explicitly when automatic placement does not select the full gallery. |
| `overlayPosition` | `string` | `top-right` | `top-right`, `top-left`, `bottom-right`, or `bottom-left`. |
| `product` | `object` | URL-resolved | Optional explicit product context. |
| `customer` | `object` | Anonymous | Current customer `id` and optional `email`. |
| `auth` | `object` | Anonymous visible | Login visibility and destination. |
| `labels` | `object` | English defaults | Shopper-facing labels and messages. |
| `terms` | `object` | Default terms | Summary, full terms, and email controls. |
| `language` | `string` | `en` | Language identifier for terms configuration. |
| `overlayTargetSelector` | `string` | Automatic | Advanced gallery host override. |
| `overlayImageSelector` | `string` | `img` | Image inside the overlay target. |
| `gallerySelector` | `string` | Empty | Advanced result-gallery selector. |
| `thumbnailSelector` | `string` | Empty | Advanced thumbnail selector. |
Start with `siteKey`, `mount`, and terms. Add advanced selectors only after the basic integration works.
## Product object
```javascript theme={null}
{
id: 'dress-10042',
handle: 'linen-midi-dress',
title: 'Linen Midi Dress',
imageUrl: 'https://cdn.example.com/linen-midi-dress.jpg',
variantId: 'linen-black-petite-2',
variantImageUrl: 'https://cdn.example.com/linen-black.jpg'
}
```
Provide `id` or `handle`. The loader verifies it against the synced enabled catalog before mounting.
Stable product ID from catalog sync. Keep this ID unchanged when the shopper selects another variant.
Synced product handle. Provide `id` or `handle`.
Current shopper-facing title.
Product display fallback. It does not replace canonical prepared media.
Optional exact `source_variant_id` synced under the product.
Optional selected-variant display hint. Canonical synced variant media remains authoritative for try-on.
Call `setProduct` when a dynamic storefront changes the product or selected variant. See the [Browser API](/custom-js/browser-api#setproduct).
## Customer and authentication
```javascript theme={null}
auth: {
showToAnonymous: true,
loginUrl: ({ returnTo, product, location }) =>
'/login?return_to=' + encodeURIComponent(returnTo)
},
customer: {
id: 'customer-8421',
email: 'shopper@example.com'
}
```
`auth.loginUrl` accepts a string or callback. The callback receives:
* `returnTo` — Current absolute page URL.
* `product` — Resolved product context, or `null`.
* `location` — Current `href`, origin, pathname, search, and hash.
`showToAnonymous` controls whether a logged-out shopper can see a login call to action when your virtual.fit settings require authentication. The customer-access policy in virtual.fit remains authoritative.
## Terms object
```javascript theme={null}
terms: {
summaryHtml: 'AI preview only. Actual fit may differ.',
fullSelector: '#virtual-fit-terms',
collectEmail: false,
requireEmail: false,
emailNote: 'We will send this try-on result to the address you provide.'
}
```
Use one source for full terms:
* `fullHtml` — Pass full HTML directly.
* `fullSelector` — Read `innerHTML` from an existing host-page element.
If neither is set, virtual.fit uses its default terms. See [Styling, labels, and terms](/custom-js/styling-and-copy).
## Single-tag installation
When a platform allows one script tag but no inline queue, use data attributes:
```html theme={null}
```
JavaScript initialization is preferred when values are dynamic, variant selection changes after page load, or `loginUrl` needs callback logic.
## Legacy aliases
Use `terms` for disclaimer and legal content. Use `labels` for interface text. Older `content` and `ui` aliases remain accepted for existing installs, but new integrations should not depend on them.
# Resolve product URLs
Source: https://docs.virtual.fit/custom-js/product-resolution
Map custom storefront URLs to enabled virtual.fit catalog products.
Before rendering, virtual.fit matches the current page to a synced product. Configure one deterministic rule and test it with real storefront URLs.
## Resolution modes
| Mode | Example URL | Configuration | Extracted value |
| ----------------- | --------------------------------- | ------------------------------------ | ------------------- |
| Path template | `/products/linen-dress` | `/products/:handle` | `linen-dress` |
| Last path segment | `/collections/summer/linen-dress` | Match by handle | `linen-dress` |
| Query parameter | `/product?sku=sku-10042` | Parameter `sku`, match by product ID | `sku-10042` |
| Custom regex | `/shop/item/linen-dress` | `^/shop/item/([^/]+)$` | First capture group |
### Path template
Use a path template when product routes have a consistent structure.
```text theme={null}
/products/:handle
/shop/:handle
/p/:product_id
```
The token must match **Match Products By**. Use `:handle` when matching handles and `:product_id` when matching external product IDs.
### Last path segment
Use this only when the final path segment is always the product handle or ID.
```text theme={null}
/women/dresses/linen-midi-dress
└─ linen-midi-dress
```
Avoid it if locale, variant, or campaign segments can appear after the product value.
### Query parameter
Use this for routes that expose a stable product identifier in the query string.
```text theme={null}
/product?sku=sku-10042
```
Set **Query Parameter Name** to `sku` and match by **Product ID**.
### Custom regex
Use a custom regular expression only when the standard modes cannot represent the route. The first capture group becomes the product hint.
```regex theme={null}
^/shop/item/([^/]+)$
```
Keep the expression anchored and narrow. A broad regex can accidentally match category, search, or account pages.
## Test the rule
In virtual.fit's **Live URL Tester**:
1. Paste an absolute URL from the real storefront.
2. Confirm the extracted value.
3. Confirm the matched product title and ID.
4. Confirm the message says the product is enabled.
Test at least:
* A valid enabled product.
* A valid disabled product.
* An unknown product.
* A collection or search page.
* A localized route, if your storefront uses locales.
## Manual product context
For SPAs, query-driven PDPs, or routes that cannot be expressed by a rule, call `setProduct` after initialization:
```javascript theme={null}
window.virtualfit?.('setProduct', {
id: product.id,
handle: product.handle,
title: product.title,
imageUrl: product.featuredImage,
variantId: product.selectedVariant?.id || '',
variantImageUrl: product.selectedVariant?.featuredImage || ''
});
```
The `id` or `handle` must still identify a synced, enabled product. Manual context does not bypass its availability settings in virtual.fit.
Call `setProduct` again after your router commits each new product page and whenever the selected variant changes.
### Color and style variants
Keep one synced product ID for the product. Sync exact variants under it, including variant media when color, pattern, material, or style changes the garment.
```javascript theme={null}
virtualfit('setProduct', {
id: product.id,
handle: product.handle,
title: product.title,
imageUrl: product.featuredImage,
variantId: selectedVariant.id,
variantImageUrl: selectedVariant.featuredImage
});
```
`variantId` must match a `source_variant_id` synced under the product. `variantImageUrl` is a display hint; virtual.fit uses the canonical prepared media linked to the variant.
Size-only variants usually share the product's media. You can still send their `variantId` so availability and inventory refer to the exact purchasable combination.
Do not create duplicate product records for each color or size. One product with exact variants keeps recommendations product-level while still allowing virtual.fit to select the best in-stock visual variant.
## Fail-closed behavior
The widget stays hidden when:
* The rule extracts no value.
* The value does not match a synced product.
* The matched product is disabled.
* The matched product has no usable garment images.
This is expected behavior. Do not add a fallback product unless every unmatched page should deliberately use that product.
# Custom JavaScript quickstart
Source: https://docs.virtual.fit/custom-js/quickstart
Install the hosted virtual.fit loader on a custom or headless storefront.
The Custom JavaScript integration adds virtual.fit to any storefront that can load a hosted script. Your virtual.fit settings control product availability, shopper access, and daily limits.
## Prerequisites
Before installing the loader, you need:
* A custom storefront site in virtual.fit.
* Its public site key and hosted loader URL.
* An exact production or staging origin.
* One synced, enabled product with usable garment images.
* A CSS selector for the main product media wrapper.
The site key is public and belongs in browser code. Management API keys are secret and must never be embedded in the storefront.
## 1. Allow the storefront origin
In virtual.fit, open **Custom JS → Installation**. Add each origin that will load the widget or send analytics.
```text theme={null}
https://shop.example.com
https://staging-shop.example.com
```
An origin is the scheme, hostname, and optional port. Do not include paths, query strings, or trailing product URLs.
| Page URL | Allowed origin |
| ----------------------------------------------- | ---------------------------------- |
| `https://shop.example.com/products/linen-dress` | `https://shop.example.com` |
| `https://staging.example.com:8443/p/sku-42` | `https://staging.example.com:8443` |
## 2. Sync and enable one product
Use a CSV import or the management API to add a product. Its `handle` or `product_id` must match the value your product URL exposes.
For `/products/linen-midi-dress`, a typical management API request uses the
stable product ID in the URL:
```bash theme={null}
curl --request PUT \
"https://api.virtual.fit/vfr/manage/sites/$SITE_ID/products/sku-10042" \
--header "Authorization: Bearer $VIRTUAL_FIT_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"handle": "linen-midi-dress",
"title": "Linen Midi Dress",
"images": [
{"url": "https://cdn.example.com/linen-midi-dress-front.jpg", "role": "front"},
{"url": "https://cdn.example.com/linen-midi-dress-back.jpg", "role": "back"}
],
"enabled": true
}'
```
Prefer full-product front, back, and side views on a model or mannequin when
available. virtual.fit analyzes the images and chooses the strongest prepared
views automatically.
See [Sync the catalog](/custom-js/catalog) for CSV and API details.
## 3. Configure product URL detection
For a URL such as `https://shop.example.com/products/linen-midi-dress`:
* Set **Resolution Mode** to **Path template**.
* Set **Match Products By** to **Handle**.
* Set **Path Template** to `/products/:handle`.
Paste a real product URL into the virtual.fit live URL tester. Continue only when it reports an enabled matched product.
## 4. Install the loader
Copy the generated snippet from virtual.fit. The basic pattern is:
```html theme={null}
```
Place the snippet on product pages, usually before `