---
title: Managing the cart (Shopify Hydrogen)
slug: p1oe0470
canonical_url: https://docs.coveo.com/en/p1oe0470/
collection: coveo-for-commerce
source_format: adoc
---
# Managing the cart (Shopify Hydrogen)
When building Coveo-powered commerce interfaces using [server-side rendering (SSR)](https://docs.coveo.com/en/p2af0263/), it's crucial to keep the Headless cart state synchronized with the Shopify cart.
When a user interacts with the cart, such as adding or removing a product, the cart state must be updated in the Headless engine and the Shopify cart.
## Convert the Shopify cart to a Headless cart
When [fetching the static state](https://docs.coveo.com/en/p3ae0283#fetch-static-headless-state) of the app, you must retrieve the Shopify cart state and convert it to the Headless cart state.
The following example shows how to convert the Shopify cart to a Headless cart:
```ts
// lib/map-coveo-shopify.cart-ts
import type {CartItem as HeadlessCartItem} from '@coveo/headless-react/ssr-commerce';
import type {
CartLine,
ComponentizableCartLine,
CartReturn,
} from '@shopify/hydrogen/storefront-api-types';
function mapShopifyCartToCoveoCart(cart: CartReturn | null) { <1>
return {
items: cart?.lines.nodes.map((node) => {
return mapShopifyMerchandiseToCoveoCartItem(node);
}),
};
}
export function mapShopifyMerchandiseToCoveoCartItem( <2>
node: CartLine | ComponentizableCartLine,
): HeadlessCartItem {
const {merchandise} = node;
const selectedColor = merchandise.selectedOptions.find(
(opt) => opt.name === 'Color',
);
return {
productId: `${merchandise.product.handle.toUpperCase()}_${colorToShorthand(
selectedColor?.value || '',
)}`,
name: merchandise.product.title,
price: Number(merchandise.price.amount),
quantity: node.quantity,
};
}
export function colorToShorthand(color: string) {
const colorMap: {[key: string]: string} = {
'birchwood brown': 'BB',
black: 'BK',
blue: 'BL',
brown: 'BR',
clear: 'CL',
cyan: 'CY',
'deep red': 'DR',
'forest green': 'FG',
gray: 'GY',
green: 'GN',
grey: 'GY',
khaki: 'KH',
lime: 'LM',
'multi color': 'MC',
'multi-colored': 'MC',
natural: 'NT',
navy: 'NY',
'olive green': 'OG',
olive: 'OL',
one: '01',
orange: 'OR',
pink: 'PK',
purple: 'PL',
red: 'RD',
'rustic yellow': 'RY',
silver: 'SV',
'sky blue': 'SB',
white: 'WH',
yellow: 'YL',
beige: 'BG',
gold: 'GD',
striped: 'ST',
neon: 'NE',
pastel: 'PS',
tan: 'TN',
};
return colorMap[color.toLowerCase() as keyof typeof colorMap] || 'BK';
}
```
<1> Define a `mapShopifyCartToCoveoCart` method that converts a Shopify cart to a Headless cart.
<2> The `mapShopifyMerchandiseToCoveoCartItem` method converts a Shopify [`CartLine`](https://shopify.dev/docs/api/functions/reference/cart-transform/graphql/common-objects/cartline) to a Headless [`CartItem`](https://docs.coveo.com/en/headless-react/latest/reference/interfaces/SSR_Commerce.index.CartItem.html) object.
## Modify the cart state based on user interactions
When a user interacts with the cart, such as adding or removing a product, you must update both the Shopify cart and the Headless cart state.
This section focuses on the Headless-specific implementation.
For details on updating the Shopify cart, refer to the [Shopify documentation](https://shopify.dev/docs/storefronts/headless/hydrogen/cart/manage).
> **Note**
>
> To use the components defined in the following section, make sure you have [set up a cart handler](https://shopify.dev/docs/storefronts/headless/hydrogen/cart/setup) and can [read cart data](https://shopify.dev/docs/storefronts/headless/hydrogen/cart/read).
>
> This setup provides access to the Shopify cart, which is passed to the components as a prop to access objects such as `lines` and `lineIds`.
### Add cart items
The add-to-cart button component is often included directly on the [product listing page (PLP)](https://docs.coveo.com/en/m1sf3187/), [product detail page (PDP)](https://docs.coveo.com/en/n8ad7392/), or the search results page.
```tsx
import {CartForm} from '@shopify/hydrogen';
import {useCart} from '~/lib/commerce-engine.ts';
import {Product} from '@coveo/headless-react/ssr-commerce';
export default function AddToCartButton({
product,
lines,
}: {
product: Product;
lines: { quantity: number }[];
}) {
const coveoCart = useCart(); <1>
const currentQuantity = <2>
coveoCart.state.items.find((item) => item.productId === product.id)
?.quantity || 0;
const quantityToAdd = lines[0]?.quantity ?? 0;
const newQuantity = currentQuantity + quantityToAdd;
return (
inputs={{ lines }}
>
);
}
```
<1> Use the `useCart` hook to retrieve the Headless cart state.
Ensure that the cart controller was [defined when creating your engine configuration](https://docs.coveo.com/en/p27e1343#define-the-controllers).
<2> Calculate the current quantity of the product in the cart.
<3> Use the `CartForm` component to submit the cart update as specified in the [Shopify documentation](https://shopify.dev/docs/storefronts/headless/hydrogen/cart/manage#add-cart-items).
<4> Update the cart item quantity by calling the [`updateItemQuantity`](https://docs.coveo.com/en/headless-react/latest/reference/interfaces/SSR_Commerce.index.Cart.html#updateitemquantity) method.
### Update cart items
When a user updates an item's quantity in the cart, ensure the Headless cart state reflects the new quantity.
```tsx
import {CartForm} from '@shopify/hydrogen';
import type {CartLineUpdateInput} from '@shopify/hydrogen/storefront-api-types';
import type {CartItem} from '@coveo/headless-react/ssr-commerce';
import {useCart} from '~/lib/commerce-engine.ts';
export default function UpdateCartItemsButton({
cartItem,
lines,
newQuantity,
}: {
cartItem: CartItem;
lines: CartLineUpdateInput[];
newQuantity: number;
}) {
const coveoCart = useCart();
return (
inputs={{ lines }}
>
);
}
```
<1> Use the `CartForm` component to submit the cart update as specified in the [Shopify documentation](https://shopify.dev/docs/storefronts/headless/hydrogen/cart/manage#update-cart-items).
<2> Update the cart item quantity using the [`updateItemQuantity`](https://docs.coveo.com/en/headless-react/latest/reference/interfaces/SSR_Commerce.index.Cart.html#updateitemquantity) method.
### Remove cart items
When a user removes an item from the cart, update the Headless cart state by setting the item's quantity to `0`.
```tsx
import { CartForm } from '@shopify/hydrogen';
import type { CartItem } from '@coveo/headless-react/ssr-commerce';
import { useCart } from '~/lib/commerce-engine.ts';
export default function RemoveCartItemButton({
lineIds,
cartItem,
}: { lineIds: string[]; cartItem: CartItem }) {
const coveoCart = useCart();
return (
inputs={{ lineIds }}
>
);
}
```
<1> Use the `CartForm` component to submit the cart update as specified in the [Shopify documentation](https://shopify.dev/docs/storefronts/headless/hydrogen/cart/manage#remove-cart-items).
<2> Update the cart item quantity to `0` using the [`updateItemQuantity`](https://docs.coveo.com/en/headless-react/latest/reference/interfaces/SSR_Commerce.index.Cart.html#updateitemquantity) method.