How to setup google analytics in Remix project

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

  1. app_remove

  2. app_store_refund

  3. app_store_subscription_cancel

  4. app_store_subscription_renew

  5. click

  6. error

  7. file_download

  8. first_open

  9. first_visit

  10. form_start

  11. form_submit

  12. in_app_purchase

  13. page_view

  14. scroll

  15. session_start

  16. user_engagement

  17. view_complete

  18. video_progress

  19. video_start

  20. view_search_results