Customize a cart handler
The cart handler is an interface that allows you to easily make cart query and mutation requests to the Storefront API. It creates a new cart if one doesn't already exist, and provides default built-in cart queries.
This guide shows you how to customize a cart handler. You can customize a cart handler to return different cart query fields, override existing cart query functions, and add new cart query functions.
Requirements
Anchor link to section titled "Requirements"- You've completed the quickstart guide.
- You've set up a cart handler.
Customize the return cart fields
Anchor link to section titled "Customize the return cart fields"The createCartHandler
includes a default query fragment. Pass a custom cartQueryFragment
if you need additional data from the Storefront API. See the default CartApiQuery
fragment for reference. In this example, we added the note
field.
Provide cartMutateFragment
to customize what data is returned from mutation queries. See the default CartApiMutation
fragment for reference. In this example, we added the checkoutUrl
field.
Add custom methods to cart handler
Anchor link to section titled "Add custom methods to cart handler"If you have common cart operations that you would like to reuse across your app, you can add custom methods to your cart handler. For example, add and remove an item from the cart at the same time.
Override existing cart handler methods
Anchor link to section titled "Override existing cart handler methods"Hydrogen provides out of the box multiple methods for interacting with the cart. You can override any default method with your own logic. For example, you can override the updateAttributes
to do something custom with cart attributes:
The default cart handler includes basic cart logic. If you override these methods, you need to implement the cart logic as well. For example when adding a line item to a cart, you would need to implement the logic needed to create a cart with the line item.
The following methods include create cart logic::
addLines
- If a cart doesn't exist, then create a cart with the line items.setMetafields
- If a cart doesn't exist, then create a cart with the metafields applied.updateAttributes
- If a cart doesn't exist, then create a cart with the attributes applied.updateBuyerIdentity
- If a cart doesn't exist, then create a cart with the buyer identity applied.updateDiscountCode
- If a cart doesn't exist, then create a cart with the discount applied.updateNote
- If a cart doesn't exist, then create a cart with the note applied.