Skip to main content

๐Ÿ›’ 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.