Analytics
Shopify collects analytics for headless storefronts the same way as for themes, for the reports and the live view in your Shopify admin.
The module loads the same scripts as Shopify's own storefronts, from @shopify/hydrogen, and reports page views automatically.
For product, collection, search and cart views, it provides a component each.
Getting started
Analytics is opt-in. Enable it in your nuxt.config.ts:
export default defineNuxtConfig({
shopify: {
name: 'nuxt-module-store',
clients: {
storefront: {
publicAccessToken: '...',
},
},
analytics: true,
},
})
Configuration
The analytics option accepts true, false (default), or an object with the following settings, all optional:
page_viewed event on the initial load and on every client-side navigation. Defaults to true; set it to
false to publish page views yourself.The shop and its locales are set in top-level options, because the Shopify routes use them too:
12345). Fetched from your store when omitted.NUXT_SHOPIFY_STOREFRONT_ID, see environment variables.defaultLocale that has a country, a language and an optional currency, see
buyer market. Your shop's default market is fetched with the storefront client when omitted.To skip these lookups, set shopId and an i18n.defaultLocale with a currency.
Without the storefront client, you need to set both.
export default defineNuxtConfig({
shopify: {
shopId: 12345,
storefrontId: 1000012345,
i18n: {
defaultLocale: {
country: 'US',
language: 'EN',
currency: 'USD',
},
},
analytics: true,
},
})
Shopify's scripts
The module adds Shopify's scripts to the head of every page and starts them when the app is mounted.
The scripts are added whenever the storefront client or analytics is configured, because Hydrogen's cart also uses them.
With analytics disabled, they are added without Shopify's analytics script.
With routes: false on the storefront client, they aren't added at all, and analytics can't be enabled, see without the routes.
They still need the locale of the request, so set i18n.defaultLocale to skip the lookup of your shop's default market.
When analytics is enabled, the module also adds Shopify's analytics and performance scripts, the privacy banner for your consent mode, and page views. The scripts send their requests to Shopify through the Shopify routes on your own domain. If your pages don't use Shopify's standard paths, set your route templates, so that the scripts link to your pages.
Tracking views
Page views are reported automatically.
The module reports a page_viewed event on the initial load and on every client-side navigation.
Changing only the hash of the URL, for example to jump to an anchor, doesn't report another view.
For product, collection, search and cart views, the module provides a renderless component each.
Their data prop takes the event payload from @shopify/hydrogen, such as ProductViewPayload.
The product and collection components report the view again when the product or collection changes, for example on client-side navigation between two products.
ShopifyCartView reports a cart_viewed event once per mount, after the cart has loaded and has no pending changes.
<template>
<!-- your product page -->
<ShopifyProductView
:data="{
products: [{
id: product.id,
title: product.title,
vendor: product.vendor,
price: variant.price,
variantId: variant.id,
variantTitle: variant.title,
quantity: 1,
}],
}"
/>
</template>
price is the variant's MoneyV2 with amount and currencyCode, as returned by the Storefront API.
If a field that Shopify needs is missing, Shopify's analytics script logs it in the browser console.
The other view components work the same way:
<template>
<ShopifyCollectionView :data="{ collection: { id: collection.id, handle: collection.handle } }" />
<ShopifySearchView :data="{ searchTerm: query, searchResults: { totalCount } }" />
<ShopifyCartView :cart="cartState" />
</template>
ShopifySearchView only reports searches with a term, and reports again when the term or the searchResults change.
Take both from the same response, so that a new term isn't reported with the results of the previous term while they load.
ShopifyCartView takes the whole state of Hydrogen's cart in its cart prop, such as useCart(state => state), not only the cart's data.
Use the components on server-rendered pages. On a page that is only rendered in the browser, Shopify's scripts load after the page is mounted, so views reported while mounting are lost.
Analytics composable
To publish events yourself, use the useShopifyAnalytics() composable.
It returns Shopify's analytics bus, typed as StorefrontAnalytics from @shopify/hydrogen.
On the server and before Shopify's scripts have loaded, it returns null, so call it in browser code, such as in onMounted or an event handler:
const analytics = useShopifyAnalytics()
analytics?.publish('product_viewed', {
products: [/* ... */],
})
publish only accepts Shopify's standard events, typed by @shopify/hydrogen.
The shop and the page URL are added automatically, and events are held until the visitor's consent allows them.
Buyer market
Events include the country, currency and language of the locale of the request, the same locale as the cart:
- the locale that your app sets in
event.context.shopifyLocalein a Nitro plugin - otherwise, the locale that matches the URL in the
i18noption, or itsdefaultLocale - without
i18n, your shop's default market, fetched once with the storefront client
If the locale has no currency, the module fetches it once per locale.
Shopify's scripts read the locale when the page loads.
To switch locales, use a full page load, for example with navigateTo(path, { external: true }).
Until then, events use the locale of the last full page load.
Cart events
Shopify creates the cart events cart_updated, product_added_to_cart and product_removed_from_cart from Hydrogen's cart.
With the cart from @shopify/hydrogen/vue, call useCartAnalytics() once inside CartProvider, for example in your layout:
<script setup lang="ts">
import { useCartAnalytics } from '@shopify/hydrogen/vue'
useCartAnalytics()
</script>
Call it on server-rendered pages, because on pages that are only rendered in the browser, Shopify's scripts load too late. Shopify only receives the cart events while analytics is enabled. Don't publish the cart events yourself, or they are counted twice.
Forwarding to other tools
To send events to other tools, such as GA4 or Meta, add them as destinations of Shopify's analytics bus once Shopify's scripts are running. Events are only sent to them if the visitor's consent allows it, including the events that were published before:
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('shopify:analytics:ready', () => {
useShopifyAnalytics()?.addDestination({
name: 'ga4',
setup: ({ subscribe }) => subscribe('product_added_to_cart', ({ currentLine }) => {
gtag('event', 'add_to_cart', { /* map from currentLine */ })
}),
})
})
})
addDestination returns a function that removes the destination.
Keep your destinations for the lifetime of the page, because a destination that is added again receives the earlier events again.
Consent
Events are only sent if Shopify's Customer Privacy API allows it. In regions that require opt-in, such as the EU, no events are sent and no tracking cookies are set until the visitor gives consent. In other regions, Shopify may allow tracking by default.
export default defineNuxtConfig({
shopify: {
analytics: {
consent: {
mode: 'default-banner',
},
},
},
})
no-banner (default) only loads the Customer Privacy API, without a banner. default-banner loads Shopify's own
privacy banner. custom-banner holds all events until the visitor's choice is known, either from an earlier visit or
from your own banner or consent provider.Recording consent
With your own banner or consent provider, record the visitor's choice with Shopify's Customer Privacy API:
await window.Shopify?.customerPrivacy?.setTrackingConsent({
analytics: true,
marketing: true,
preferences: true,
sale_of_data: true,
})
The API is available after the consentTrackingApiLoaded event on document.
shouldShowBanner() tells you whether the visitor still has to make a choice, and analyticsProcessingAllowed() whether analytics is allowed.
After each recorded choice, Shopify dispatches a visitorConsentCollected event.
With custom-banner, events are sent as soon as the page loads if Shopify has already stored a choice for the visitor.
Otherwise, they are sent after the first choice that is recorded on the page.
So record the choice of your consent provider on every page load, also for visitors in regions that don't require consent.
Reopening preferences
Once a visitor has made a choice, Shopify's banner disappears.
To reopen the consent dialog on demand, call showPreferences() on Shopify's privacy banner:
<script setup lang="ts">
const showPreferences = () => window.privacyBanner?.showPreferences()
</script>
<template>
<button @click="showPreferences">
Cookie Preferences
</button>
</template>
This only works with mode: 'default-banner', and window.privacyBanner is only available after its script has loaded.
Shopify only shows the banner in regions where consent is required.
When using your own banner, you have to handle the state yourself.