agentleFS
remix-runremix-run/remix-store/.agents/skills/hydrogen-cart-ui/SKILL.md

hydrogen-cart-ui

Skill218 starsChanged 5 days agoMITView on GitHub

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.

1 other project uses a version of this, 1 of them edited.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 1 is distinctive, and 6 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Before building UI, check whether this skill has a reference file for the app's framework in references/.

    line 22
  2. Very specific:

    When creating a full cart page, use the app's existing route convention when present.

    line 30
  3. Distinctive:

    When the promise resolves, the store folds that transaction into settled state and reapplies remaining projections.

    line 48
  4. Very specific:

    Wait for the store: Call updateCart only after all of these hold:

    line 63
  5. Very specific:

    Use the register contract exactly: Call register("attributeValue", {key, ...}) rather than spelling its generated attributes.<key> field …

    line 164
  6. Very specific:

    Show scoped pending and errors: Use pending.attributes for the save state and display entries from errors.attributes next to the editor for …

    line 166
  7. Very specific:

    Hand-rolled framework cart state: If the skill has a matching framework reference, use its provider/hooks/helpers.

    line 250

≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Cart Primitive

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.

Framework Bindings

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.

Route Placement

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.

Prerequisites

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".

How the store works

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:

  1. The store applies an optimistic projection over its settled state, so the UI-visible state changes immediately.
  2. The affected entity is added to pending — a set of in-flight line IDs or discount codes, or a note/attributes boolean.
  3. When the promise resolves, the store folds that transaction into settled state and reapplies remaining projections. Overlapping mutations discard ambiguous response snapshots, then coalesce one authoritative cart refresh after the burst settles.
  4. On failure, the store removes only the failed projection, preserves unrelated work, and clears the matching pending entry.

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.

Code-driven cart changes

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.

  • Wait for the store. Call 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; a store from createCartStore() keeps using Shopify's default handler until the app calls configureCartEndpoint(path).
    • The initial cart load has finished: 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.
    • A cart exists: 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.
  • One kind of change per call. Send lines, discountCodes, attributes or note, not several. The cart route rejects a combined call and the store rolls back its projections.
  • Lines. { 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.
  • Previews for added lines. Pass { 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.
  • Rules that react to the cart. Evaluate them on settled state only (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.
  • Several attribute writers. 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.
  • Analytics. trackCartAnalytics reports every confirmed change, including code-driven ones. Storefronts that keep system changes out of analytics must track shopper changes themselves.

Stable selectors

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),
  ];
});

Pending state

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.

Error state

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.


Rules

Money

  • NEVER calculate currency amounts on the client. Display server-provided amounts (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.
  • Format with Hydrogen money helpers, not string concatenation. Use the local hydrogen-money skill for an app wrapper around formatMoney(). The store provides amount (string) and currencyCode (string).

Optimistic interactions

  • Keep rapid-action controls interactive during pending state. Increase, decrease, remove, apply, and remove-discount controls must remain interactive. The store's abort-controller pattern makes concurrent mutations safe — a new click supersedes the in-flight request. A save-style editor, such as a gift-message attribute form, may disable its own submit button while its scoped mutation is pending when duplicate saves provide no value. Disabling for a non-pending reason is also fine — for example, the decrease control may be disabled when the quantity is already <= 1.
  • Inventory-aware set-quantity clamping is opt-in. The default cart query does not request 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). Without that field, let Shopify validate inventory and surface the returned line error.
  • NEVER show a spinner or skeleton where a stale value would do. The user already sees a quantity and a price. Replacing confirmed-looking content with a loading state is a regression. Show the previous value with a visual indicator that it's unconfirmed.
  • ALWAYS visually indicate unconfirmed data. Any value whose entity is in a 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.
  • NEVER block navigation during pending. Cart mutations are fire-and-forget from the user's perspective. No confirmation dialogs on route change.

Errors

  • ALWAYS display errors closest to the element they describe. A line item error appears next to that line item. A discount code error appears next to that discount code. Errors should not only live in a distant banner.
  • Use a banner only for errors that have no inline home. This includes: network errors, cart-level errors, and orphaned line errors.
  • Orphaned line errors — when 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.
  • Inline errors must be accessible — use role="alert" and link them to the nearest interactive element via aria-describedby. Mark the associated input as aria-invalid="true".
  • Use 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.

Note editing

  • Maintain a local draft for the note, synced from the store. When the server responds with an updated note, only overwrite the local draft if pending.note is false. This prevents the server response from clobbering the user's in-progress typing.
  • Allow users to click the save button even when the draft matches the stored note (nothing to save), but prevent any action. This enables progressive enhancement and prevents frustration.
  • Show a pending indicator while the note mutation is pending.

Cart attribute editing

  • Treat an attribute update as complete-list replacement. 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.
  • Keep each key attached to its value. Pass the attribute key to every 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.
  • Use the register contract exactly. Call 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.
  • Maintain a local draft for an editable attribute when the UI can remain mounted across server responses. Only sync confirmed attribute data into that draft while pending.attributes is false, so a response does not clobber typing that happened during the request.
  • Show scoped pending and errors. Use 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.

