Analytics. Providercomponent
Provides a context for tracking page views and cart events to send as analytics data to Shopify. This component is integrated with the Customer Privacy API for consent management. The provider can also be used to connect third-party analytics services through its subscribe and publish system. The hook provides access to the analytics provider context.
You can also listen to a document
event for . It will be emitted when the Customer Privacy API is loaded.
Anchor to propsProps
- Anchor to cartcartPromise< | null> | | nullrequired
The cart or cart promise to track for cart analytics. When there is a difference between the state of the cart,
will trigger a
event. It will also produce
and
based on cart line quantity and cart line id changes.
- Anchor to consentconsentrequired
The customer privacy consent configuration and options.
- Anchor to shopshopPromise< | null> | | nullrequired
- Anchor to canTrackcanTrack() => boolean
An optional function to set wether the user can be tracked. Defaults to Customer Privacy API's
.
- Anchor to childrenchildrenReactNode
React children to render.
- string
The domain scope of the cookie set with
. *
- Anchor to customDatacustomDataRecord<string, unknown>
An optional custom payload to pass to all events. e.g language/locale/currency.
- Anchor to disableThrowOnErrordisableThrowOnErrorboolean
- Deprecated
Disable throwing errors when required props are missing.
AnalyticsProviderProps
- canTrack
An optional function to set wether the user can be tracked. Defaults to Customer Privacy API's `window.Shopify.customerPrivacy.analyticsProcessingAllowed()`.
() => boolean
- cart
The cart or cart promise to track for cart analytics. When there is a difference between the state of the cart, `AnalyticsProvider` will trigger a `cart_updated` event. It will also produce `product_added_to_cart` and `product_removed_from_cart` based on cart line quantity and cart line id changes.
Promise<CartReturn | null> | CartReturn | null
- children
React children to render.
ReactNode
- consent
The customer privacy consent configuration and options.
Consent
- cookieDomain
The domain scope of the cookie set with `useShopifyCookies`. *
string
- customData
An optional custom payload to pass to all events. e.g language/locale/currency.
Record<string, unknown>
- disableThrowOnError
boolean
- shop
The shop configuration required to publish analytics events to Shopify. Use [`getShopAnalytics`](/docs/api/hydrogen/utilities/getshopanalytics).
Promise<ShopAnalytics | null> | ShopAnalytics | null
{
/** React children to render. */
children?: ReactNode;
/** The cart or cart promise to track for cart analytics. When there is a difference between the state of the cart, `AnalyticsProvider` will trigger a `cart_updated` event. It will also produce `product_added_to_cart` and `product_removed_from_cart` based on cart line quantity and cart line id changes. */
cart: Promise<CartReturn | null> | CartReturn | null;
/** An optional function to set wether the user can be tracked. Defaults to Customer Privacy API's `window.Shopify.customerPrivacy.analyticsProcessingAllowed()`. */
canTrack?: () => boolean;
/** An optional custom payload to pass to all events. e.g language/locale/currency. */
customData?: Record<string, unknown>;
/** The shop configuration required to publish analytics events to Shopify. Use [`getShopAnalytics`](/docs/api/hydrogen/utilities/getshopanalytics). */
shop: Promise<ShopAnalytics | null> | ShopAnalytics | null;
/** The customer privacy consent configuration and options. */
consent: Consent;
/** @deprecated Disable throwing errors when required props are missing. */
disableThrowOnError?: boolean;
/** The domain scope of the cookie set with `useShopifyCookies`. **/
cookieDomain?: string;
}
CartReturn
Cart & {
errors?: StorefrontApiErrors;
}
Cart
Cart
StorefrontApiErrors
JsonGraphQLError[] | undefined
JsonGraphQLError
ReturnType<GraphQLError['toJSON']>
Consent
Partial<
Pick<
CustomerPrivacyApiProps,
'checkoutDomain' | 'storefrontAccessToken' | 'withPrivacyBanner' | 'country'
>
> & {language?: LanguageCode}
CustomerPrivacyApiProps
- checkoutDomain
The production shop checkout domain url.
string
- country
Country code for the shop.
CountryCode
- locale
Language code for the shop.
LanguageCode
- onReady
Callback to be call when customer privacy api is ready.
() => void
- onVisitorConsentCollected
Callback to be called when visitor consent is collected.
(consent: VisitorConsentCollected) => void
- storefrontAccessToken
The storefront access token for the shop.
string
- withPrivacyBanner
Whether to load the Shopify privacy banner as configured in Shopify admin. Defaults to true.
boolean
{
/** The production shop checkout domain url. */
checkoutDomain: string;
/** The storefront access token for the shop. */
storefrontAccessToken: string;
/** Whether to load the Shopify privacy banner as configured in Shopify admin. Defaults to true. */
withPrivacyBanner?: boolean;
/** Country code for the shop. */
country?: CountryCode;
/** Language code for the shop. */
locale?: LanguageCode;
/** Callback to be called when visitor consent is collected. */
onVisitorConsentCollected?: (consent: VisitorConsentCollected) => void;
/** Callback to be call when customer privacy api is ready. */
onReady?: () => void;
}
VisitorConsentCollected
- analyticsAllowed
boolean
- firstPartyMarketingAllowed
boolean
- marketingAllowed
boolean
- preferencesAllowed
boolean
- saleOfDataAllowed
boolean
- thirdPartyMarketingAllowed
boolean
{
analyticsAllowed: boolean;
firstPartyMarketingAllowed: boolean;
marketingAllowed: boolean;
preferencesAllowed: boolean;
saleOfDataAllowed: boolean;
thirdPartyMarketingAllowed: boolean;
}
PrivacyBanner
- loadBanner
(options?: Partial<CustomerPrivacyConsentConfig>) => void
- showPreferences
(options?: Partial<CustomerPrivacyConsentConfig>) => void
{
/* Display the privacy banner */
loadBanner: (options?: Partial<CustomerPrivacyConsentConfig>) => void;
/* Display the consent preferences banner */
showPreferences: (options?: Partial<CustomerPrivacyConsentConfig>) => void;
}
CustomerPrivacyConsentConfig
- checkoutRootDomain
string
- country
CountryCode
- locale
The privacyBanner refers to `language` as `locale`
LanguageCode
- storefrontAccessToken
string
- storefrontRootDomain
string
{
checkoutRootDomain: string;
storefrontRootDomain?: string;
storefrontAccessToken: string;
country?: CountryCode;
/** The privacyBanner refers to `language` as `locale` */
locale?: LanguageCode;
}
ShopAnalytics
- acceptedLanguage
The language code that is being displayed to user.
LanguageCode
- currency
The currency code that is being displayed to user.
CurrencyCode
- hydrogenSubchannelId
The Hydrogen subchannel ID generated by Oxygen in the environment variable.
string | '0'
- shopId
The shop ID.
string
{
/** The shop ID. */
shopId: string;
/** The language code that is being displayed to user. */
acceptedLanguage: LanguageCode;
/** The currency code that is being displayed to user. */
currency: CurrencyCode;
/** The Hydrogen subchannel ID generated by Oxygen in the environment variable. */
hydrogenSubchannelId: string | '0';
}
Example
examples
example
description
This is the default example
JavaScript
import {Analytics, getShopAnalytics} from '@shopify/hydrogen'; import {Outlet, useLoaderData} from 'react-router'; export async function loader({context}) { const {cart, env} = context; const cartPromise = cart.get(); return { cart: cartPromise, shop: getShopAnalytics(context), consent: { checkoutDomain: env.PUBLIC_CHECKOUT_DOMAIN, storefrontAccessToken: env.PUBLIC_STOREFRONT_API_TOKEN, withPrivacyBanner: true, // false stops the privacy banner from being displayed // localize the privacy banner country: context.storefront.i18n.country, language: context.storefront.i18n.language, }, }; } export default function App() { const data = useLoaderData(); return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> </head> <body> <Analytics.Provider cart={data.cart} shop={data.shop} consent={data.consent} > <Outlet /> </Analytics.Provider> </body> </html> ); }
TypeScript
import {Analytics, getShopAnalytics} from '@shopify/hydrogen'; import {type LoaderFunctionArgs} from '@shopify/remix-oxygen'; import {Outlet, useLoaderData} from 'react-router'; export async function loader({context}: LoaderFunctionArgs) { const {cart, env} = context; const cartPromise = cart.get(); return { cart: cartPromise, shop: getShopAnalytics({ storefront: context.storefront, publicStorefrontId: env.PUBLIC_STOREFRONT_ID, }), consent: { checkoutDomain: env.PUBLIC_CHECKOUT_DOMAIN, storefrontAccessToken: env.PUBLIC_STOREFRONT_API_TOKEN, withPrivacyBanner: true, // false stops the privacy banner from being displayed // localize the privacy banner country: context.storefront.i18n.country, language: context.storefront.i18n.language, }, }; } export default function App() { const data = useLoaderData<typeof loader>(); return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> </head> <body> <Analytics.Provider cart={data.cart} shop={data.shop} consent={data.consent} > <Outlet /> </Analytics.Provider> </body> </html> ); }