/shopify-hydrogen:hydrogen-variant-formfrom shopify-hydrogen
Behavioral guide for building product variant selection UI with @shopify/hydrogen. Use when writing, modifying, or reviewing product option selectors, variant pickers, or add-to-cart forms. Framework agnostic.
Ships in shopify-hydrogen. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
The product form primitive is a client-side store that computes per-option-value existence, availability, and selection state from Shopify's encoded variant fields. Variant selection performs no network requests; it is derived from product data provided by the Storefront API, combined with live cart state for error surfacing and line-item matching. Form submission is delegated to the cart store. Framework-specific bindings are thin wrappers over the core createProductFormStore.
The store holds a ProductFormStoreState and notifies subscribers on change. It is initialized with a product object and a CartStore instance. The product includes encodedVariantExistence, encodedVariantAvailability, product options (each with firstSelectableVariant per option value), a sparse variant cache (adjacentVariants), and a nullable selectedOrFirstAvailableVariant.
On initialization:
adjacentVariants + firstSelectableVariant per option value + selectedOrFirstAvailableVariant) to resolve a concrete variant object per option value where possible.selectedOrFirstAvailableVariant (server-resolved), falling back to explicitly provided selectedOptions, falling back to empty selection.CartStore to derive matchedLineItem and errors reactively.On selectOption(name, value):
selectedOptions and recomputes the full options grid.VariantSelectionResult: resolved (full variant matched), unresolved (valid, but no full variant resolved locally), or invalid (unknown or non-existent, with a reason string).The store does not own URL synchronization or navigation. Add-to-cart mutation logic belongs to the cart store and is reached through handleFormSubmit(event).
interface ProductFormStoreState<TVariant> {
options: VariantOptionState<TVariant>[];
selectedOptions: SelectedOption[];
selectedVariant: TVariant | null;
errors: ProductFormErrors;
matchedLineItem: CartLine | null;
}
options is the computed grid — one entry per product option, each containing its values:
value.name — the option value label (e.g. "Red", "Small").value.selected — whether this value is part of the current selection.value.exists — resolved from encodedVariantExistence when present. false means no variant exists for the current symmetric selection constraints — the control should be disabled and visually de-emphasized.value.available — resolved from encodedVariantAvailability when present. false means no available variant was found for the current symmetric selection constraints.value.variant — the resolved variant object, or null if the combination is not in the local cache.value.selectedOptions — the full option tuple that would result from selecting this value. Used for URL construction.value.handle — the product handle for this variant. Differs from the current product's handle in combined listings.selectedOptions is the current selection in product-option order (e.g. [{name: "Size", value: "Small"}, {name: "Color", value: "Red"}]).
selectedVariant is the currently resolved variant, or null when the selection is incomplete or the variant is not in the local cache.
errors surfaces cart errors relevant to this product form:
userErrors — merged cart-level and line-level user errors for the matched line item.warnings — merged cart-level and line-level warnings.networkErrors — cart network errors.matchedLineItem is the cart line whose merchandise.id matches the selected variant's ID, or null.
selectOption returns one of three outcomes:
resolved — a specific variant was matched. Contains selectedVariant with the full variant object and selectedOptions with the canonical option tuple from the variant.unresolved — the selection is valid, but no full variant is resolved locally because the selection is incomplete or the exact variant is absent from the bounded cache. If the buyer has not selected every option yet, ask for the remaining options. If the selection is complete but missing from the local cache, fetch or otherwise resolve the exact variant before treating it as complete.invalid — the option name or value does not exist on the product, or the combination does not exist per the encoded existence field. State is not updated. Contains a reason string explaining why the selection was rejected.The register function binds product form identity and activation handlers. It covers product-relevant fields. It intentionally does not emit option control UI props like checked, disabled, or aria-pressed; derive those from options, selectedVariant, and caller-owned state.
register("merchandiseId", opts)Returns { name: "merchandiseId", value: selectedVariantId }. The value is an empty string when no variant is resolved.
register("quantity", opts)Accepts { value: number } for a controlled input or { defaultValue: number } for an uncontrolled input. Returns the appropriate { name, value } or { name, defaultValue } props, with numeric values stringified for HTML form submission.
register("optionValue", opts)Requires { optionName, value }. Returns { name, value, onChange, onClick } — form identity plus activation handlers. Derive caller-owned UI props from the matching option value state, such as value.exists, value.available, and value.selected.
register("attributeValue", opts)Requires { key: string; value: string } (controlled) or { key: string; defaultValue: string } (uncontrolled). Returns { name: "attributes.<key>", value } — a hidden input that attaches a line-item attribute to the add-to-cart submission. Use for per-line metadata like engraving text, gift messages, or custom options. Multiple attributeValue fields can be registered for different keys. The key must be non-empty (throws TypeError otherwise). Attributes with keys starting with _ are conventionally internal/private and should not be set from the storefront UI.
register("addToCart", opts)Returns { name: "add-to-cart", type: "submit" } for the add-to-cart submit button.
handleFormSubmit(event) delegates to the underlying CartStore's form submission. The store does not own submission logic — it passes the SubmitEvent through to the cart layer, plus selected-product event detail when a variant is resolved. Cart errors from the submission are surfaced reactively via the errors state.
When creating a product detail page, use the app's existing route convention when present; otherwise create /products/{handle}. Keep variant selection in query params on that product route.
Before building product UI, check whether this skill has a reference file for the app's framework in references/. If one exists, read it and use that framework binding or route pattern first.
references/react.md — React Router (Link, useNavigate, useLocation).references/nextjs.md — Next.js App Router (next/link, next/navigation).references/nuxt.md — Nuxt (NuxtLink, Vue Router).If there is no matching reference, use createProductFormStore from @shopify/hydrogen directly, subscribe with the framework's reactivity primitive, and own hydration, URL sync, and destroy() yourself. Packaged bindings are thin wrappers over this same store — apply every rule and anti-pattern below; do not invent a different contract.
For example, in SolidStart or SvelteKit, write one select function that calls store.selectOption(name, value) and, when the result is not invalid, navigates once with the router (replace the history entry, keep scroll). This function takes the place of the provider onSelect. Render existing same-product values as native <a href> links. In the link click handler, apply the guard from the rules below, call event.preventDefault(), and then call your select function. The router's own link handling skips a click that is already prevented, so your select function is the only client navigation.
When the product data changes (e.g. after a URL navigation triggers a data refetch), the store must be hydrated with the new product — not recreated. hydrate(product, opts?) replaces the product data, clears the decoded variant cache, and recomputes state. The new product's selectedOrFirstAvailableVariant takes priority; if absent, falls back to explicitly provided opts.selectedOptions, then to the selection that was active before hydration.
Provider bindings should hydrate automatically when the product's semantic identity changes (product.id + selectedOrFirstAvailableVariant.id). They should skip hydration on mount to avoid double-initialization, and skip hydration when the product identity is unchanged — preserving user selections through unrelated re-renders. Standalone useProductForm(store) users manage hydration themselves.
reset() restores the store to its initial state — the product and selected options it was created with. It clears the decoded variant cache and recomputes all derived state. Useful for "reset form" interactions.
getSelectedProductOptions({ searchParams, allowedOptionNames }) extracts selected options from URLSearchParams. Each query parameter is treated as an option name/value pair (e.g. ?Color=Red&Size=M produces [{name:"Color",value:"Red"},{name:"Size",value:"M"}]).
Pass allowedOptionNames to filter search params to only known product option names, avoiding unrelated query parameters. Passing an empty array filters out every option.
The variant param is reserved for Liquid-style numeric variant ids and is never treated as an option name. Server-side, handleShopifyRoutes({ routeTemplates }) (see the local hydrogen-request-handlers skill) redirects ?variant=<id> product URLs to their canonical option-params URL before the loader runs; when both variant and option params are present, the variant wins.
buildProductSelectionSearchParams({ style?, selectedOptions, variant?, optionNames, base? }) builds the search params for a selection link. It always removes the reserved variant param and every param named in optionNames/selectedOptions from base before writing the new selection, preserving unrelated params (?ref=campaign). Compose it with the app's product pathname:
const params = buildProductSelectionSearchParams({
selectedOptions: result.selectedOptions,
optionNames: product.options.map((option) => option.name),
base: new URLSearchParams(location.search),
});
const url = `/products/${handle}${params.size ? `?${params}` : ""}`;
Pass style: "variant" with a resolved variant to emit a shareable ?variant=<numeric id> link instead of option params. When no variant is resolved (partial selection), the variant style falls back to option params — a variant link is not constructible. Prefer option-params links for in-app navigation; ?variant= links cost a server redirect on landing.
options.every((o) => o.values.length <= 1)). A single-variant product has nothing to choose — rendering its one option/one value is noise. This is distinct from the value-hiding rule below: it hides the whole picker when there's nothing to choose, not individual values based on selection.Medium / Olive is sold out, selecting Color=Olive should mark Size=Medium as unavailable even though Medium / Green is available.exists is false. These represent combinations that do not exist in the product's variant matrix. A non-existent combination cannot be selected — showing it as interactive is misleading.exists is true but available is false. These are sold-out variants. The control must remain interactive so the buyer can see what the variant would be. Show a "Sold out" indicator instead, such as opacity plus line-through styling.onSelect callback. Do not navigate inside each same-product option control. Let register("optionValue", ...) call selectOption; the provider receives the valid selection result and owns URL sync from there.exists: true) as a real link (the framework's link component or <a href>) whose href is the option URL for that value, built from value.selectedOptions — not a bare <button onClick>. The href is the no-JS path: with scripting off, activating it issues a GET to the option URL, the loader reads the params, queries the Storefront API, and the server renders the newly selected variant. A button-/onClick-only control gives a no-JS shopper nothing to act on, so they stay on the default variant. Non-existent combinations (exists: false) have no valid option URL; render those as a disabled <button>, not a link. Cross-product values are links too (see Combined listings).onSelect is the only client navigation. Handle the same-product link click yourself. For a plain primary click — not already prevented, event.button === 0, no Meta, Ctrl, Shift, or Alt key, and the link target is empty or _self — call event.preventDefault(), then call onClick() from register("optionValue", ...) (or your select function when you use the store directly). The registered handler calls selectOption, and the provider onSelect replaces the URL one time. preventDefault() stops the link and the framework router from navigating a second time. Do not call navigate() yourself in addition to the registered handler. Keep the selection callback safe to repeat, including clicks on already-selected values. Each framework reference shows the click hook to use.target other than _self must keep the browser's link behavior (for example, open the option URL in a new tab). They must not change the selection on the current page. Do not put download on option links; a guard on a native <a> also returns early when the link has download. Do not spread register("optionValue", ...) onto a link: the spread onClick runs for every click, including modifier-key clicks, and does not stop the link's own navigation.href and for the selection callback (provider onSelect, or your select function when you use the store directly). Pass the current URL search params as base to buildProductSelectionSearchParams in both places. Then the no-JS link and the hydrated navigation go to the same URL, and unrelated params (?ref=campaign) stay on both paths.selectOption return value for navigation, not a reactive effect on state. selectOption returns the result synchronously. Use the returned selectedOptions to construct the next URL immediately. Reacting to derived state (e.g. selectedOptions from the store) instead introduces an unnecessary update cycle and risks stale values. Framework bindings may wrap this as an onSelect callback — the principle is the same.selectOption returns resolved, the selected variant is already in the local cache. It is safe to skip revalidation only if the route does not need fresh loader data for other UI. When a complete selection returns unresolved, fetch or otherwise resolve the exact variant before treating the selection as complete.selectOption for combined-listing cross-product values. When value.handle !== product.handle, the value belongs to a different product. Render it as a navigation element (anchor or link component) that navigates to the other product's URL — not a button that calls selectOption. The store only knows about the current product's variant matrix.value.handle against the current product.handle. If they differ, the option value points to a different product in a combined listing. The UI must navigate to that product (full page navigation or a link component), not call selectOption.<a> only when that is the app's established routing convention.[handle] segment by its value), record the activated value before navigating and focus its same-product link as the new page mounts. Otherwise focus drops to <body>, and keyboard and screen-reader users lose their place and never hear the new selection.?ref=campaign) and replace only the option params. Use buildProductSelectionSearchParams with the current product's option names as optionNames — it deletes all option params (and any stale variant param) first, then sets the new ones, preventing stale params when combined-listing products have different option names.Color=Black param must not constrain a child product whose options are Size and Mount.selectedVariant.price when a variant is resolved. Fall back to product.priceRange.minVariantPrice when no variant is selected. Never compute prices client-side.hydrogen-money skill for app wrappers around formatMoney().canAddToCart(product, options) to determine if the add-to-cart button should be enabled. This checks three conditions: a variant is selected, it is available for sale, and the product does not require a selling plan. Checking only selectedVariant !== null misses the selling-plan and availability constraints.merchandiseId (the selected variant ID), quantity, and optionally attributeValue fields for line-item attributes. Do not put variant selection controls inside the cart form.register to bind form fields. register("merchandiseId", {}) returns the hidden input props with the current variant ID. register("quantity", { value: 1 }) returns the quantity input props. register("attributeValue", { key: "Engraving", value }) returns a hidden input for a line-item attribute. register("addToCart", {}) returns stable add-to-cart submit button props. These stay synchronized with store state automatically.hydrogen-shop-pay skill when adding accelerated checkout near the add-to-cart form.canAddToCart is true: "Add to cart". When no variant is selected (selectedVariant === null): "Select options" unless a navigation or submission is actually pending. When a variant is selected but unavailable: "Unavailable" or "Sold out".errors state. After form submission, user errors, warnings, and network errors relevant to the current product form are available on state.errors. Display these to the buyer.hydrate() instead. Recreating the store discards the decoded variant cache and any user interaction state.destroy() on unmount. This unsubscribes from the CartStore and releases internal caches (the decoded variant field cache). Provider bindings handle this automatically; standalone store users must do it themselves.aria-current — aria-pressed is not a valid state on a link. Reserve aria-pressed={value.selected} for values rendered as a <button>, chiefly the disabled non-existent (exists: false) case. Derive either from the matching option value's selected state.aria-label on visual-only controls (e.g. color swatches without visible text).exists: false) must use the native disabled attribute — not aria-disabled with prevented clicks. Non-existent combinations are truly non-interactive.selectedOrFirstAvailableVariant, the corresponding option values are marked as selected on first render. The variant's price and details are displayed. selectedVariant on the state is non-null.selectedOrFirstAvailableVariant is null, no option values are selected. selectedVariant is null. The add-to-cart button shows "Select options" (or equivalent) and is disabled.?Color=Blue&Size=Small), the data loader resolves the selection and passes it to the Storefront API query. The returned selectedOrFirstAvailableVariant reflects the URL selection, and the store initializes with those options selected. The page shows the shopper which option values are selected (visible styling or text), in addition to aria-current or aria-pressed.selectedVariant updates on the state. In URL-routing apps, the URL updates to reflect the new selection without a scroll reset.available: false; selecting Color=Green marks Size=Medium as available: true.selectOption with an unknown option name or value returns invalid with a reason string and does not change state. No navigation occurs.exists: false is disabled. Clicking it does nothing.exists: true and available: false is interactive but shows a "Sold out" indicator. Selecting it updates the state and shows the variant as unavailable.value.handle !== product.handle renders as a navigation element (anchor or link component), not a button. Clicking it navigates to the other product's page with the appropriate option params. After the navigation, focus is on the activated value's link on the new product page and the scroll position is unchanged.value.handle === product.handle renders as a GET link to its option URL enhanced by the register("optionValue", ...) click handler. With JavaScript disabled the link navigates and the server resolves the variant. Hydrated, a plain click calls selectOption, the provider syncs the URL client-side, and the link's own navigation does not run, so a resolved selection issues no loader request. A Cmd- or Ctrl-click opens the option URL in a new tab and leaves the current page's selection unchanged.product.id) hydrates the store with Product B's data. The selection reflects Product B's selectedOrFirstAvailableVariant.?Color=Blue instead of ?Color=Red) hydrates with the new pre-selected variant without recreating the store.merchandise.id, matchedLineItem is non-null and contains the cart line data.errors.userErrors contains the relevant user errors, errors.warnings contains warnings, and errors.networkErrors contains any network failures.matchedLineItem and errors update without any manual intervention.canAddToCart returns true (variant selected, available, no selling plan required), the add-to-cart button is enabled and shows "Add to cart".product.requiresSellingPlan is true, the button is disabled regardless of variant selection.register("merchandiseId", {}) returns { name: "merchandiseId", value: selectedVariantId }. When no variant is selected, value is an empty string.handleFormSubmit(event) delegates to the cart store with the submit event and selected-product detail when a variant is resolved. Cart errors surface reactively via the errors state.register("optionValue", { optionName: "Color", value: "Red" }) returns { name, value, onChange, onClick }. Calling onChange or onClick triggers selectOption.register("optionValue", { optionName: "Color", value: "Red" }) returns only { name, value, onChange, onClick }. Derive disabled, aria-pressed, and visual state from the matching options value.register("quantity", { value: 1 }) returns { name: "quantity", value: "1" }. register("quantity", { defaultValue: 1 }) returns { name: "quantity", defaultValue: "1" }.register("addToCart", {}) returns { name: "add-to-cart", type: "submit" }.register("attributeValue", { key: "Engraving", value: "Hello" }) returns { name: "attributes.Engraving", value: "Hello" }. register("attributeValue", { key: "Engraving", defaultValue: "" }) returns { name: "attributes.Engraving", defaultValue: "" }. An empty key throws a TypeError.register("attributeValue", { key: "Engraving", value: "Hello" }) is included as a hidden input in the add-to-cart form, the submitted cart line carries the attribute. The attribute appears on the matched line item in the cart drawer (with _-prefixed internal attributes filtered out).unresolved because the exact variant is absent from the local cache, the app navigates to the new URL and re-fetches product data. The subsequent hydration resolves the variant. Incomplete selections should remain in selection UI until the buyer chooses the remaining options.reset() restores the store to the product and selected options it was created with. All user selections are discarded.?ref=campaign in the URL, option link href values and the URL after a hydrated selection both keep ref=campaign.target="_blank" opens the option URL natively. The current page's selection and URL do not change.selectOption return value provides the selection result synchronously. Reacting to state.selectedOptions instead introduces an extra update cycle and can fire with stale values.navigate() in an option click handler and then also call the registered handler. This bypasses the provider onSelect contract and can navigate from stale or invalid data. A guarded link handler that calls event.preventDefault() and then only registered.onClick() is correct.register("optionValue", ...) onto a link unguarded. The link runs the registered handler and then its own navigation. The second navigation refetches the loader a resolved selection skipped, and a Cmd- or Ctrl-click both opens a new tab and changes the current page. Run the handler only for a plain primary click and cancel the link's navigation.<button onClick={selectOption}> with no href is dead without JavaScript — a no-JS shopper cannot switch variants and is stuck on the default. Render it as a GET link to the option URL and let the registered handler enhance it; the href is the progressive-enhancement fallback.<a> tags lose client-router behavior such as scroll preservation, pending navigation state, prefetching, and route transitions. Use the app's established link component unless raw anchors are the framework convention.merchandiseId and quantity to the cart. Mixing them creates ambiguous form semantics and breaks progressive enhancement.errors state after form submission. Cart user errors, warnings, and network errors are surfaced reactively on the store state. Failing to display these leaves the buyer with no feedback when something goes wrong.What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub fcakiroglu16/marketplace --plugin shopify-hydrogen11 skills in this plugin
/hydrogen-cart-drawerGuide for building an accessible cart drawer using @shopify/hydrogen. Use when creating or reviewing a cart drawer, mini cart, or slide-out cart, including native dialog element (showModal), closedby light dismiss, body scroll lock, exit animations, and wiring window.Shopify.actions.openCart()./hydrogen-cart-uiBehavioral guide for building cart UI with @shopify/hydrogen: line items, quantity and remove controls, optimistic updates, discount, note, and cart attribute inputs, and the full-page /cart fallback. Use when writing, modifying, or reviewing cart line-item UI, quantity/remove controls, cart mutation forms, or code that changes the cart without a form. Framework agnostic./hydrogen-customer-accountCustomer Account API setup for Hydrogen storefronts. Use when wiring customer sessions, login/logout/OAuth route handlers, account profile, order history, account-gated UI, cart buyer identity sync, or Customer Account GraphQL queries./hydrogen-marketsGuide for implementing Shopify Markets with Hydrogen. Use when adding market routing, country/language localization, Shopify Markets, subdomains, per-market domains, path-prefixed markets, defineShopifyI18n, LocaleProvider, locale switchers, hreflang links, the <html lang> attribute, Next.js App Router market routing, or Storefront API @inContext wiring./hydrogen-oxygenAudit and adapt an existing Hydrogen storefront for Shopify Oxygen and local MiniOxygen. Use when asked to make a server-capable Hydrogen project Oxygen-compatible, add or repair its Worker server entrypoint, configure MiniOxygen, remove Node runtime assumptions, wire Worker environment, cache, and waitUntil, or verify dev, preview, and deploy behavior./hydrogen-predictive-searchGuide for building predictive search with @shopify/hydrogen. Use when adding, modifying, or reviewing autocomplete/search-as-you-type UI, predictive search route handlers, tracking URLs, custom predictive search fragments, or framework predictive search bindings.