Form structure

  • Optionally render visible line-item attributes. Each cart line may carry 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.
  • Each line item is its own form. This gives each line its own identity input and its own submit buttons. A single form containing multiple lines creates ambiguity about which line an action targets.
  • Each line item form must preserve the progressive-enhancement shape. The rendered structure will vary by framework and design system, but every line item quantity form needs the same Hydrogen contract: 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.
  • The 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.
  • Each discount "remove" button is its own form — separate from the "apply" form. The apply form needs input validation (empty/duplicate prevention); each remove form is a single action.
  • Attribute forms submit keyed values. Render one register("attributeValue", {key, value}) control for every attribute in the complete next list, then submit with register("attributes-update").

Loading

  • While loading is true, show skeleton placeholders — not empty state. The cart hasn't been fetched yet.
  • When loading is false and lines is empty, show empty state ("Your cart is empty" or equivalent).
  • If resolved 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.

User Acceptance Tests

Line items

  1. Increase quantity — Click the increase control. The displayed quantity increments immediately. The quantity and totals appear in their pending visual state until the server confirms.
  2. Decrease quantity — Click the decrease control. Same optimistic behavior. At quantity 1, decreasing removes the line.
  3. Remove line — Activate the remove control. The line disappears immediately. Totals update optimistically.
  4. Rapid clicks — Click increase five times quickly. Each click increments the displayed quantity by one. The store aborts intermediate requests. The final server-confirmed state matches the quantity the user sees.
  5. Failure rollback — If the server rejects a line update, the quantity reverts to the last confirmed value. An error message appears inline next to the affected line item.
  6. Line-scoped error — When the server returns a 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.
  7. Progressive quantity set — The line item form contains a hidden set submit control, hidden/read-only lineId, and an editable quantity input. Pressing Enter in the quantity input submits a set-quantity action.
  8. No-JS line update — If JavaScript fails or hydration has not run, the line item form can still submit an explicit quantity value to the cart action endpoint.

Discount codes

  1. Apply discount — Enter a code and submit. The code appears in the list immediately in its pending visual state. When the server confirms, the pending indicator clears and the "applied" / "not applicable" status updates.
  2. Duplicate prevention — Submitting a code that is already present does nothing.
  3. Empty input prevention — Submitting with a blank input does nothing.
  4. Remove discount — Activate the remove control next to a code. The code disappears optimistically.
  5. Discount-scoped error — If the server returns an error for a specific code, the message appears next to that code in the list.

Order note

  1. Save note — Edit the text and submit. A pending indicator appears while the mutation is in-flight.
  2. No-op save — When the draft matches the stored note, clicking on save does nothing (but can still be clicked).
  3. Server sync without clobber — After save completes, the local draft updates to match the server response — but only when pending.note is false, preserving any typing the user did in the meantime.

Cart attributes

  1. Save attribute — Edit an attribute and submit. The optimistic value appears immediately, pending.attributes is true, and the editor shows a saving state until confirmation.
  2. Preserve unrelated attributes — Saving one attribute includes all unrelated existing key/value pairs; those attributes remain after the server response.
  3. Clear attributes — Submitting an empty attribute list removes every cart attribute.
  4. Failure rollback — If the update fails, the complete attribute list returns to the last confirmed baseline.
  5. Attribute-scoped error — An error for a key appears next to that key's editor and marks its input invalid.
  6. No draft clobber — Typing that occurs while an attribute save is pending is not overwritten by the confirming response.

Error banner

  1. Network error — When a mutation fails due to a transport error, a banner appears with the error message and a dismiss control.
  2. Cart-level error — Errors not attributable to a line, code, note, or attribute appear in the banner.
  3. Orphaned line error — If a line no longer exists in state.data.lines.nodes but errors.lines has an entry for its ID, that error appears in the banner.
  4. Dismiss and re-trigger — Dismissing the banner hides it. A subsequent error (with a newer lastUpdatedAt) re-shows it.

Totals

  1. Pending totals — While any line or discount mutation is in-flight, subtotal and total appear in their pending visual state. The amounts shown are the last server-confirmed values — never client-computed.
  2. Settled totals — After an ordinary mutation settles, totals display the latest server values. Overlapping mutation bursts retain pending styling and the last trustworthy amounts while one authoritative cart refresh is in flight.

Loading

  1. Initial load — Before the cart is fetched, show skeleton placeholders.
  2. Empty cart — After fetch completes with zero lines, show empty state.

Out-of-band mutations

  1. Refresh custom data — After an app-owned cart mutation succeeds, request a cart refresh. Every cart consumer receives the updated custom fragment data, revalidating represents the refresh, and a refresh failure preserves the confirmed cart while appearing in errors.network.

Code-driven changes

  1. Rule on settled state — A threshold rule that adds a line runs once per qualifying settled cart, never before the initial load finishes or on its own pending projection.

Anti-patterns

  • Hand-rolled framework cart state. If the skill has a matching framework reference, use its provider/hooks/helpers. Otherwise, use the core store directly instead of duplicating cart data in component state or custom reducers.
  • Client-seeded /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.
  • Quantity as text only. Rendering quantity as a <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 }).
  • Plus/minus-only line forms. Increase/decrease/remove buttons do not replace register("set") and the interactive quantity input. Omitting them breaks the form invariant even if hydrated clicks appear to work.
  • Drawer-specific line form drift. The cart drawer may have a different layout from the /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.
  • Banner-only errors. A line-level error displayed far from the line it refers to is effectively invisible. Show inline first; promote to the banner only when there's no inline target.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.