Create Cart Context in the Storefront
Share cart state across React components.
On this page
In this guide, you'll learn how to share cart state in a storefront.
Next.js App Router (recommended)
Do not create a client CartProvider that calls the SDK in useEffect and stores the cart ID in localStorage.
On Next.js:
- Persist the cart ID in the
_aiminaabee_cart_idhttpOnly cookie. - Create or load the cart in
src/lib/data/cart.ts(getOrSetCart,retrieveCart). - Call those functions from pages and server actions. Pass
storeCodeand the URLcountryCodeseparately. - After mutations,
revalidateTagforcarts(andfulfillmentwhen shipping options can change).
See Build a Next.js Storefront and Create Cart.
A small client hook is fine for UI-only cart drawers. It should call server actions, not sdk.store.cart directly.
SPA: Cart Context Provider
If you're building a client-rendered SPA (not App Router), a React context can hold the current cart so product pages can add items without prop drilling.
The provider should:
- Resolve the customer's region first.
- Create a cart if none exists, or retrieve it by ID.
- Persist the cart ID the same way the rest of the SPA does (cookie or memory). Prefer a cookie over
localStorageso you can later move to SSR.
tsx
Copy
Wrap the tree with RegionProvider outside CartProvider. Use refreshCart after login, logout, or placing an order.
Tip: Add helpers for line items and region updates from: