Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix missing custom data from provider to page view events #2224

Merged
merged 9 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/strange-keys-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen': patch
---

Fix customData from Analytics.Provider not being passed to page view events
2 changes: 1 addition & 1 deletion examples/gtm/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Hydrogen example: Shopify Analytics & Consent (unstable)
# Hydrogen example: Google Tag Manager (GTM) with `<Analytics.Provider>`

This folder contains an end-to-end example of how to implement Google Tag Manager for Hydrogen. Hydrogen supports both Shopify analytics, as well as third-party services.

Expand Down
2 changes: 0 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/hydrogen/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@
"content-security-policy-builder": "^2.2.0",
"type-fest": "^4.5.0",
"source-map-support": "^0.5.21",
"tiny-invariant": "^1.3.1",
"use-resize-observer": "^9.1.0",
"worktop": "^0.7.3"
},
Expand Down
36 changes: 32 additions & 4 deletions packages/hydrogen/src/analytics-manager/AnalyticsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {ShopifyAnalytics} from './ShopifyAnalytics';
import {CartAnalytics} from './CartAnalytics';
import type {CustomerPrivacyApiProps} from '../customer-privacy/ShopifyCustomerPrivacy';
import type {Storefront} from '../storefront';
import {errorOnce, warnOnce} from '../utils/warning';

