Set up analytics instrumentation
In this tutorial, you'll learn how to instrument analytics on page view and cart-related interaction events. You can report these events to Shopify and to third party analytics tools like Google Analytics.
Requirements
Anchor link to section titled "Requirements"- You've completed the quickstart guide.
- You can add an item to cart.
Step 1: Set up the page view event
Anchor link to section titled "Step 1: Set up the page view event"Set up your Remix app to recieve page view events.
Use Remix's
useLocation
to attach the page view event.From any
loader
, return an object with the desired analytics data. The following example usesanalytics
as the common data key:Create a utility function that collects the
analytics
events from all loaders triggered by the current route navigation.By default, Remix's built-in
useLoaderData
hook, which fires on every route navigation, only returns data from the current route's associated loader. Creating the utility function enables you to aggregate the Store ID from the app root loader function with product data from the$productHandle
loader function.The following utility function collects all data with an
analytics
data key from all loaders using Remix's built-inuseMatches
hook.Use the utility function to retrieve an object that contains any data from any loader with the data key
analytics
Step 2: Set up a cart interaction event
Anchor link to section titled "Step 2: Set up a cart interaction event"Interaction events that expect a response from an API endpoint are often implemented with Remix's actions. If you followed the tutorial for adding an item to cart, then your add to cart button makes a request to the cart action. Collecting analytics data from actions is slightly different from loaders.
From any
action
, return an object with the desired analytics data. The following example usesanalytics
as the common data key:With a
CartForm
, you can add additional data as hidden form inputs under the same data key as long as it is JSON parseable.Use the
fetcher
provided byCartForm
to know when to send analytics after an interaction. For example, we want to send an add to cart analytics event after we obtained a successful response from the fetcher request. Create a wrapper component that handles add to cart analytics.Add the
AddToCartAnalytics
wrapper component to theAddToCartButton
- Set up Shopify analytics.