/shopify-hydrogen:hydrogen-cart-uifrom shopify-hydrogen
Behavioral 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.
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 cart primitive is a client-side store that syncs with Shopify via Standard Actions events. It provides optimistic updates, scoped error handling, and a form-based mutation API. The store is framework-neutral; framework-specific bindings are thin wrappers over the core store.
Before building 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 first; the reference owns provider setup, state selectors, and form helpers for that runtime.
If there is no matching reference, there may be no packaged @shopify/hydrogen/<framework> export. Use the framework-neutral createCartStore and createCartFormRegister from @shopify/hydrogen directly, subscribe to store changes with the framework's reactivity primitive, and apply every rule in this skill yourself. Packaged bindings are thin wrappers over these same core APIs — match their behavior, do not invent a new contract.
In island-based frameworks, use the binding for the island's UI framework when a matching reference exists; otherwise use the core store directly.
When creating a full cart page, use the app's existing route convention when present; otherwise create /cart. This page is separate from Hydrogen's /api/cart server handler, which is registered with createCartServerHandlers() through handleShopifyRoutes.
The /cart page must render from the server data path. It is the fallback route for the cart drawer (reachable as a real /cart link in the footer), so its line items and totals must not depend only on an ad hoc client store read. Seed CartProvider with initialData from the server data path (React Router loader, Next.js server layout/page). When the framework can preserve streamed promises, pass the unresolved cart promise as initialData instead of awaiting it; the Next.js reference is the best current non-blocking pattern. If strict no-JS HTML must include the real cart today, pass the resolved handler envelope instead. A /cart page whose only data source is a client useCart read renders "Your cart is empty" without JS even when the shopper has items. See the framework reference for the exact wiring.
The native no-JS add-to-cart POST must set the cart cookie server-side. With scripting off, the add-to-cart <form method="post"> submits natively and the cart server handler must respond with the cart cookie so the next /cart request server-renders the seeded cart — not only service the hydrated fetch. See the hydrogen-request-handlers skill for the endpoint contract.
The store sends cart changes through Shopify's Standard Actions runtime (window.Shopify.actions) and listens for its events. Render ShopifyScripts once in the document head. When the app deliberately skips Shopify's other scripts, include only <script type="module" src="https://cdn.shopify.com/storefront/standard-actions.js"></script>. Without the runtime, cart actions reject with "Standard Actions not available".
The store holds a CartState and notifies subscribers when it changes. state.readyPromise is present while an applicable full-cart load is pending and resolves after the resulting state is published. Mutations flow through Shopify Standard Actions — the store listens for shopify:cart:lines-update, shopify:cart:discount-update, shopify:cart:note-update, and shopify:cart:attributes-update DOM events. Each event carries a promise that resolves with the server response.
On mutation:
pending — a set of in-flight line IDs or discount codes, or a note/attributes boolean.When overlapping mutations make response snapshots ambiguous, the store sets state.revalidating to true. It starts one authoritative refresh after those mutations settle and clears the flag when the refresh completes or fails. Until then, server-derived values such as costs remain at their last trustworthy value. A refresh failure preserves the locally reconciled cart and appears in errors.network. A change made while a cart load is in flight is handled the same way: loading ends and the refresh brings in the rest of the cart.
App-owned cart mutations outside Standard Actions do not emit the events the store normally observes. After such a mutation succeeds, call CartStore.refresh() directly or use the framework binding's useCartActions().refresh(). The refresh waits for active optimistic work, reconciles custom fragment fields from the configured cart endpoint, and loads the cart when none exists yet (e.g. one just created server-side). Do not call it after ordinary Hydrogen cart forms; their Standard Actions events already synchronize the store. For cart metafields specifically, see the hydrogen-cart-metafields skill.
The store supersedes keyed mutations for the same line, discount batch, note, or complete attribute list. Relative additions remain independent so every submitted quantity reaches the server; their projections are reconciled together without disabling controls. A Shopify.actions.updateCart call that updates or removes several lines is keyed per line: each line is projected, pending and rolled back on its own, and a newer change to one of those lines supersedes only that line.
The cart store combines its lifecycle, timeout, and caller signals with AbortSignal.any, which Safari added in 17.4. The store already requires Safari 16 for toSorted, so Safari 16.0 through 17.3 is the gap. To keep add to cart working there, load an AbortSignal.any polyfill in the browser bundle before the store is created.
Some changes have no form: a free gift added when the cart crosses a threshold, removing a line that became unavailable, an attribute written by a script. Send them with window.Shopify.actions.updateCart(payload, options). The store observes the events it dispatches, so these changes get the same optimistic projection, pending state and rollback as form submissions. Do not hand-roll fetch calls to the cart route.
updateCart only after all of these hold:
window.Shopify.actions.updateCart.isDefault() returns false, which happens once a connected cart store has configured it. Before that, Shopify's default handler runs instead of the app's cart route. The framework cart providers also configure the cart endpoint (/api/cart, or the path the app set with configureCartEndpoint(path) first); a store from createCartStore() keeps using Shopify's default handler until the app calls configureCartEndpoint(path).state.loading is false and state.readyPromise is absent (or await it). A change made during that load can hide the shopper's other lines.state.data.id is set. While it is null, the first add creates the cart. The store queues form adds behind it, but not updateCart calls: an add from code sent before the cart exists, alongside another add from code or a form, creates a second cart, and the shopper keeps only one of them. Send the first add alone and wait for it to settle.lines, discountCodes, attributes or note, not several. The cart route rejects a combined call and the store rolls back its projections.{ merchandiseId, quantity } adds, { id, quantity } updates, { id, quantity: 0 } removes, and { id, merchandiseId, quantity } swaps the line to another variant. Only additions batch: send several adds in one call if needed, but send each update, removal or swap as its own call with one line. The store does not project a call that updates or removes several lines. A swap projects only the quantity; the new variant appears when Shopify responds, possibly under a new line ID, so don't hold on to the old one. When the response returns a new line ID while other changes are in flight, the new variant appears after the cart refresh that follows them.{ event: { detail: { products: [{ id: merchandiseId, price, ...merchandise }] } } } so a new line shows before Shopify responds. Events do not carry line attributes or selling plans, so the projected line does not show them.loading false, no pending entries, revalidating false), and do not start another change while your own is in flight. Otherwise the rule reacts to its own projection and can loop.attributes replaces the whole list. Build each write from the latest list you sent, falling back to state.data.attributes when nothing is in flight, so writers in the same tick keep each other's keys.trackCartAnalytics reports every confirmed change, including code-driven ones. Storefronts that keep system changes out of analytics must track shopper changes themselves.Store selectors should select primitives or stable references from the store. Do not allocate arrays, objects, maps, sets, or derived view models inside a selector unless the framework binding also accepts an equality function.
Bad:
const selectMessages = (state) => [
...state.errors.network.map((error) => error.message),
...state.errors.cart.userErrors.map((error) => error.message),
];
That selector returns a new array whenever the store notifies subscribers, so bindings that rely on referential equality cannot skip unchanged output. Select stable slices first, then derive:
const selectErrors = (state) => state.errors;
const messages = deriveFromErrors(errors, () => {
return [
...errors.network.map((error) => error.message),
...errors.cart.userErrors.map((error) => error.message),
];
});
state.pending tracks what is currently in-flight:
pending.lines — Set<string> of line IDs with mutations in flight.pending.discountCodes — Set<string> of discount codes being applied or removed.pending.cost — true when pending line or discount mutations can leave totals stale.pending.note — boolean indicating whether a note save is in flight.pending.attributes — boolean indicating whether a complete attribute-list update is in flight.Any value whose entity is in a pending set is optimistic and unconfirmed. The UI must treat it differently from confirmed values.
state.revalidating is true while the store refreshes authoritative cart-wide fields after overlapping mutations. Treat totals as unconfirmed and suppress cart analytics while it is true.
state.errors is scoped to the entity that caused the error:
errors.lines — Map<string, CartErrorGroup> keyed by line ID.errors.discountCodes — Map<string, CartErrorGroup> keyed by discount code string.errors.note — CartErrorGroup for note-related errors.errors.attributes — Map<string, CartErrorGroup> keyed by attribute key.errors.cart — CartErrorGroup for cart-level errors not attributable to a specific entity.errors.network — CartNetworkEntry[] for transport failures (timeouts, HTTP errors).errors.lastUpdatedAt — timestamp of the most recent error update across any scope. Per-scope timestamps also exist (linesUpdatedAt, discountCodesUpdatedAt, attributesUpdatedAt, etc.).Each CartErrorGroup contains { userErrors: CartUserError[], warnings: CartWarning[] }.
Errors survive unrelated cart work and clear when a new mutation begins for the same key.
line.cost.totalAmount, state.data.cost.subtotalAmount, etc.) directly. Client-side arithmetic drifts from the truth when discounts, taxes, duties, or rounding apply. If a value is stale because a mutation is in-flight, show it with pending UI — not a client-computed estimate.hydrogen-money skill for an app wrapper around formatMoney(). The store provides amount (string) and currencyCode (string).<= 1.ProductVariant.quantityAvailable because that field requires the unauthenticated_read_product_inventory Storefront API scope. If a cart UI needs the entered quantity to clamp to sellable inventory before submission, add quantityAvailable to the app's custom cart fragment and enable the Hydrogen channel's product inventory permission (unauthenticated_read_product_inventory). The store only clamps when quantityAvailable is positive. Zero (untracked inventory) and negative (oversold) values set no cap, so the requested quantity goes to Shopify for validation. Without that field, let Shopify validate inventory and surface the returned line error.pending set must look visually distinct from confirmed values. Reduced opacity is the reference pattern — the stale text acts as a spatial placeholder (like a skeleton), not as readable content. Rules of contrast can be disregarded because the pending value is a signal, not content the user needs to read.errors.lines contains entries for line IDs not present in state.data.lines.nodes, those errors have no inline target. Surface them in the banner. This happens when a line was removed but the server returned errors referencing its ID.role="alert" and link them to the nearest interactive element via aria-describedby. Mark the associated input as aria-invalid="true".errors.lastUpdatedAt for dismissal. Track a local dismissedAt timestamp. If lastUpdatedAt <= dismissedAt, the banner is hidden. If a new error arrives with a newer timestamp, the banner reappears.pending.note is false. This prevents the server response from clobbering the user's in-progress typing.attributes-update sends the full next attribute list; attributes omitted from the submission are removed. When editing one attribute, explicitly include every unrelated existing attribute as a hidden keyed attributeValue field. Submit no attribute fields to clear all attributes.register("attributeValue", {key, ...}) call. The generated attributes.<key> field name encodes that key, so the server never relies on parallel field positions. Storefront API mutation inputs require string values, so normalize a nullable returned value deliberately (usually to "") before resubmitting it.register("attributeValue", {key, ...}) rather than spelling its generated attributes.<key> field name by hand. The submit intent is kebab-case (attributes-update) because action intents follow the existing discount-apply, discount-remove, and note-update convention.pending.attributes is false, so a response does not clobber typing that happened during the request.pending.attributes for the save state and display entries from errors.attributes next to the editor for the matching key. A save-style submit button may be disabled until the attribute promise settles.attributes — an array of { key, value } pairs set during add-to-cart. If your storefront uses line-item attributes (e.g. engraving text, gift messages, custom options), render them below the variant subtitle as secondary text. Filter out attributes whose key starts with _ (these are internal/private, set by apps or Shopify systems). The same variant with different attributes creates separate cart lines — the optimistic layer uses attributes in line identity matching.register("set"), register("lineId", { value: line.id }), and a real editable quantity input using register("quantity", { value: line.quantity, interactive: true }). Increase, decrease, and remove buttons are additional submit controls, not replacements for the set intent or the quantity input.set control is a hidden submit button, not a hidden input. register("set") already returns { type: "submit", hidden: true }; render it on a <button>. Do not swap it for <input type="hidden"> — that removes the submit button, so pressing Enter in the quantity input no longer submits the set action.register("attributeValue", {key, value}) control for every attribute in the complete next list, then submit with register("attributes-update").loading is true, show skeleton placeholders — not empty state. The cart hasn't been fetched yet.loading is false and lines is empty, show empty state ("Your cart is empty" or equivalent).initialData is provided when creating the store, loading starts as false and the initial fetch is skipped. initialData is the cart handler data envelope ({cart, errors?}), not only the cart object. Use resolved data when the response should include full cart HTML. If promise initialData is provided, loading starts as true, state.readyPromise tracks readiness, and useSuspenseCart can suspend cart content while the app shell stays non-blocking. Use promises when the backend can stream them into the HTML response. {cart: null} means the server already completed the bootstrap with no usable cart, so the UI should render empty state without a browser retry. undefined means no server bootstrap was provided, so the store fetches /api/cart after hydration; use this only when a client-side fetch is acceptable, such as an SPA. Cart server handlers log bootstrap errors before returning them, so app loaders should forward handler data instead of logging or throwing those errors again.userError scoped to a specific line, the message appears adjacent to that line (not only in a banner). The relevant input is marked aria-invalid.set submit control, hidden/read-only lineId, and an editable quantity input. Pressing Enter in the quantity input submits a set-quantity action.pending.note is false, preserving any typing the user did in the meantime.pending.attributes is true, and the editor shows a saving state until confirmation.state.data.lines.nodes but errors.lines has an entry for its ID, that error appears in the banner.lastUpdatedAt) re-shows it.revalidating represents the refresh, and a refresh failure preserves the confirmed cart while appearing in errors.network./cart page. Mounting CartProvider with no initialData (or reading the cart only through a "use client" useCart hook) leaves the SSR HTML empty, so the /cart page cannot render the server cart. Read the cart in the server data path and pass initialData. Use resolved initialData when strict no-JS live cart HTML is required; use promise initialData when the framework can stream and hydrated cart content is wrapped in Suspense.<span> with only plus/minus buttons breaks the set-quantity path and the no-JS fallback. Use a real input wired with register("quantity", { value, interactive: true }).register("set") and the interactive quantity input. Omitting them breaks the form invariant even if hydrated clicks appear to work./cart page, but its line item forms must keep the same Hydrogen form contract. Prefer sharing line item form components between the page and drawer.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-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./hydrogen-routingGuide for Hydrogen route templates and Shopify storefront URL routing. Use when adding, modifying, or reviewing defineShopifyRouteTemplates, routeTemplates, custom Shopify resource or utility-page paths, handleShopifyRoutes, standard route redirects, ShopifyScripts routes, predictive search result URLs, or localized path prefixes from defineShopifyI18n.