use Analytics
A hook that provides access to the analytics provider context. Must be a descendent of Analytics.Provider.
Anchor to returnsReturns
- Anchor to canTrackcanTrack() => boolean
A function to tell you the current state of if the user can be tracked by analytics. Defaults to Customer Privacy API's
.- Anchor to cartcartUserCart | DefaultCart
The current cart state. You can overwrite the type by passing a generic
- Anchor to customDatacustomDataRecord<string, unknown>
The custom data passed in from the
.- Anchor to prevCartprevCartUserCart | DefaultCart
The previous cart state. You can overwrite the type by passing a generic
- Anchor to publishpublishAnalyticsContextPublishForDoc
A function to publish an analytics event.
- Anchor to registerregister(key: string) => { ready: () => void; }
A function to register with the analytics provider. It holds the first browser load events until all registered key has executed the supplied
readyfunction. See example register usage.- Anchor to shopshopPromise<ShopAnalytics | null> | ShopAnalytics | null
The shop configuration required to publish events to Shopify.
- Anchor to subscribesubscribeAnalyticsContextSubscribeForDoc
A function to subscribe to analytics events.
DefaultCart
Promise<CartReturn | null> | CartReturn | nullCartReturn
Cart & {
errors?: StorefrontApiErrors;
}Cart
CartStorefrontApiErrors
JsonGraphQLError[] | undefinedJsonGraphQLError
ReturnType<GraphQLError['toJSON']>AnalyticsContextPublishForDoc
PublishPageView | PublishProductView | PublishCollectionView | PublishCartView | PublishSearchView | PublishCartUpdated | PublishProductAddedToCart | PublishProductRemovedFromCart | PublishCustomEventPublishPageView
- event
"page_viewed" - payload
PageViewPayload
voidtype PublishPageView = (event: 'page_viewed', payload: PageViewPayload) => void;PageViewPayload
UrlPayload & BasePayloadUrlPayload
- url
The url location of when this event is collected.
string
{
/** The url location of when this event is collected. */
url: string;
}BasePayload
- customData
The custom data passed in from the `AnalyticsProvider`.
Record<string, unknown> - shop
The shop data passed in from the `AnalyticsProvider`.
ShopAnalytics | null
{
/** The shop data passed in from the `AnalyticsProvider`. */
shop: ShopAnalytics | null;
/** The custom data passed in from the `AnalyticsProvider`. */
customData?: AnalyticsProviderProps['customData'];
}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';
}PublishProductView
- event
"product_viewed" - payload
ProductViewPayload
voidtype PublishProductView = (
event: 'product_viewed',
payload: ProductViewPayload,
) => void;ProductViewPayload
ProductsPayload & UrlPayload & BasePayloadProductsPayload
- products
The products associated with this event.
Array<ProductPayload & OtherData>
{
/** The products associated with this event. */
products: Array<ProductPayload & OtherData>;
}ProductPayload
- id
The product id.
string - price
The displaying variant price.
string - productType
The product type.
string - quantity
The quantity of product.
number - sku
The product sku.
string - title
The product title.
string - variantId
The displaying variant id.
string - variantTitle
The displaying variant title.
string - vendor
The product vendor.
string
{
/** The product id. */
id: Product['id'];
/** The product title. */
title: Product['title'];
/** The displaying variant price. */
price: ProductVariant['price']['amount'];
/** The product vendor. */
vendor: Product['vendor'];
/** The displaying variant id. */
variantId: ProductVariant['id'];
/** The displaying variant title. */
variantTitle: ProductVariant['title'];
/** The quantity of product. */
quantity: number;
/** The product sku. */
sku?: ProductVariant['sku'];
/** The product type. */
productType?: Product['productType'];
}OtherData
OtherDataPublishCollectionView
- event
"collection_viewed" - payload
CollectionViewPayload
voidtype PublishCollectionView = (
event: 'collection_viewed',
payload: CollectionViewPayload,
) => void;CollectionViewPayload
CollectionPayload & UrlPayload & BasePayloadCollectionPayload
- collection
CollectionPayloadDetails
{
collection: CollectionPayloadDetails;
}CollectionPayloadDetails
- handle
The collection handle.
string - id
The collection id.
string
{
/** The collection id. */
id: string;
/** The collection handle. */
handle: string;
}PublishCartView
- event
"cart_viewed" - payload
CartViewPayload
voidtype PublishCartView = (event: 'cart_viewed', payload: CartViewPayload) => void;CartViewPayload
CartPayload & UrlPayload & BasePayloadCartPayload
- cart
The current cart state.
CartReturn | null - prevCart
The previous cart state.
CartReturn | null
{
/** The current cart state. */
cart: CartReturn | null;
/** The previous cart state. */
prevCart: CartReturn | null;
}PublishSearchView
- event
"search_viewed" - payload
SearchViewPayload
voidtype PublishSearchView = (
event: 'search_viewed',
payload: SearchViewPayload,
) => void;SearchViewPayload
SearchPayload & UrlPayload & BasePayloadSearchPayload
- searchResults
The search results
any - searchTerm
The search term used for the search results page
string
{
/** The search term used for the search results page */
searchTerm: string;
/** The search results */
searchResults?: any;
}PublishCartUpdated
- event
"cart_updated" - payload
CartUpdatePayload
voidtype PublishCartUpdated = (
event: 'cart_updated',
payload: CartUpdatePayload,
) => void;CartUpdatePayload
CartPayload & BasePayload & OtherDataPublishProductAddedToCart
- event
"product_added_to_cart" - payload
CartLineUpdatePayload
voidtype PublishProductAddedToCart = (
event: 'product_added_to_cart',
payload: CartLineUpdatePayload,
) => void;CartLineUpdatePayload
CartLinePayload & CartPayload & BasePayload & OtherDataCartLinePayload
- currentLine
The current state of the cart line that got updated.
CartLine | ComponentizableCartLine - prevLine
The previous state of the cart line that got updated.
CartLine | ComponentizableCartLine
{
/** The previous state of the cart line that got updated. */
prevLine?: CartLine | ComponentizableCartLine;
/** The current state of the cart line that got updated. */
currentLine?: CartLine | ComponentizableCartLine;
}PublishProductRemovedFromCart
- event
"product_removed_from_cart" - payload
CartLineUpdatePayload
voidtype PublishProductRemovedFromCart = (
event: 'product_removed_from_cart',
payload: CartLineUpdatePayload,
) => void;PublishCustomEvent
- event
`custom_${string}` - payload
OtherData
voidtype PublishCustomEvent = (
event: `custom_${string}`,
payload: OtherData,
) => void;AnalyticsContextSubscribeForDoc
SubscribePageView | SubscribeProductView | SubscribeCollectionView | SubscribeCartView | SubscribeSearchView | SubscribeCartUpdated | SubscribeProductAddedToCart | SubscribeProductRemovedFromCart | SubscribeCustomEventSubscribePageView
- event
"page_viewed" - callback
(payload: PageViewPayload) => void
voidtype SubscribePageView = (
event: 'page_viewed',
callback: (payload: PageViewPayload) => void,
) => void;SubscribeProductView
- event
"product_viewed" - callback
(payload: ProductViewPayload) => void
voidtype SubscribeProductView = (
event: 'product_viewed',
callback: (payload: ProductViewPayload) => void,
) => void;SubscribeCollectionView
- event
"collection_viewed" - callback
(payload: CollectionViewPayload) => void
voidtype SubscribeCollectionView = (
event: 'collection_viewed',
callback: (payload: CollectionViewPayload) => void,
) => void;SubscribeCartView
- event
"cart_viewed" - callback
(payload: CartViewPayload) => void
voidtype SubscribeCartView = (
event: 'cart_viewed',
callback: (payload: CartViewPayload) => void,
) => void;SubscribeSearchView
- event
"search_viewed" - callback
(payload: SearchViewPayload) => void
voidtype SubscribeSearchView = (
event: 'search_viewed',
callback: (payload: SearchViewPayload) => void,
) => void;SubscribeCartUpdated
- event
"cart_updated" - callback
(payload: CartUpdatePayload) => void
voidtype SubscribeCartUpdated = (
event: 'cart_updated',
callback: (payload: CartUpdatePayload) => void,
) => void;SubscribeProductAddedToCart
- event
"product_added_to_cart" - callback
(payload: CartLineUpdatePayload) => void
voidtype SubscribeProductAddedToCart = (
event: 'product_added_to_cart',
callback: (payload: CartLineUpdatePayload) => void,
) => void;SubscribeProductRemovedFromCart
- event
"product_removed_from_cart" - callback
(payload: CartLineUpdatePayload) => void
voidtype SubscribeProductRemovedFromCart = (
event: 'product_removed_from_cart',
callback: (payload: CartLineUpdatePayload) => void,
) => void;SubscribeCustomEvent
- event
`custom_${string}` - callback
(payload: OtherData) => void
voidtype SubscribeCustomEvent = (
event: `custom_${string}`,
callback: (payload: OtherData) => void,
) => void;Example
Examples
example
Description
This is the default example
JavaScript
import {useAnalytics} from '@shopify/hydrogen'; import {useEffect} from 'react'; export function CustomAnalytics() { const {subscribe, register} = useAnalytics(); const {ready} = register('CustomAnalytics'); // unique string identifier useEffect(() => { // Triggers on every page navigation subscribe('page_viewed', (data) => { console.log('CustomAnalytics - Page viewed:', data); }); // Triggers on a page that uses `<Analytics.ProductView>` subscribe('product_viewed', (data) => { console.log('CustomAnalytics - Product viewed:', data); }); // Triggers on a page that uses `<Analytics.CollectionView>` subscribe('collection_viewed', (data) => { console.log('CustomAnalytics - Collection viewed:', data); }); // Triggers on a page that uses `<Analytics.CartView>` subscribe('cart_viewed', (data) => { console.log('CustomAnalytics - Cart viewed:', data); }); // Triggers on a page that uses `<Analytics.SearchView>` subscribe('search_viewed', (data) => { console.log('CustomAnalytics - Search viewed:', data); }); // Triggers on a page that uses `<Analytics.CustomView type="custom_promotion_viewed">` subscribe('custom_promotion_viewed', (data) => { console.log('CustomAnalytics - Promotion viewed:', data); }); // Triggers when the cart is updated subscribe('cart_updated', (data) => { console.log('CustomAnalytics - Cart updated:', data); }); // Triggers when an existing cart line increases in quantity or a new cart line is added subscribe('product_added_to_cart', (data) => { console.log('CustomAnalytics - Product added to cart:', data); }); // Triggers when an existing cart line decreases in quantity or a cart line is removed subscribe('product_removed_from_cart', (data) => { console.log('CustomAnalytics - Product removed from cart:', data); }); // Register the CustomAnalytics component as ready ready(); }, []); return null; }TypeScript
import { type PageViewPayload, type ProductViewPayload, type CollectionViewPayload, type CartViewPayload, type CartUpdatePayload, type CartLineUpdatePayload, type SearchViewPayload, useAnalytics, } from '@shopify/hydrogen'; import {useEffect} from 'react'; export function CustomAnalytics() { const {subscribe, register} = useAnalytics(); const {ready} = register('CustomAnalytics'); // unique string identifier useEffect(() => { // Triggers on every page navigation subscribe('page_viewed', (data: PageViewPayload) => { console.log('CustomAnalytics - Page viewed:', data); }); // Triggers on a page that uses `<Analytics.ProductView>` subscribe('product_viewed', (data: ProductViewPayload) => { console.log('CustomAnalytics - Product viewed:', data); }); // Triggers on a page that uses `<Analytics.CollectionView>` subscribe('collection_viewed', (data: CollectionViewPayload) => { console.log('CustomAnalytics - Collection viewed:', data); }); // Triggers on a page that uses `<Analytics.CartView>` subscribe('cart_viewed', (data: CartViewPayload) => { console.log('CustomAnalytics - Cart viewed:', data); }); // Triggers on a page that uses `<Analytics.SearchView>` subscribe('search_viewed', (data: SearchViewPayload) => { console.log('CustomAnalytics - Search viewed:', data); }); // Triggers on a page that uses `<Analytics.CustomView type="custom_promotion_viewed">` subscribe('custom_promotion_viewed', (data: unknown) => { console.log('CustomAnalytics - Promotion viewed:', data); }); // Triggers when the cart is updated subscribe('cart_updated', (data: CartUpdatePayload) => { console.log('CustomAnalytics - Cart updated:', data); }); // Triggers when an existing cart line increases in quantity or a new cart line is added subscribe('product_added_to_cart', (data: CartLineUpdatePayload) => { console.log('CustomAnalytics - Product added to cart:', data); }); // Triggers when an existing cart line decreases in quantity or a cart line is removed subscribe('product_removed_from_cart', (data: CartLineUpdatePayload) => { console.log('CustomAnalytics - Product removed from cart:', data); }); // Register the CustomAnalytics component as ready ready(); }, []); return null; }
Anchor to examplesExamples
Example usage with :
Anchor to example-useanalyticsregisteruseAnalytics.register
Registers a unique key with the analytics provider component, enabling custom analytics integrations to wait for a callback before sending event data.
JavaScript
Examples
Description
Registers a unique key with the analytics provider component, enabling custom analytics integrations to wait for a callback before sending event data.
JavaScript
import { type PageViewPayload, useAnalytics, useLoadScript, } from '@shopify/hydrogen'; import {useEffect} from 'react'; export function MyAnalytics() { const {subscribe, register} = useAnalytics(); // Load the 3p analytics script const scriptStatus = useLoadScript( 'https://example.com/some-3p-analytics-script.js', ); // unique string identifier const {ready} = register('MyAnalytics'); useEffect(() => { // Make sure the 3p script is loaded if (scriptStatus !== 'done') return; // Initialize the 3p analytics script // Subscribe to analytics events subscribe('page_viewed', (data: PageViewPayload) => { // report to 3p analytics }); // Register the MyAnalytics component as ready ready(); }, []); return null; }