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

hydrogen-cart-metafields

Skill218 starsChanged 4 days agoMITView on GitHub

Behavioral guide for reading and writing cart metafields with @shopify/hydrogen. Use when adding, modifying, or reviewing cart metafield reads or writes, an app-owned cart metafield route, cart-to-order metafield copying, or custom cart data such as delivery instructions or gift preferences. 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

4 rules. About 0 are common, 1 is distinctive, and 3 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.

  • 3

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Server-only: Never route metafields through Standard Actions or the optimistic cart store.

    line 122
  2. Very specific:

    No core intents: Do not add metafields-set/metafield-delete to the cart action model.

    line 123
  3. Very specific:

    Mutation returns userErrors only: Never refetch and return the cart in the same request.

    line 124
  4. Very specific:

    Re-sync with refresh(): after success. Treat a refresh failure as a soft error (errors.network), not a failed save.

    line 125

≈ “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 Metafields

Cart metafields store custom data on the cart (for example delivery instructions or a gift preference). They are server-only: the Storefront cart ajax API (Standard Actions) does not support them, so they never flow through Hydrogen's optimistic cart store the way line, discount, note, and attribute mutations do.

Because of that, do not add metafields to the core cart action/intent model. Compose three pieces Hydrogen already provides:

  1. Read — a custom CartFragment on createCartServerHandlers, so metafields appear in cart state.
  2. Write — an app-owned route (createShopifyRouteHandler) calling cartMetafieldsSet / cartMetafieldDelete.
  3. Re-sync — useCartActions().refresh() after a successful write.

See hydrogen-cart-ui for cart state, refresh(), and form patterns, and hydrogen-request-handlers for registering the custom route.

Golden rule: decouple the write from the read

The mutation route returns only the mutation's userErrors — it must never refetch and return the cart. Re-syncing is a separate refresh() call.

POST /api/cart/metafields  → cartMetafieldsSet → { userErrors }   (truthful: success is success)
then, on success:
refresh()                  → re-reads the cart via CartFragment

If the write and a refetch were coupled in one request, a blip on the read would mask a successful save as a "network error." Decoupled, a failed re-sync surfaces as state.errors.network (a soft refresh error) and preserves the saved cart — it is never reported as a failed save.

Reading metafields

Select the metafields you need in a CartFragment named CartFragment:

const CART_FRAGMENT = gql(`
  fragment CartFragment on Cart {
    metafields(identifiers: [{ namespace: "custom", key: "delivery_instructions" }]) {
      namespace
      key
      type
      value
    }
  }
`);

export const cartHandlers = createCartServerHandlers({ fragment: CART_FRAGMENT });

They then appear in cart state. Read a primitive in the selector so referential equality can skip re-renders:

const instructions = useCart(
  (state) =>
    state.data.metafields?.find(
      (m) => m?.namespace === "custom" && m.key === "delivery_instructions",
    )?.value ?? "",
);

Writing metafields (app-owned route)

Register a custom POST route with createShopifyRouteHandler in handleShopifyRoutes. Do not extend /api/cart or open up its intents.

async function handleCartMetafieldsPost({ request, storefrontClient }) {
  const body = parseRequest(await request.json()); // validate at the boundary
  const cartId = getCartId(request); // read the owner from the cookie, never the client body

  // Mutate an existing cart only; never create one here. Two concurrent empty-cart
  // writes would each call cartCreate and race — the last Set-Cookie wins,
  // orphaning one cart and dropping its write.
  if (!cartId) {
    return { type: "error", error: { code: "missing_cart", message: "No cart exists." } };
  }

  if (body.intent === "delete") {
    const result = await storefrontClient.graphql(CART_METAFIELD_DELETE_MUTATION, {
      variables: { input: { ownerId: cartId, key: body.key } },
    });
    return { type: "json", data: { userErrors: result.data?.cartMetafieldDelete?.userErrors ?? [] } };
  }

  const result = await storefrontClient.graphql(CART_METAFIELDS_SET_MUTATION, {
    variables: { metafields: body.metafields.map((m) => ({ ...m, ownerId: cartId })) },
  });
  return { type: "json", data: { userErrors: result.data?.cartMetafieldsSet?.userErrors ?? [] } };
}
  • Existing cart → cartMetafieldsSet with ownerId = the cart id from getCartId(request).
  • No cart → reject with a missing_cart error. Do not call cartCreate here: two concurrent empty-cart writes would each create a cart and race on the cookie, orphaning one and dropping its write. Require callers to add a line first.
  • Delete → a single key via cartMetafieldDelete. The Storefront API deletes one metafield per call, so keep the contract single-key.

Re-syncing the store

On success, call refresh():

const { refresh } = useCartActions();
// after the POST resolves ok:
refresh();

refresh() reconciles the CartFragment fields for the cart after a write. Never call refresh() after ordinary Hydrogen cart forms — their Standard Actions events already synchronize the store.

Copying to the order

To copy a cart metafield onto the order at checkout, the store must define the metafield with the cart-to-order copyable capability: https://shopify.dev/docs/apps/build/metafields/use-metafield-capabilities#cart-to-order-copyable Without the definition the cart write still succeeds, but nothing is copied to the order.

Rules

  • Server-only. Never route metafields through Standard Actions or the optimistic cart store.
  • No core intents. Do not add metafields-set/metafield-delete to the cart action model; use an app-owned route.
  • Mutation returns userErrors only. Never refetch and return the cart in the same request.
  • Re-sync with refresh() after success. Treat a refresh failure as a soft error (errors.network), not a failed save.
  • Inject ownerId server-side from the cart cookie (getCartId). Never trust a client-supplied ownerId.
  • Require an existing cart. Reject writes when no cart cookie is present; never call cartCreate in this route — it races on the cookie.
  • Validate the request body at the route boundary before calling the Storefront API.
  • Delete is single-key, matching cartMetafieldDelete.

Putting it together

Three pieces in your app, each owning one concern:

  1. Cart handlers — add the CartFragment (see Reading metafields) so the values load into cart state.
  2. Metafields route — an app-owned POST handler (see Writing metafields) that runs cartMetafieldsSet / cartMetafieldDelete and returns only userErrors.
  3. Your component — read with useCart, write via the route, then call refresh() on success (see Re-syncing the store).

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.