Repository navigation
Carry shopper product customization through add-to-cart - #1534
Conversation
AIROBUILD-9325
AddToCartItemInput was narrowed to { skuId, name, quantity }, so shopper
customization (uploaded designs, add-ons, metafields) never reached
order-api or checkout. Widen the cart contract end-to-end:
- order-subgraph.ts: add optional details (productAssetUrl,
selectedAddons) and metafields to AddToCartItemInput, forward them in
buildAddLineItemBySkuIdInput with length/HTTPS/count validation, and
select metafields in getCartOrderQuery so they round-trip on read.
- cart/[id]/items/POST.ts: forward the full validated body instead of a
hand-picked three-field literal.
- cart-model.ts: widen the storefront-side AddToCartItemInput identically.
- commerce-provider.tsx: addItem() was rebuilding a narrowed
{ skuId, name, quantity } object before calling addToCart(), dropping
details/metafields even after the type widened; pass the full item
through instead.
🦋 Changeset detectedLatest commit: 760c747 The changes in this PR will be included in the next version bump. This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Thanks Drew, this is a nice, small change and the contract matches order-api's Worth fixing
Smaller items
What I checked
Could you also add screenshot proof from the MCP playground showing a customized item in hosted checkout (the add-on text and the preview image)? Thanks! |
@sbolinger-godaddy Here's a short Loom showing the line item data before and after: https://www.loom.com/share/0e97ef9539b4401bb1290b648785bd0c I'll get you a catalog add-to-cart view version of this and report back. Edit: Here's another short loom showing the product detail and image (the mug): https://www.loom.com/share/2a72b573652f457b9f5442df1051cfa9 Let me know if you had something else in mind. |
The cart drawer mapped only catalog selectedOptions (Color, Size) into CartItemOptions, so a line's selectedAddons (shopper customization) showed the preview image but not the add-on text, leaving the drawer out of sync with checkout. Fold selectedAddons into the same options list useCart() already exposes, reusing the existing "Label: value" rendering.
… cart
assertValidCartItemInput ran inside buildAddLineItemBySkuIdInput, which on
POST /cart is only reached after addDraftOrder already created the cart —
an invalid productAssetUrl or an oversized add-on list orphaned that cart
and, since it threw a plain Error, came back as a 500 instead of a 400.
Run the same validation in the pre-create loop, and switch every check to
InvalidRequestError so it maps to 400.
Also reject a LIST-option addon value ({ optionValueId }) explicitly: only
TEXT/NUMBER options ({ inputValue }) are supported by this change, and an
optionValueId-only value previously crashed with a TypeError on
.inputValue.length instead of a clean validation error.
Correct a comment that called this guard UX-only with order-api's schema
as the authoritative enforcement point — order-api's schema has no such
length/HTTPS/count limits, so this is the only place they're enforced.
|
@sbolinger-godaddy I believe I've addressed all of your feedback in 454ab95 and b014094. |
pbennett1-godaddy
left a comment
There was a problem hiding this comment.
Reviewed against order-api main (5b1ef214): storefront.graphql and actions/line-items/createFromSkuId.ts. The input shapes (AddLineItemDetailsInput, AddLineItemSelectedAddonsInput, OrderMetafieldInput) and the line-item metafields selection match the storefront subgraph.
Main concerns:
- Same-SKU adds that differ only by metafields/asset URL merge in order-api, and the second add's customization overwrites the first's.
- order-api's
BAD_USER_INPUTvalidation errors (catalog min/max etc.) surface as 502 rather than 400. - Local validation doesn't check runtime types, so malformed bodies 500.
Also not updated: packages/commerce-storefront/docs/server-api.md should document the new details/metafields request fields and the metafields in cart responses. LIST-option (optionValueId) support is fine to defer, since order-api already supports it; maybe track a follow-up.
| } catch { | ||
| throw new InvalidRequestError('productAssetUrl must be an absolute URL'); | ||
| } | ||
| if (parsed.protocol !== 'https:') throw new InvalidRequestError('productAssetUrl must use https'); |
There was a problem hiding this comment.
order-api uses data.details?.productAssetUrl || <catalog media>, so any https URL a shopper sends replaces the catalog image on the merchant's order, emails and fulfillment views. If this is meant for design previews, consider restricting it to a host-configured origin allowlist rather than any https URL.
There was a problem hiding this comment.
I think an allowlist would make sense here, but worry we might "paint ourselves into a corner" so to speak if the allowlist isn't broad enough for it to work well. What hosts would you propose to explicitly allow?
There was a problem hiding this comment.
Agreed, let's not add an allowlist for now. It only makes sense if we can confirm Airo uploads design assets to specific CDNs. If we confirm that later, an optional host-configured origin list (with unset meaning any https URL, as today) would avoid painting ourselves into a corner. The https check is fine for this PR.
There was a problem hiding this comment.
Leaving this unresolved so it's easier to find when we return to this question.
…ead of 500 assertValidCartItemInput assumed metafields/selectedAddons already matched their TypeScript shapes, so a non-array selectedAddons, a metafield missing key/value, or a non-string metafield value threw an uncaught TypeError instead of InvalidRequestError. The add-item route also cast the request body to AddToCartItemInput before any validation ran. Validate the body's shape explicitly before the cast, and check each field's type before reading off it.
AddLineItemMetafieldInput passed through metafield.type ?? 'JSON', so a client-supplied type reached order-api unchecked (order-api rejects anything but a literal 'JSON', turning it into a 502) and any other client property on a metafield object was forwarded too. JSON is the only supported type, so build the mutation input by picking key/value explicitly and always setting type: 'JSON'. Drop the now-pointless type field from AddToCartMetafieldInput in both packages.
…names in the drawer useCart() mapped selectedAddons values with value.name ?? '', so a value missing a name rendered a blank "Attribute: " line, and costAdjustment was read from the API response but never surfaced, so a priced addon's surcharge was invisible next to a subtotal that already included it. Skip values with no name, and append the formatted cost adjustment to the ones that have a price.
This was addressed in fcde81e. |
order-api reports its own input validation (catalog option min/max, the TEXT/NUMBER single-value rule, a SKU with no price, etc.) as a BAD_USER_INPUT GraphQL error code on addLineItemBySkuId and addDraftOrder. The shopper can't have known a catalog-side rule in advance, but every cart route still answered this the same as a true upstream outage: a generic 502 internal_error. Add a classifyCartUpstreamError rule matching BAD_USER_INPUT and mapping it to InvalidRequestError (400), reused across all existing saved-cart routes. POST /cart had no classifier at all (its "no existing cart to miss" note in classifyCartUpstreamError excludes it from that one), so give it its own classifyCartCreationUpstreamError for just this rule.
order-api's findMatchingLineItem only treats an addLineItemBySkuId call as a new line when details.selectedAddons is present; it ignores metafields and details.productAssetUrl entirely. So two adds of the same skuId that differ only by metafields or productAssetUrl, with no selectedAddons on either, merge into one line in order-api, and buildLineItemFromSku replaces the first add's details/metafields with the second's rather than merging them — the first customization is silently lost. This is order-api behavior, not something this repo's route code can fix. Document it on AddToCartItemInput so a caller needing metafield-only or image-only customizations to stay on distinct lines knows to also include a distinguishing selectedAddons entry, and add a test pinning what this route actually sends (two independent mutation calls, each with its own metafields) so the limitation is visible rather than silently assumed.
…er object
addItem(item) passed item straight through to addToCart(), so a caller
spreading a larger object (e.g. addItem({ ...product, skuId, name,
quantity })) now serialized every other property on product into the
cart POST body. order-api rejects unknown fields on its strict schema,
so this surfaced as a 502 instead of a clean validation error. Pick only
skuId, name, quantity, details, and metafields before calling addToCart,
the same allowlist AddToCartButton already applies.
…outes Both cart/POST.ts and cart/[id]/items/POST.ts read the required fields off the untyped request body by hand, then cast the rest of the body straight to AddToCartItemInput before calling assertValidCartItemInput separately. The cast was a type-only annotation with no runtime filtering, so a body carrying extra properties (or a malformed one that assertValidCartItemInput didn't happen to check) had no single place guaranteeing it was shaped and allowlisted before use, and the two routes' required-field checks had already drifted into slightly different messages. Add parseCartItemInput(body) in order-subgraph.ts: validates skuId/name/ quantity, allowlists exactly the known fields (skuId, name, quantity, details, metafields), and runs assertValidCartItemInput, returning a trusted AddToCartItemInput. Both routes now call this once instead of hand-rolling their own field checks and casting the remainder.
pbennett1-godaddy
left a comment
There was a problem hiding this comment.
Re-reviewed at c43a6126. Thanks for the fixes: shape validation, the allowlist on both sides, always sending type: 'JSON', the BAD_USER_INPUT → 400 mapping and the addon display all look good, and the merge comment is fine as a documented limitation pending order-api.
Remaining before merge:
- Remove
metafieldsfrom the browser-facing cart shape (replied on that thread). - Update
packages/commerce-storefront/docs/server-api.mdwith the newdetails/metafieldsrequest fields forPOST /cartandPOST /cart/:id/items, including the limits, the https-onlyproductAssetUrl, the unsupported LIST (optionValueId) values, and the same-SKU merge behavior.
Inline comments below cover the wider reach of the 400 rule, the unlocalized surcharge text, and two minor cleanups.
…ute only Adding BAD_USER_INPUT_RULE to the shared CART_UPSTREAM_ERROR_RULES applied it to every route using classifyCartUpstreamError — cart GET, discounts POST, and item PATCH/DELETE — not just add-item, which is the only path this PR actually exercises for that code. A promo code or other BAD_USER_INPUT on those other routes would now have silently become a 400 with an add-item-flavored message, untested. Split it into a dedicated classifyAddItemUpstreamError (cart-not-found + BAD_USER_INPUT) used only by cart/[id]/items/POST.ts, and revert classifyCartUpstreamError back to just the cart-not-found rule for the other routes. classifyCartCreationUpstreamError (POST /cart) already only applied BAD_USER_INPUT and is unaffected.
…e double validation
parseCartItemInput forwarded candidate.details wholesale, so unknown keys
inside it (sku, unitOfMeasure, or extra properties on an addon or its
values) still reached order-api — cosmetic now that BAD_USER_INPUT maps
to 400, but incomplete next to the explicit metafields pick already in
place. Validate the candidate first, then rebuild details by picking only
productAssetUrl and selectedAddons (each addon narrowed to optionId and
values: [{ inputValue }]), the same way metafields is narrowed to key/value.
Validating before picking also means every field the pick reads is
already known-valid, so buildAddLineItemBySkuIdInput's own
assertValidCartItemInput call is now pure duplication for both of its
only two callers — both already go through parseCartItemInput. Remove it
and document the precondition on the function instead.
Cart reads returned every line-item metafield to the browser, including ones written by the merchant or other apps that have nothing to do with this storefront, to anyone holding a cart id. Metafields added here are a write-only mechanism (e.g. a designId reference) for the merchant's order, not a display surface — anything a shopper should see echoed back (engraving text, a selected addon) already has a home in details.selectedAddons, which still round-trips on read. Remove metafields from getCartOrderQuery's lineItems selection and the CartMetafield/CartLineItem.metafields read-side type in both order-subgraph.ts and the storefront's cart-model.ts. Add-to-cart can still send metafields; the browser just no longer reads them back.
…ge catalog
useCart() built "(+$5.00)" with raw string interpolation and a manual
cost.value > 0 ? '+' : '' ternary, bypassing messages.ts/fr-fr.ts
entirely — every other package string goes through a message key, and
the manual ternary never added a sign for a negative adjustment (it
relied on Intl's default negative rendering, untested).
Add addonValueWithCost: '{name} ({amount})' to messages.ts and fr-fr.ts
(a pure interpolation template with no localizable wording, so it's
exempted from messages.test.tsx's English/French identity check the
same way skuOptionLabel already is). Format the signed amount with a
small dedicated Intl.NumberFormat using signDisplay: 'exceptZero'
instead of the manual ternary — kept separate from api.ts's shared
money() cache since signDisplay is only needed on this path.
…n add-item server-api.md's endpoint table and cart-response description still showed the pre-widening three-field contract, with no mention of details, metafields, their limits, the https-only productAssetUrl rule, the unsupported LIST-option addon shape, or the same-SKU merge limitation that order-api's own line-matching has today.
|
@pbennett1-godaddy I believe I've addressed everything from your latest round of feedback. Also c8909c7 covers |
pbennett1-godaddy
left a comment
There was a problem hiding this comment.
Re-reviewed at c8909c79. Everything from the last round is addressed: metafields are out of cart reads, the 400 mapping only applies to adding items, the surcharge text uses a message key, details is fully allowlisted, items are validated once, and server-api.md is updated. Approving. The two inline nits are non-blocking. Thanks!
…urcharge format cache server-api.md described productAssetUrl as both "additive to the catalog image" and taking "priority over the catalog image everywhere" in the same sentence, which reads as contradictory. State plainly that it replaces the image for this line item only; the catalog itself is unchanged. Also cap the addon-surcharge Intl.NumberFormat cache added for the signDisplay fix, matching api.ts's currencyFormat eviction pattern — not a correctness issue (locale/currency pairs are few in practice), just consistency with the existing cache nearby.
Summary
Add-to-cart calls can now carry an optional
detailsobject (a product asset URL and selected add-ons) andmetafieldsalongside the existingskuId/name/quantityfields, so a shopper's product customization travels with the line item all the way through checkout instead of being limited to the client. Existing add-to-cart calls that don't use these fields are unaffected.Changeset
Test Plan
Setup
No special setup required — standard local dev environment.
Steps
Run the following:
pnpm --filter @godaddy/gd-commerce-server testdetails/metafieldsreach theaddLineItemBySkuIdmutation and that an invalidproductAssetUrlor an oversized add-on list is rejectedRun the following:
addItem()call forwardsdetails/metafieldsunchanged in the cart POST bodyNote:
colors.test.tsandartifacts.test.tscurrently fail locally withlocalStorage.clear is not a function— this is a pre-existing environment issue unrelated to this change (reproduces identically onmain) and does not affect the 179 other tests, including the new one above.Confirm CI checks pass