Track cart events in Hydrogen with Shopify analytics
While page view events rely on collecting analytics data from Remix loader functions, add-to-cart events, which mutate API state, are tracked in Remix action functions. Consult Hydrogen’s built-in cart component for an example of an Add to Cart button that uses a Remix action.
RequirementsAnchor link to section titled "Requirements"
Step 1: Collect analytics data from cart actionsAnchor link to section titled "Step 1: Collect analytics data from cart actions"
From any nested route's
action function, return a JSON object containing the analytics data you want to collect. These objects should have the same key name across all actions, in this example
In the following example code, the cart action returns an
analytics object containing the event type and the cart ID:
Step 2: Create a wrapper function to handle cart analyticsAnchor link to section titled "Step 2: Create a wrapper function to handle cart analytics"
You can use Hydrogen's
CartForm component to know when to send analytics after an interaction. For example, you might want to send an add-to-cart analytics event after getting a successful response from the
fetcher request. This wrapper component handles add-to-cart analytics.
|The list of accepted event types.
|A function that returns information about the user's browser.
|A function that handles sending data to Shopify analytics.
The following example code creates a new
AddToCartAnalytics component that can be added to Hydrogen’s
CartForm component. It then uses React’s
useEffect hook to collect the analytics data when the form is submitted and send it to Shopify analytics.
Step 3: Add the wrapper function to CartFormAnchor link to section titled "Step 3: Add the wrapper function to CartForm"
<AddToCartButton> component, include the wrapper function inside
CartForm, along with a hidden input containing the analytics data.
<AddToCartAnalytics/> takes a
fetcher prop provided by
The hidden input should use a consistent key name, in this case
analytics. Hidden input values must be strings, so you should stringify the JSON object when adding it to the form element.