export type ShopAnalytics = {
/** The shop ID. */
Expand Down Expand Up @@ -67,7 +68,7 @@ export type AnalyticsProviderProps = {
'checkoutDomain' | 'storefrontAccessToken' | 'withPrivacyBanner'
>
>;
/** Disable throwing errors when required props are missing. */
/** @deprecated Disable throwing errors when required props are missing. */
disableThrowOnError?: boolean;
/** The domain scope of the cookie set with `useShopifyCookies`. **/
cookieDomain?: string;
Expand Down Expand Up @@ -265,6 +266,10 @@ function shopifyCanTrack(): boolean {
return false;
}

function messageOnError(field: string, envVar: string) {
return `[h2:error:Analytics.Provider] - ${field} is required. Make sure ${envVar} is defined in your environment variables. See https://h2o.fyi/analytics/consent to learn how to setup environment variables in the Shopify admin.`;
}

function AnalyticsProvider({
canTrack: customCanTrack,
cart: currentCart,
Expand All @@ -285,6 +290,31 @@ function AnalyticsProvider({
customCanTrack ? () => customCanTrack : () => shopifyCanTrack,
);

if (!!shop) {
// If mock shop is used, log error instead of throwing
if (/\/68817551382$/.test(shop.shopId)) {
warnOnce(
'[h2:error:Analytics.Provider] - Mock shop is used. Analytics will not work properly.',
);
} else {
if (!consent.checkoutDomain) {
const errorMsg = messageOnError(
'consent.checkoutDomain',
'PUBLIC_CHECKOUT_DOMAIN',
);
errorOnce(errorMsg);
wizardlyhel marked this conversation as resolved.
Show resolved Hide resolved
}

if (!consent.storefrontAccessToken) {
const errorMsg = messageOnError(
'consent.storefrontAccessToken',
'PUBLIC_STOREFRONT_API_TOKEN',
);
errorOnce(errorMsg);
}
}
}

const value = useMemo<AnalyticsContextValue>(() => {
return {
canTrack,
Expand Down Expand Up @@ -318,7 +348,7 @@ function AnalyticsProvider({
{!!shop && !!currentCart && (
<CartAnalytics cart={currentCart} setCarts={setCarts} />
)}
{!!shop && (
{!!shop && consent.checkoutDomain && (
<ShopifyAnalytics
consent={consent}
onReady={() => {
Expand All @@ -327,8 +357,6 @@ function AnalyticsProvider({
setCanTrack(() => shopifyCanTrack);
}}
domain={cookieDomain}
disableThrowOnError={disableThrowOnError}
isMockShop={/\/68817551382$/.test(shop.shopId)}
/>
)}
</AnalyticsContext.Provider>
Expand Down
13 changes: 11 additions & 2 deletions packages/hydrogen/src/analytics-manager/AnalyticsView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,21 @@ function AnalyticsView(props: CustomViewProps): null;
function AnalyticsView(props: any) {
const {type, data = {}, customData} = props;
const location = useLocation();
const {publish, cart, prevCart, shop} = useAnalytics();
const {
publish,
cart,
prevCart,
shop,
customData: analyticProviderCustomData,
} = useAnalytics();
const url = location.pathname + location.search;

let viewPayload: ViewPayload = {
...data,
customData,
customData: {
...analyticProviderCustomData,
...customData,
},
cart,
prevCart,
shop,
Expand Down
49 changes: 5 additions & 44 deletions packages/hydrogen/src/analytics-manager/ShopifyAnalytics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ import {
ComponentizableCartLine,
Maybe,
} from '@shopify/hydrogen-react/storefront-api-types';
import invariant from 'tiny-invariant';
import {warnOnce} from '../utils/warning';

function getCustomerPrivacyRequired() {
const customerPrivacy = getCustomerPrivacy();
Expand All @@ -44,10 +42,6 @@ function getCustomerPrivacyRequired() {
return customerPrivacy;
}

function messageOnError(field: string) {
return `[h2:error:Analytics.Provider] - ${field} is required`;
}

/**
* This component is responsible for sending analytics events to Shopify.
* It emits the following events:
Expand All @@ -61,42 +55,11 @@ export function ShopifyAnalytics({
consent,
onReady,
domain,
disableThrowOnError,
isMockShop,
}: {
consent: AnalyticsProviderProps['consent'];
onReady: () => void;
domain?: string;
disableThrowOnError: boolean;
isMockShop: boolean;
}) {
// If mock shop is used, log error instead of throwing
if (isMockShop) {
warnOnce(
'[h2:error:Analytics.Provider] - Mock shop is used. Analytics will not work properly.',
);
} else {
if (!consent.checkoutDomain) {
const errorMsg = messageOnError('consent.checkoutDomain');
if (disableThrowOnError) {
// eslint-disable-next-line no-console
console.error(errorMsg);
} else {
invariant(false, errorMsg);
}
}

if (!consent.storefrontAccessToken) {
const errorMsg = messageOnError('consent.storefrontAccessToken');
if (disableThrowOnError) {
// eslint-disable-next-line no-console
console.error(errorMsg);
} else {
invariant(false, errorMsg);
}
}
}

const {subscribe, register, canTrack} = useAnalytics();
const [shopifyReady, setShopifyReady] = useState(false);
const [privacyReady, setPrivacyReady] = useState(false);
Expand All @@ -117,13 +80,11 @@ export function ShopifyAnalytics({
const {checkoutDomain, storefrontAccessToken, withPrivacyBanner} = consent;

useCustomerPrivacy({
checkoutDomain:
isMockShop || !checkoutDomain ? 'mock.shop' : checkoutDomain,
storefrontAccessToken:
isMockShop || !storefrontAccessToken
? 'abcdefghijklmnopqrstuvwxyz123456'
: storefrontAccessToken,
withPrivacyBanner: isMockShop ? false : withPrivacyBanner,
checkoutDomain: !checkoutDomain ? 'mock.shop' : checkoutDomain,
storefrontAccessToken: !storefrontAccessToken
? 'abcdefghijklmnopqrstuvwxyz123456'
: storefrontAccessToken,
withPrivacyBanner,
onVisitorConsentCollected: setCustomerPrivacyReady,
onReady: () => {
// Set customer privacy ready 3 seconds after load
Expand Down
8 changes: 8 additions & 0 deletions packages/hydrogen/src/utils/warning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,11 @@ export const warnOnce = (string: string) => {
warnings.add(string);
}
};

const errors = new Set<string>();
export const errorOnce = (string: string) => {
if (!errors.has(string)) {
console.error(new Error(string));
errors.add(string);
}
};
6 changes: 1 addition & 5 deletions packages/hydrogen/src/vite/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,7 @@ export function hydrogen(pluginOptions: HydrogenPluginOptions = {}): Plugin[] {
// Avoid optimizing Hydrogen itself in the monorepo
// to prevent caching source code changes:
include: isHydrogenMonorepo
? [
'content-security-policy-builder',
'tiny-invariant',
'worktop/cookie',
]
? ['content-security-policy-builder', 'worktop/cookie']
: ['@shopify/hydrogen'],
},
};
Expand Down
Loading