Ultimate guide to setup Google Analytics in remix.run project
Before proceeding to this article, you must have google analytics account setup for the website, if not you can follow this article Google Support.
Let's assume, you have Google Analytics property ready and you have an tag id that starts with G-
example:
G-XXXXXXXXXX
Let's create a utility function that adds google analytics script to our remix project. Also, a function which helps us send the events to google Analytics.
// utils.js
export const initializeGA = (tagId) => {
if (typeof window !== "undefined") {
const script = document.createElement("script");
script.async = true;
script.src = `https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID`;
document.head.appendChild(script);
script.onload = () => {
// Initialize Google Analytics
(window as any).dataLayer = (window as any).dataLayer || [];
function gtag() {
(window as any).dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", tagId);
window.gtag = gtag;
};
}
};
export const sendCustomEvent = (
eventName,
eventParams
) => {
if (typeof window !== "undefined") {
window.gtag("event", eventName, eventParams);
}
};
Goto remix.run Root.tsx file and call this function there in the useEffect()
//Root.tsx
export default function App() {
const navigation = useNavigation();
const isLoading = navigation.state === "loading";
const location = useLocation();
useEffect(() => {
initializeGA("G-XXXXXXXXX");
}, []);
return <html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<ContextProvider>
<Body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</Body>
</ContextProvider>
</html>
}
The useEffect without dependency will only run when the component is ready (only once) and it will only run in the client side (useEffect only runs on the client Side).
Now, to call the google analytics, you can call sendCustomEvent in any file, and specify the event name and value to the arguments, That it.
example:
//Root.tsx
const navigation = useNavigation();
const location = useLocation();
useEffect(() => {
if (navigation.state === "idle") {
sendCustomEvent("pageview", {
location: location.pathname + location.search,
title: location.pathname,
});
}
}, [location.pathname, navigation.state]);
Now, we are checking if the user changes the route then in this useEffect, you can call sendCustomEvent and send your event.
Here is the list of all the predefined event names
app_remove
app_store_refund
app_store_subscription_cancel
app_store_subscription_renew
click
error
file_download
first_open
first_visit
form_start
form_submit
in_app_purchase
page_view
scroll
session_start
user_engagement
view_complete
video_progress
video_start
view_search_results