Last active
April 6, 2025 15:50
-
-
Save hatsumatsu/daf9043dad751b14a5e8b4124832909b to your computer and use it in GitHub Desktop.
ShopifyAnalytics.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
AnalyticsEventName, | |
AnalyticsPageType, | |
getClientBrowserParameters, | |
sendShopifyAnalytics, | |
ShopifySalesChannel, | |
useShopifyCookies, | |
} from '@shopify/hydrogen-react'; | |
import { useCallback, useEffect } from 'react'; | |
function useShopifyAnalytics() { | |
const idNumber = process.env.NEXT_PUBLIC_SHOPIFY_STORE_ID_NUMBER; | |
const checkoutDomain = process.env.NEXT_PUBLIC_SHOPIFY_CHECKOUT_DOMAIN; | |
const trackPageView = useCallback( | |
(payload = { pageType: AnalyticsPageType.home, resourceId: null, collectionHandle: null }) => { | |
if (!idNumber || !checkoutDomain) return; | |
console.info('ShopifyAnalytics.trackPageView()', payload); | |
sendShopifyAnalytics( | |
{ | |
eventName: AnalyticsEventName.PAGE_VIEW, | |
payload: { | |
...getClientBrowserParameters(), | |
shopId: `gid://shopify/Shop/${idNumber}`, | |
currency: 'USD', | |
hasUserConsent: true, | |
shopifySalesChannel: ShopifySalesChannel.headless, | |
acceptedLanguage: 'en', | |
...payload, | |
}, | |
}, | |
checkoutDomain | |
); | |
}, | |
[] | |
); | |
return { | |
trackPageView, | |
}; | |
} | |
/** | |
* Shopify Analyctis page tracking | |
* | |
* Example: | |
* useShopifyAnalyticsTrackPageView({ pageType: AnalyticsPageType.product, resourceId: product.id }); | |
* | |
* @param {object} payload | |
* @param {object.pageType} page type defined in AnalyticsPageType from @shopify/hydrogen-react | |
* @param {object.resourceId} resource id e.g. product or collection ID in the gid:// format. Mandatory when tracking products or collections | |
* @param {object.collectionHandle} collection handle. Only used when tracking collections | |
*/ | |
function useShopifyAnalyticsTrackPageView(payload) { | |
const { trackPageView } = useShopifyAnalytics(); | |
useEffect(() => { | |
if (payload?.pageType || payload?.resourceId) trackPageView(payload); | |
}, [payload?.pageType, payload?.resourceId, trackPageView]); | |
} | |
/** | |
* Place in global layout | |
* <ShopifyAnalytics /> | |
*/ | |
const ShopifyAnalytics = () => { | |
const frontendDomain = process.env.NEXT_PUBLIC_SHOPIFY_FRONTEND_DOMAIN; | |
useShopifyCookies({ | |
hasUserConsent: true, | |
domain: frontendDomain, | |
}); | |
return null; | |
}; | |
export { ShopifyAnalytics, useShopifyAnalytics, useShopifyAnalyticsTrackPageView }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment