Track cart events in Hydrogen with Shopify analytics
In addition to tracking page views in Hydrogen, you can trigger a Shopify analytics event when a user adds a product to their cart.
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.
Requirements
Anchor link to section titled "Requirements"- You’ve created a Hydrogen app and connected it to your Shopify store.
- You've already created a
usePageAnalytics
custom hook. This custom React hook is used when collecting both page view and cart events.
Step 1: Collect analytics data from cart actions
Anchor 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 analytics
.
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 analytics
Anchor 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 wrapper reuses the usePageAnalytics
custom hook used to track Hydrogen page views. It also uses several built-in Hydrogen utilities:
Utility | Description |
---|---|
AnalyticsEventName |
The list of accepted event types. |
getClientBrowserParameters |
A function that returns information about the user's browser. |
sendShopifyAnalytics |
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 CartForm
Anchor link to section titled "Step 3: Add the wrapper function to CartForm"In your <AddToCartButton>
component, include the wrapper function inside CartForm
, along with a hidden input containing the analytics data. <AddToCartAnalytics/>
takes a fetcher
prop provided by <CartForm/>
.
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.