๐ CartProvider
& useCart()
Overview
The CartProvider
and useCart()
hook from @nextshopkit/sdk
give you a complete, reactive cart system that works in modern Shopify headless storefronts.
It combines React Context, Shopify Storefront API, and advanced configuration options to manage:
- Persistent cart state
- Line item operations (add, remove, update)
- Discount codes
- Buyer identity
- Custom cart attributes
- Fully typed metafield casting
โ When to Use Thisโ
- Building a custom cart page
- Adding Add to Cart buttons across your site
- Displaying a mini cart in the header
- Managing cart state globally via React Context
- Working with typed custom attributes and metafields
- Or using standalone cart methods in non-React or SSR environments
๐ง Key Featuresโ
- โ๏ธ React Context provider (
<CartProvider />
) - ๐ช Hook access via
useCart()
- ๐ฆ LocalStorage cart ID persistence
- ๐งพ Discount code support
- ๐ Secure Storefront API integration
- ๐ฏ Strong TypeScript support
- ๐งฌ Metafield casting with transform hooks
- ๐งฐ Optional standalone methods for server use
๐ฆ Exposed Methodsโ
const {
cart,
loading,
addProducts,
removeProduct,
updateQuantity,
applyDiscountCode,
removeDiscountCode,
emptyCart,
mergeCarts,
updateBuyerIdentity,
updateCartAttributes,
setCartAttribute,
removeCartAttribute,
resetCart,
totalCount,
totalPrice,
typedCartAttributes,
} = useCart();
โก๏ธ Learn more in the API Reference โ
๐ง Requirementsโ
- Your Shopify Storefront API token must not be hardcoded into client-side code.
- If calling standalone SDK methods, use a secure environment (like API routes or server components).
- Ensure your Storefront API has the correct permissions enabled for cart access.
๐งช Pro Tipโ
Use typed cart attributes to cast metafields into useful frontend shapes, like:
- Tags
- Flags (e.g.
custom.isB2B
) - UI-driven personalization
typedCartAttributes.customTagline; // โ "Free shipping on orders over โฌ100"
โ Next: Provider Setup โ
Description
Manage Shopify cart state with React Context, standalone API methods, and full metafield support using @nextshopkit/sdk.