send Shopify Analyticsutility
Sends analytics to Shopify.
If is false, no analytics event will happen.
- Anchor to eventeventrequired
The analytics event.
- Anchor to shopDomainshopDomainstring
The Online Store domain to sent Shopify analytics under the same top level domain.
SendShopifyAnalyticsGeneratedType
- event
The analytics event.
ShopifyAnalytics
- shopDomain
The Online Store domain to sent Shopify analytics under the same top level domain.
string
Promise<void>
export function sendShopifyAnalytics(
event: ShopifyAnalytics,
shopDomain?: string,
): Promise<void> {
const {eventName, payload} = event;
if (!payload.hasUserConsent) return Promise.resolve();
let events: ShopifyMonorailEvent[] = [];
if (eventName === AnalyticsEventName.PAGE_VIEW) {
const pageViewPayload = payload as ShopifyPageViewPayload;
events = events.concat(
trekkiePageView(pageViewPayload),
customerPageView(pageViewPayload),
);
} else if (eventName === AnalyticsEventName.ADD_TO_CART) {
events = events.concat(
customerAddToCart(payload as ShopifyAddToCartPayload),
);
}
if (events.length) {
return sendToShopify(events, shopDomain);
} else {
return Promise.resolve();
}
}
ShopifyAnalytics
ShopifyPageView | ShopifyAddToCart
ShopifyPageView
- eventName
Use `AnalyticsEventName.PAGE_VIEW` constant.
string
- payload
ShopifyPageViewPayload
{
/** Use `AnalyticsEventName.PAGE_VIEW` constant. */
eventName: string;
payload: ShopifyPageViewPayload;
}
ShopifyPageViewPayload
- canonicalUrl
Canonical url.
string
- pageType
Shopify page type.
string
- resourceId
Shopify resource id in the form of `gid://shopify/<type>/<id>`.
string
- collectionHandle
Shopify collection handle.
string
- searchString
Search term used on a search results page.
string
- hasUserConsent
If we have consent from buyer for data collection
boolean
- shopId
Shopify shop id in the form of `gid://shopify/Shop/<id>`.
string
- currency
Currency code.
CurrencyCode
- storefrontId
Shopify storefront id generated by Hydrogen sales channel.
string
- acceptedLanguage
Language displayed to buyer.
LanguageCode
- shopifySalesChannel
Shopify sales channel.
keyof ShopifySalesChannel
- customerId
Shopify customer id in the form of `gid://shopify/Customer/<id>`.
string
- totalValue
Total value of products.
number
- products
Product list.
ShopifyAnalyticsProduct[]
- uniqueToken
Shopify unique user token: Value of `_shopify_y` cookie. Use `getClientBrowserParameters()` to collect this value.
string
- visitToken
Shopify session token: Value of `_shopify_s` cookie. Use `getClientBrowserParameters()` to collect this value.
string
- url
Value of `window.location.href`. Use `getClientBrowserParameters()` to collect this value.
string
- path
Value of `window.location.pathname`. Use `getClientBrowserParameters()` to collect this value.
string
- search
Value of `window.location.search`. Use `getClientBrowserParameters()` to collect this value.
string
- referrer
Value of `window.location.referrer`. Use `getClientBrowserParameters()` to collect this value.
string
- title
Value of `document.title`. Use `getClientBrowserParameters()` to collect this value.
string
- userAgent
Value of `navigator.userAgent`. Use `getClientBrowserParameters()` to collect this value.
string
- navigationType
Navigation type: `'navigate' | 'reload' | 'back_forward' | 'prerender' | 'unknown'`. Use `getClientBrowserParameters()` to collect this value.
string
- navigationApi
Navigation api: `'PerformanceNavigationTiming' | 'performance.navigation'`. Use `getClientBrowserParameters()` to collect this value.
string
export interface ShopifyPageViewPayload
extends ShopifyAnalyticsBase,
ClientBrowserParameters {
/** Canonical url. */
canonicalUrl?: string;
/** Shopify page type. */
pageType?: string;
/** Shopify resource id in the form of `gid://shopify/<type>/<id>`. */
resourceId?: string;
/** Shopify collection handle. */
collectionHandle?: string;
/** Search term used on a search results page. */
searchString?: string;
}
ShopifySalesChannel
- hydrogen
Shopify Hydrogen sales channel
"hydrogen"
- headless
Shopify Headless sales channel
"headless"
interface ShopifySalesChannel {
/** Shopify Hydrogen sales channel */
hydrogen: 'hydrogen';
/** Shopify Headless sales channel */
headless: 'headless';
}
ShopifyAnalyticsProduct
- productGid
Product id in the form of `gid://shopify/Product/<id>`.
string
- variantGid
Variant id in the form of `gid://shopify/ProductVariant/<id>`.
string
- name
Product name.
string
- variantName
Variant name.
string
- brand
Product brand or vendor.
string
- category
Product category or type.
string
- price
Product price.
string
- sku
Product sku.
string
- quantity
Quantity of the product in this event.
number
{
/** Product id in the form of `gid://shopify/Product/<id>`. */
productGid: Product['id'];
/** Variant id in the form of `gid://shopify/ProductVariant/<id>`. */
variantGid?: ProductVariant['id'];
/** Product name. */
name: Product['title'];
/** Variant name. */
variantName?: ProductVariant['title'];
/** Product brand or vendor. */
brand: Product['vendor'];
/** Product category or type. */
category?: Product['productType'];
/** Product price. */
price: ProductVariant['price']['amount'];
/** Product sku. */
sku?: ProductVariant['sku'];
/** Quantity of the product in this event. */
quantity?: number;
}
ShopifyAddToCart
- eventName
Use `AnalyticsEventName.ADD_TO_CART` constant.
string
- payload
ShopifyAddToCartPayload
{
/** Use `AnalyticsEventName.ADD_TO_CART` constant. */
eventName: string;
payload: ShopifyAddToCartPayload;
}
ShopifyAddToCartPayload
- cartId
Shopify cart id in the form of `gid://shopify/Cart/<id>`.
string
- hasUserConsent
If we have consent from buyer for data collection
boolean
- shopId
Shopify shop id in the form of `gid://shopify/Shop/<id>`.
string
- currency
Currency code.
CurrencyCode
- storefrontId
Shopify storefront id generated by Hydrogen sales channel.
string
- acceptedLanguage
Language displayed to buyer.
LanguageCode
- shopifySalesChannel
Shopify sales channel.
keyof ShopifySalesChannel
- customerId
Shopify customer id in the form of `gid://shopify/Customer/<id>`.
string
- totalValue
Total value of products.
number
- products
Product list.
ShopifyAnalyticsProduct[]
- uniqueToken
Shopify unique user token: Value of `_shopify_y` cookie. Use `getClientBrowserParameters()` to collect this value.
string
- visitToken
Shopify session token: Value of `_shopify_s` cookie. Use `getClientBrowserParameters()` to collect this value.
string
- url
Value of `window.location.href`. Use `getClientBrowserParameters()` to collect this value.
string
- path
Value of `window.location.pathname`. Use `getClientBrowserParameters()` to collect this value.
string
- search
Value of `window.location.search`. Use `getClientBrowserParameters()` to collect this value.
string
- referrer
Value of `window.location.referrer`. Use `getClientBrowserParameters()` to collect this value.
string
- title
Value of `document.title`. Use `getClientBrowserParameters()` to collect this value.
string
- userAgent
Value of `navigator.userAgent`. Use `getClientBrowserParameters()` to collect this value.
string
- navigationType
Navigation type: `'navigate' | 'reload' | 'back_forward' | 'prerender' | 'unknown'`. Use `getClientBrowserParameters()` to collect this value.
string
- navigationApi
Navigation api: `'PerformanceNavigationTiming' | 'performance.navigation'`. Use `getClientBrowserParameters()` to collect this value.
string
export interface ShopifyAddToCartPayload
extends ShopifyAnalyticsBase,
ClientBrowserParameters {
/** Shopify cart id in the form of `gid://shopify/Cart/<id>`. */
cartId: string;
}
Anchor to analyticseventnameAnalyticsEventName
Analytics event names accepted by Shopify analytics.
- Anchor to PAGE_VIEWPAGE_VIEW"PAGE_VIEW"required
Page view
- Anchor to ADD_TO_CARTADD_TO_CART"ADD_TO_CART"required
Add to cart
AnalyticsEventName
These duplicated interface declaration is so that we can generate proper documentation for these public facing constants
- PAGE_VIEW
Page view
"PAGE_VIEW"
- ADD_TO_CART
Add to cart
"ADD_TO_CART"
interface AnalyticsEventName {
/** Page view */
PAGE_VIEW: 'PAGE_VIEW';
/** Add to cart */
ADD_TO_CART: 'ADD_TO_CART';
}
Anchor to analyticspagetypeAnalyticsPageType
Analytics page type values accepted by Shopify analytics.
- Anchor to articlearticle"article"required
- Anchor to blogblog"blog"required
- Anchor to captchacaptcha"captcha"required
- Anchor to cartcart"cart"required
- Anchor to collectioncollection"collection"required
- Anchor to customersAccountcustomersAccount"customers/account"required
- Anchor to customersActivateAccountcustomersActivateAccount"customers/activate_account"required
- Anchor to customersAddressescustomersAddresses"customers/addresses"required
- Anchor to customersLogincustomersLogin"customers/login"required
- Anchor to customersOrdercustomersOrder"customers/order"required
- Anchor to customersRegistercustomersRegister"customers/register"required
- Anchor to customersResetPasswordcustomersResetPassword"customers/reset_password"required
- Anchor to giftCardgiftCard"gift_card"required
- Anchor to homehome"index"required
- Anchor to listCollectionslistCollections"list-collections"required
- Anchor to forbiddenforbidden"403"required
- Anchor to notFoundnotFound"404"required
- Anchor to pagepage"page"required
- Anchor to passwordpassword"password"required
- Anchor to productproduct"product"required
- Anchor to policypolicy"policy"required
- Anchor to searchsearch"search"required
AnalyticsPageType
- article
"article"
- blog
"blog"
- captcha
"captcha"
- cart
"cart"
- collection
"collection"
- customersAccount
"customers/account"
- customersActivateAccount
"customers/activate_account"
- customersAddresses
"customers/addresses"
- customersLogin
"customers/login"
- customersOrder
"customers/order"
- customersRegister
"customers/register"
- customersResetPassword
"customers/reset_password"
- giftCard
"gift_card"
- home
"index"
- listCollections
"list-collections"
- forbidden
"403"
- notFound
"404"
- page
"page"
- password
"password"
- product
"product"
- policy
"policy"
- search
"search"
interface AnalyticsPageType {
article: 'article';
blog: 'blog';
captcha: 'captcha';
cart: 'cart';
collection: 'collection';
customersAccount: 'customers/account';
customersActivateAccount: 'customers/activate_account';
customersAddresses: 'customers/addresses';
customersLogin: 'customers/login';
customersOrder: 'customers/order';
customersRegister: 'customers/register';
customersResetPassword: 'customers/reset_password';
giftCard: 'gift_card';
home: 'index';
listCollections: 'list-collections';
forbidden: '403';
notFound: '404';
page: 'page';
password: 'password';
product: 'product';
policy: 'policy';
search: 'search';
}
Anchor to shopifysaleschannelShopifySalesChannel
Analytics sales channel values accepted by Shopify analytics.
- Anchor to hydrogenhydrogen"hydrogen"required
Shopify Hydrogen sales channel
- Anchor to headlessheadless"headless"required
Shopify Headless sales channel
ShopifySalesChannel
- hydrogen
Shopify Hydrogen sales channel
"hydrogen"
- headless
Shopify Headless sales channel
"headless"
interface ShopifySalesChannel {
/** Shopify Hydrogen sales channel */
hydrogen: 'hydrogen';
/** Shopify Headless sales channel */
headless: 'headless';
}
Example code
examples
Example code
description
I am the default example
JavaScript
import { sendShopifyAnalytics, getClientBrowserParameters, AnalyticsEventName, useShopifyCookies, } from '@shopify/hydrogen-react'; import {useRouter} from 'next/router'; import {useEffect} from 'react'; function sendPageView(analyticsPageData) { const payload = { ...getClientBrowserParameters(), ...analyticsPageData, }; sendShopifyAnalytics({ eventName: AnalyticsEventName.PAGE_VIEW, payload, }); } // Hook into your router's page change events to fire this analytics event: // for example, in NextJS: const analyticsShopData = { shopId: 'gid://shopify/Shop/{your-shop-id}', currency: 'USD', acceptedLanguage: 'en', }; export default function App({Component, pageProps}) { const router = useRouter(); // eslint-disable-next-line no-undef const hasUserConsent = yourFunctionToDetermineIfUserHasConsent(); // eslint-disable-next-line react-hooks/exhaustive-deps const analytics = { hasUserConsent, ...analyticsShopData, ...pageProps.analytics, }; const pagePropsWithAppAnalytics = { ...pageProps, analytics, }; useEffect(() => { const handleRouteChange = () => { sendPageView(analytics); }; router.events.on('routeChangeComplete', handleRouteChange); return () => { router.events.off('routeChangeComplete', handleRouteChange); }; }, [analytics, router.events]); useShopifyCookies(); return <Component {...pagePropsWithAppAnalytics} />; }
TypeScript
import * as React from 'react'; import {useEffect} from 'react'; import { sendShopifyAnalytics, getClientBrowserParameters, AnalyticsEventName, useShopifyCookies, } from '@shopify/hydrogen-react'; import {useRouter} from 'next/router'; function sendPageView(analyticsPageData) { const payload = { ...getClientBrowserParameters(), ...analyticsPageData, }; sendShopifyAnalytics({ eventName: AnalyticsEventName.PAGE_VIEW, payload, }); } // Hook into your router's page change events to fire this analytics event: // for example, in NextJS: const analyticsShopData = { shopId: 'gid://shopify/Shop/{your-shop-id}', currency: 'USD', acceptedLanguage: 'en', }; export default function App({Component, pageProps}) { const router = useRouter(); // @ts-expect-error - this is an example, you should implement this function const hasUserConsent = yourFunctionToDetermineIfUserHasConsent(); // eslint-disable-next-line react-hooks/exhaustive-deps const analytics = { hasUserConsent, ...analyticsShopData, ...pageProps.analytics, }; const pagePropsWithAppAnalytics = { ...pageProps, analytics, }; useEffect(() => { const handleRouteChange = () => { sendPageView(analytics); }; router.events.on('routeChangeComplete', handleRouteChange); return () => { router.events.off('routeChangeComplete', handleRouteChange); }; }, [analytics, router.events]); useShopifyCookies(); return <Component {...pagePropsWithAppAnalytics} />; }