🧩 CartProvider
Setup
To enable global cart state in your app, wrap your layout or root component with the CartProvider
from @nextshopkit/sdk
.
This provides access to all cart operations via useCart()
and keeps cart state in sync across your components.
✅ Basic Usage (App Router)
In app/layout.tsx
or a similar top-level wrapper:
- TypeScript
- JavaScript
"use client";
import { CartProvider } from "@nextshopkit/sdk/client";
import client from "lib/nextshopkit/client";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return <CartProvider client={client}>{children}</CartProvider>;
}
"use client";
import { CartProvider } from "@nextshopkit/sdk/client";
import client from "lib/nextshopkit/client";
export default function RootLayout({ children }) {
return <CartProvider client={client}>{children}</CartProvider>;
}
This initializes the cart once, stores the cart ID in localStorage
, and provides cart functions throughout the tree.
⚙️ Props Reference
type CartProviderProps = {
client: ShopifyCartClient;
children: React.ReactNode;
debug?: boolean;
config?: CartProviderConfig;
};
client
(required)
Your configured Shopify Storefront API client instance.
Must implement methods like getCart
, addToCart
, removeFromCart
, etc.
debug
(optional)
Logs internal steps to console.log()
in dev mode.
<CartProvider client={client} debug />
config
(optional)
Controls advanced behavior:
- metafield resolution
- typed custom attributes
- transform hooks
➡️ See Types Reference →
🔐 API Token Security
Your client
instance must use a secure Storefront API token.
Never expose Admin API keys or sensitive tokens in client-side code.
You should only use the Storefront API in the browser.
If you need to run advanced logic (like merging carts or setting buyer identity), consider calling SDK methods inside API routes.
🧠 Notes on Cart ID Persistence
- The cart ID is saved in
localStorage
asshopify_cart_id
. - If no cart exists, a new one is created and stored automatically.
- This enables persistent carts between visits on the same device.
🚫 What It Doesn't Do Automatically
While your CartProvider
defines a mergeCarts()
method, it does not auto-merge carts across devices or sessions.
If you want to merge carts after login or identity switch, call:
const { mergeCarts } = useCart();
await mergeCarts(previousCartId);
You’ll need to handle identity tracking separately.
✅ Next: Usage Examples →
Description
Configure and wrap your app in the CartProvider to enable global Shopify cart state management using @nextshopkit/sdk/client.