Skip to main content

Cart store

The createCartStore function holds the customer's cart in the browser and shows cart changes before the server confirms them. Use the function in frameworks without a Hydrogen binding to start from the server's cart, submit cart forms, and rerender your cart UI when the cart changes.

In React and Vue apps, use createCartComponents.

Import createCartStore and configureCartEndpoint from @shopify/hydrogen.

Render ShopifyScripts before you connect a store. The store sends cart changes through Standard Actions, a Shopify storefront script that ShopifyScripts loads.


Creates a cart store that holds the cart and applies cart changes before the server responds.

Call connect() to start the store and destroy() to stop it. The React and Vue cart providers call both for you.

Anchor to options
options
<>

The cart that the server loaded for the first render.

The cart store. Read the cart with getState() and listen for changes with subscribe().

Examples

TypeScript

import { configureCartEndpoint, createCartStore, type CartData } from "@shopify/hydrogen";

export function mountCart(initialCart: CartData | null, render: (cart: CartData) => void) {
configureCartEndpoint("/api/cart");

const store = createCartStore({ initialData: { cart: initialCart } });
store.connect();

const unsubscribe = store.subscribe((state) => {
render(state.data);
});

return () => {
unsubscribe();
store.destroy();
};
}

Sends every cart load and cart change on the page to your cart endpoint. Without an endpoint, Standard Actions handles cart requests with its default handler.

Call the function before you connect a cart store. The first cart load then goes to your endpoint. A later call with a different endpoint replaces the first endpoint and logs a warning. In React, CartProvider sets the endpoint to /api/cart when the provider mounts.

Anchor to endpoint
endpoint
string
required

The URL path of your cart route.

Nothing. Later cart loads and changes on the page go to the endpoint.

Examples

TypeScript

import { configureCartEndpoint, createCartStore } from "@shopify/hydrogen";

const cartStore = createCartStore();

export function connectCartStore() {
if (typeof window === "undefined") return;

configureCartEndpoint("/api/cart");
cartStore.connect();
}

Was this page helpful?