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.
RequirementsAnchor link to section titled "Requirements"
Customize the return cart fieldsAnchor link to section titled "Customize the return cart fields"
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
cartMutateFragment to customize what data is returned from mutation queries. See the default
CartApiMutation fragment for reference. In this example, we added the
Add custom methods to cart handlerAnchor 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 methodsAnchor 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.