Skip to content

Carry shopper product customization through add-to-cart - #1534

Merged
ajaynes-godaddy merged 18 commits into
mainfrom
airobuild-9325/widen-cart-contract
Nov 19, 2026
Merged

ajaynes-godaddy merged 18 commits into
mainfrom
airobuild-9325/widen-cart-contract

Conversation

@ajaynes-godaddy

@ajaynes-godaddy ajaynes-godaddy commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Add-to-cart calls can now carry an optional details object (a product asset URL and selected add-ons) and metafields alongside the existing skuId/name/quantity fields, 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

  • Changeset added (docs)

Test Plan

Setup

No special setup required — standard local dev environment.

Steps

  1. Run the following:

    pnpm --filter @godaddy/gd-commerce-server test
    • All tests pass, including new cases asserting details/metafields reach the addLineItemBySkuId mutation and that an invalid productAssetUrl or an oversized add-on list is rejected
  2. Run the following:

    pnpm --filter @godaddy/gd-commerce-storefront build && pnpm --filter @godaddy/gd-commerce-storefront test
    • All tests pass, including a new case asserting a custom addItem() call forwards details/metafields unchanged in the cart POST body

    Note: colors.test.ts and artifacts.test.ts currently fail locally with localStorage.clear is not a function — this is a pre-existing environment issue unrelated to this change (reproduces identically on main) and does not affect the 179 other tests, including the new one above.

  3. Confirm CI checks pass

    • All GitHub Actions checks green

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.
@ajaynes-godaddy
ajaynes-godaddy requested a review from a team as a code owner November 13, 2026 17:37
@ajaynes-godaddy ajaynes-godaddy self-assigned this Nov 13, 2026
@changeset-bot

changeset-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 760c747

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@godaddy/gd-commerce-server Patch
@godaddy/gd-commerce-storefront Patch

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

@sbolinger-godaddy

Copy link
Copy Markdown
Collaborator

Thanks Drew, this is a nice, small change and the contract matches order-api's AddLineItemInput. A few things I noticed:

Worth fixing

  • Invalid customization on the first add leaves an empty cart and returns a 500. assertValidCartItemInput runs inside buildAddLineItemBySkuIdInput, and on POST /cart that's called after addDraftOrder has already created the cart. That's the orphaned cart the pre-create validation loop in cart/POST.ts is there to prevent. It also throws a plain Error, so a bad URL or too many add-ons comes back as a 500 internal_error instead of a 400. Suggest throwing InvalidRequestError and calling the validator from that pre-create loop too, then updating the tests to expect 400.

Smaller items

  • The cart drawer shows the image, but not the add-ons: cart-state.ts maps only selectedOptions. Mapping selectedAddons there would cover the ticket's "drawer matches checkout" item.
  • The add-on value type only allows inputValue, so LIST options (optionValueId) aren't supported, and sending one would hit a TypeError on .inputValue.length. Either support it or note that only TEXT/NUMBER are supported.
  • The "order-api's schema is the authoritative enforcement point" comment isn't quite right. order-api uses plain z.string() for these fields, so this guard is the only place the HTTPS and length limits are enforced.

What I checked

  • Compared the new input types with order-api's storefront.graphql and createFromSkuId.ts. Lines with add-ons always become separate lines (findMatchingLineItem), so two customizations of one SKU make two lines.
  • Read the code path: plain add-to-cart calls build the same mutation input as before.
  • Locally, on Node 24: commerce-server typecheck, lint and tests pass (262), and commerce-storefront build, typecheck and tests pass (186).

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!

@ajaynes-godaddy

ajaynes-godaddy commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

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)?

@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.
@ajaynes-godaddy

Copy link
Copy Markdown
Collaborator Author

@sbolinger-godaddy I believe I've addressed all of your feedback in 454ab95 and b014094.

@pbennett1-godaddy pbennett1-godaddy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Same-SKU adds that differ only by metafields/asset URL merge in order-api, and the second add's customization overwrites the first's.
  2. order-api's BAD_USER_INPUT validation errors (catalog min/max etc.) surface as 502 rather than 400.
  3. 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');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@ajaynes-godaddy

Copy link
Copy Markdown
Collaborator Author
  • Invalid customization on the first add leaves an empty cart and returns a 500. assertValidCartItemInput runs inside buildAddLineItemBySkuIdInput, and on POST /cart that's called after addDraftOrder has already created the cart. That's the orphaned cart the pre-create validation loop in cart/POST.ts is there to prevent. It also throws a plain Error, so a bad URL or too many add-ons comes back as a 500 internal_error instead of a 400. Suggest throwing InvalidRequestError and calling the validator from that pre-create loop too, then updating the tests to expect 400.

This was addressed in fcde81e.

ajaynes-godaddy and others added 5 commits November 18, 2026 18:28
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 pbennett1-godaddy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 metafields from the browser-facing cart shape (replied on that thread).
  • Update packages/commerce-storefront/docs/server-api.md with the new details/metafields request fields for POST /cart and POST /cart/:id/items, including the limits, the https-only productAssetUrl, 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.
@ajaynes-godaddy

Copy link
Copy Markdown
Collaborator Author

@pbennett1-godaddy I believe I've addressed everything from your latest round of feedback. Also c8909c7 covers server-api.md updates.

@pbennett1-godaddy pbennett1-godaddy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@ajaynes-godaddy
ajaynes-godaddy merged commit 2fbe5a5 into main Nov 19, 2026
3 checks passed
@ajaynes-godaddy
ajaynes-godaddy deleted the airobuild-9325/widen-cart-contract branch November 19, 2026 20:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants