Skip to content
Guides

Cart

Mount CartProvider and manage the cart persisted in Storefront API.

The SDK cart is not a separate local store. CartProvider keeps the session identifier in localStorage and loads the real cart from Storefront API.

1. Mount the provider

layout.tsx
import { CartProvider, defineLayout } from "@ecomiq/storefront";

export default defineLayout(({ children, settings }) => (
  <CartProvider
    storeId={settings.store.id}
    currencyCode={settings.store.currency}
  >
    {children}
  </CartProvider>
));

The local key is ecomiq:cart:v1:{storeId}, so the session is isolated by store. Only the identifier is persisted; prices, inventory, and totals are reloaded from the API.

2. Add a variant

import { useCart } from "@ecomiq/storefront";

export function AddToCartButton({ variantId }: { variantId: string }) {
  const { addItem, mutation, error } = useCart();
  const isAdding = mutation?.kind === "adding";

  return (
    <>
      <button
        type="button"
        disabled={isAdding}
        onClick={() => void addItem({ variantId, quantity: 1 })}
      >
        {isAdding ? "Adding…" : "Add to cart"}
      </button>
      {error ? <p>{error}</p> : null}
    </>
  );
}

variantId is the positive decimal ID returned on a ProductDetail variant.

3. Create the cart page

/cart is not a framework-owned route; create your own UI:

pages/cart.tsx
import { definePage, Link, useCart } from "@ecomiq/storefront";

export default definePage({
  meta: () => ({ title: "Cart", noIndex: true }),
  component: CartPage,
});

function CartPage() {
  const { cart, itemCount, loadStatus, removeItem } = useCart();

  if (loadStatus === "loading") return <p>Loading…</p>;
  if (!cart?.items.length) return <p>Your cart is empty.</p>;

  return (
    <main>
      <h1>{itemCount} products</h1>
      {cart.items.map((item) => (
        <div key={item.id}>
          <span>
            {item.title} × {item.quantity}
          </span>
          <button onClick={() => void removeItem(item.id)}>Remove</button>
        </div>
      ))}
      <Link to="/checkout/$checkoutId" params={{ checkoutId: cart.id }}>
        Go to checkout
      </Link>
    </main>
  );
}

useCart contract

Field or actionUse
cart, cartIdLoaded cart and active identifier.
itemCountSum of item quantities.
loadStatusloading, ready, or error.
mutation, errorState of the latest operation.
addItemAdds { variantId, quantity }.
setItemQuantityChanges a line's quantity.
removeItemRemoves a line.
reloadReloads the cart from the API.
clearCartDeletes the current local session.

To use the included checkout, also add AuthProvider as described in the checkout guide.

On this page