use Analyticshook
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 |
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 |
The previous cart state. You can overwrite the type by passing a generic
- Anchor to publishpublish
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
ready
function. See example register usage.- Anchor to shopshopPromise< | null> | | null
The shop configuration required to publish events to Shopify.
- Anchor to subscribesubscribe
A function to subscribe to analytics events.
AnalyticsContextValueForDoc
- canTrack
A function to tell you the current state of if the user can be tracked by analytics. Defaults to Customer Privacy API's `window.Shopify.customerPrivacy.analyticsProcessingAllowed()`.
() => boolean
- cart
The current cart state. You can overwrite the type by passing a generic
UserCart | DefaultCart
- customData
The custom data passed in from the `AnalyticsProvider`.
Record<string, unknown>
- prevCart
The previous cart state. You can overwrite the type by passing a generic
UserCart | DefaultCart
- publish
A function to publish an analytics event.
AnalyticsContextPublishForDoc
- register
A function to register with the analytics provider. It holds the first browser load events until all registered key has executed the supplied `ready` function. [See example register usage](/docs/api/hydrogen/hooks/useanalytics#example-useanalytics.register).
(key: string) => { ready: () => void; }
- shop
The shop configuration required to publish events to Shopify.
Promise<ShopAnalytics | null> | ShopAnalytics | null
- subscribe
A function to subscribe to analytics events.
AnalyticsContextSubscribeForDoc
{
/** A function to tell you the current state of if the user can be tracked by analytics. Defaults to Customer Privacy API's `window.Shopify.customerPrivacy.analyticsProcessingAllowed()`. */
canTrack?: () => boolean;
/** The current cart state. You can overwrite the type by passing a generic */
cart?: UserCart | DefaultCart;
/** The custom data passed in from the `AnalyticsProvider`. */
customData?: Record<string, unknown>;
/** The previous cart state. You can overwrite the type by passing a generic */
prevCart?: UserCart | DefaultCart;
/** A function to publish an analytics event. */
publish?: AnalyticsContextPublishForDoc;
/** A function to register with the analytics provider. It holds the first browser load events until all registered key has executed the supplied `ready` function. [See example register usage](/docs/api/hydrogen/hooks/useanalytics#example-useanalytics.register). */
register?: (key: string) => {ready: () => void};
/** The shop configuration required to publish events to Shopify. */
shop?: Promise<ShopAnalytics | null> | ShopAnalytics | null;
/** A function to subscribe to analytics events. */
subscribe?: AnalyticsContextSubscribeForDoc;
}
DefaultCart
Promise<CartReturn | null> | CartReturn | null
CartReturn
Cart & {
errors?: StorefrontApiErrors;
}
Cart
Cart
StorefrontApiErrors
JsonGraphQLError[] | undefined
JsonGraphQLError
ReturnType<GraphQLError['toJSON']>
AnalyticsContextPublishForDoc
PublishPageView | PublishProductView | PublishCollectionView | PublishCartView | PublishSearchView | PublishCartUpdated | PublishProductAddedToCart | PublishProductRemovedFromCart | PublishCustomEvent
PublishPageView
- event
"page_viewed"
- payload
PageViewPayload
void
type PublishPageView = (event: 'page_viewed', payload: PageViewPayload) => void;
PageViewPayload
UrlPayload & BasePayload
UrlPayload
- 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
void
type PublishProductView = (
event: 'product_viewed',
payload: ProductViewPayload,
) => void;
ProductViewPayload
ProductsPayload & UrlPayload & BasePayload
ProductsPayload
- 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
OtherData
PublishCollectionView
- event
"collection_viewed"
- payload
CollectionViewPayload
void
type PublishCollectionView = (
event: 'collection_viewed',
payload: CollectionViewPayload,
) => void;
CollectionViewPayload
CollectionPayload & UrlPayload & BasePayload
CollectionPayload
- 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
void
type PublishCartView = (event: 'cart_viewed', payload: CartViewPayload) => void;
CartViewPayload
CartPayload & UrlPayload & BasePayload
CartPayload
- 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
void
type PublishSearchView = (
event: 'search_viewed',
payload: SearchViewPayload,
) => void;
SearchViewPayload
SearchPayload & UrlPayload & BasePayload
SearchPayload
- 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
void
type PublishCartUpdated = (
event: 'cart_updated',
payload: CartUpdatePayload,
) => void;
CartUpdatePayload
CartPayload & BasePayload & OtherData
PublishProductAddedToCart
- event
"product_added_to_cart"
- payload
CartLineUpdatePayload
void
type PublishProductAddedToCart = (
event: 'product_added_to_cart',
payload: CartLineUpdatePayload,
) => void;
CartLineUpdatePayload
CartLinePayload & CartPayload & BasePayload & OtherData
CartLinePayload
- 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
void
type PublishProductRemovedFromCart = (
event: 'product_removed_from_cart',
payload: CartLineUpdatePayload,
) => void;
PublishCustomEvent
- event
`custom_${string}`
- payload
OtherData
void
type PublishCustomEvent = (
event: `custom_${string}`,
payload: OtherData,
) => void;
AnalyticsContextSubscribeForDoc
SubscribePageView | SubscribeProductView | SubscribeCollectionView | SubscribeCartView | SubscribeSearchView | SubscribeCartUpdated | SubscribeProductAddedToCart | SubscribeProductRemovedFromCart | SubscribeCustomEvent
SubscribePageView
- event
"page_viewed"
- callback
(payload: PageViewPayload) => void
void
type SubscribePageView = (
event: 'page_viewed',
callback: (payload: PageViewPayload) => void,
) => void;
SubscribeProductView
- event
"product_viewed"
- callback
(payload: ProductViewPayload) => void
void
type SubscribeProductView = (
event: 'product_viewed',
callback: (payload: ProductViewPayload) => void,
) => void;
SubscribeCollectionView
- event
"collection_viewed"
- callback
(payload: CollectionViewPayload) => void
void
type SubscribeCollectionView = (
event: 'collection_viewed',
callback: (payload: CollectionViewPayload) => void,
) => void;
SubscribeCartView
- event
"cart_viewed"
- callback
(payload: CartViewPayload) => void
void
type SubscribeCartView = (
event: 'cart_viewed',
callback: (payload: CartViewPayload) => void,
) => void;
SubscribeSearchView
- event
"search_viewed"
- callback
(payload: SearchViewPayload) => void
void
type SubscribeSearchView = (
event: 'search_viewed',
callback: (payload: SearchViewPayload) => void,
) => void;
SubscribeCartUpdated
- event
"cart_updated"
- callback
(payload: CartUpdatePayload) => void
void
type SubscribeCartUpdated = (
event: 'cart_updated',
callback: (payload: CartUpdatePayload) => void,
) => void;
SubscribeProductAddedToCart
- event
"product_added_to_cart"
- callback
(payload: CartLineUpdatePayload) => void
void
type SubscribeProductAddedToCart = (
event: 'product_added_to_cart',
callback: (payload: CartLineUpdatePayload) => void,
) => void;
SubscribeProductRemovedFromCart
- event
"product_removed_from_cart"
- callback
(payload: CartLineUpdatePayload) => void
void
type SubscribeProductRemovedFromCart = (
event: 'product_removed_from_cart',
callback: (payload: CartLineUpdatePayload) => void,
) => void;
SubscribeCustomEvent
- event
`custom_${string}`
- callback
(payload: OtherData) => void
void
type 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; }