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
- Shopify/hydrogenedited, first seen Oct 13, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- Shopify/hydrogen★ 2.2k94% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository23 other files it gives its agents.
- AGENTS.mdAGENTS.md
- hydrogen-analyticsSkill
- hydrogen-cart-drawerSkill
- hydrogen-cart-uiSkill
- hydrogen-collection-browserSkill
- hydrogen-customer-accountSkill
- hydrogen-imageSkill
- hydrogen-local-httpsSkill
- hydrogen-marketsSkill
- hydrogen-moneySkill
- hydrogen-oxygenSkill
- hydrogen-predictive-searchSkill
- hydrogen-request-handlersSkill
- hydrogen-robots-txtSkill
- hydrogen-routingSkill
- hydrogen-setupSkill
- hydrogen-shop-paySkill
- hydrogen-smoke-testSkill
- hydrogen-storefront-clientSkill
- hydrogen-variant-formSkill
- migrate-to-hydrogen-2026-10Skill
- remix-storeSkill
- testing-practicesSkill
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
- Distinctive: line 122
Server-only: Never route metafields through Standard Actions or the optimistic cart store.
- Very specific: line 123
No core intents: Do not add metafields-set/metafield-delete to the cart action model.
- Very specific: line 124
Mutation returns
userErrorsonly: Never refetch and return the cart in the same request. - Very specific: line 125
Re-sync with
refresh(): after success. Treat a refresh failure as a soft error (errors.network), not a failed save.
≈ “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.
Files
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:
- Read — a custom
CartFragmentoncreateCartServerHandlers, so metafields appear in cart state. - Write — an app-owned route (
createShopifyRouteHandler) callingcartMetafieldsSet/cartMetafieldDelete. - 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 CartFragmentIf 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 →
cartMetafieldsSetwithownerId= the cart id fromgetCartId(request). - No cart → reject with a
missing_carterror. Do not callcartCreatehere: 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-deleteto the cart action model; use an app-owned route. - Mutation returns
userErrorsonly. 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
ownerIdserver-side from the cart cookie (getCartId). Never trust a client-suppliedownerId. - Require an existing cart. Reject writes when no cart cookie is present; never call
cartCreatein 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:
- Cart handlers — add the
CartFragment(see Reading metafields) so the values load into cart state. - Metafields route — an app-owned
POSThandler (see Writing metafields) that runscartMetafieldsSet/cartMetafieldDeleteand returns onlyuserErrors. - Your component — read with
useCart, write via the route, then callrefresh()on success (see Re-syncing the store).
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
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.

