Hello fellow developers!
I’ve been attempting to add Google Analytics to my Hydrogen 2.0 project and wanted to get feedback on my approach.
I started off by referencing the Remix example for Google Analytics found here.
Using this as my foundation, I created a file named gtags.client.ts and structured my code similarly. Here’s a brief overview:
declare global {
interface Window {
gtag: (
option: string,
gaTrackingId: string,
options: Record<string, unknown>,
) => void;
}
}
Then, I imported the above file in root:
import * as gtag from "~/lib/gtags.client";
In the defer function, I’ve added my tracking ID:
return defer({
isLoggedIn: Boolean(customerAccessToken),
layout,
selectedLocale: context.storefront.i18n,
cart: cartId ? getCart(context, cartId) : undefined,
analytics: {
shopifySalesChannel: ShopifySalesChannel.hydrogen,
shopId: layout.shop.id,
gaTrackingId: 'NUMBERS',
},
seo,
});
}
Lastly, I’ve added the following logic inside my export default function App():
const location = useLocation();
const lastLocationKey = useRef<string>('');
useEffect(() => {
if (lastLocationKey.current === location.key) return;
lastLocationKey.current = location.key;
if (data.analytics.gaTrackingId) {
gtag.pageview(location.pathname, data.analytics.gaTrackingId);
}
}, [location, data.analytics.gaTrackingId]);
Have I approached this correctly? Should I have perhaps added the tracking ID to shopId instead of creating gaTrackingId? I would greatly appreciate any feedback or suggestions!
Thank you in advance!
