React & Google Analytics: How to Integrate GA4 in React?

Click to learn how to integrate Google Analytics 4 in your any React app step by step.

Berkay Demirbaş
Berkay Demirbaş - 24 November, 2021 - 5 min read
React & Google Analytics: How to Integrate GA4 in React?

React & Google Analytics: How to Integrate Google Analytics 4 in React?

It is an undeniable fact that React and Google Analytics are one of the most popular tools and libraries among the web-analyst community. Google Analytics is the most widely used web analysis tool, which helps you easily track and retarget your users.

Google Analytics 4 (GA4) provides you with more comprehensive measurement methods such as personalized reports and intelligence analytics, by blending your web and mobile application together. Moreover, it provides you with better insights into your digital marketing strategies compared to Universal Analytics (UA).

Known for being fast and simple, React is the most popular front-end JavaScript library in the field of web development. Using Google Analytics on your React-based website gives you the following benefits:

  • You can find out from which country your users are driving traffic and what demographics they have.
  • You can see how much time your users spend on which pages.
  • You can measure the Enhanced Ecommerce and custom events.
  • You can report bugs in your React application.
  • You can measure user behavior for A/B tests in your application.

Assuming you have a Google Analytics 4 account and a react-based website, let's see how you can set up a healthy react google analytics property step by step.

First of all, you need to create a GA4 property within your current Universal Analytics account. You can use the GA4 Property Setup Assistant for this. Click on Get Started and it will be installed instantly without any pre-configuration.

GA4 Setup Assistant

You can see that the GA4 installation was successful from the Connected Property section.

GA4 Connected Property

Google Analytics 4 Measurement ID

Half of our work is done. Now that we have received the most important part, which is GA4 Measurement ID, which starts with G-, so that you can complete the GA4 installation on our React-based website.

GA4 Google Analytics 4 Measurement ID

React Google Analytics Integration

In the React ecosystem in the digital marketing world, Static Site Generators (SSG) such as Gatsby and NextJS are generally used for page management, plugin support, CMS, site speed, and SEO compatibility concerns.

Now let's start with possible integration methods.

Adding Gtag Script

First you need to install the react-ga package in your application.

yarn add react-ga

Then you have to add the react-ga package into index.js or app.js.

import ReactGA from 'react-ga';

const TRACKING_ID = "UA-12341234-1"; // YOUR_OWN_TRACKING_ID

ReactGA.initialize(TRACKING_ID);

One of the most common problems in React applications occurs in the rendering methods, specifically, CSR (Client Side Rendering) and SSR (Server Side Rendering). You can access detailed information here for rendering methods.

In your SPA (Single Page Application) applications, you should send your events with history.listen using react-router-dom in order to prevent these rendering problems.

import React from 'react'
import { withRouter } from 'react-router-dom';
import ReactGA from 'react-ga';

const RouteChangeTracker = ({ history }) => {

   history.listen((location, action) => {
       ReactGA.set({ page: location.pathname });
       ReactGA.pageview(location.pathname);
   });

   return <div></div>;
};

export default withRouter(RouteChangeTracker);

Gatsby GTAG Plugin

If you use Gatsby engine on your website, adding gatsby-plugin-google-gtag /) is recommended.

First of all, you need to install the gatsby-plugin-google-gtag plugin.

yarn add gatsby-plugin-google-gtag

Then you should update the gatsby-config.js file as follows:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        trackingIds: [
          "GA-TRACKING_ID",         ],
        gtagConfig: {
          optimize_id: "OPT_CONTAINER_ID",
          anonymize_ip: true,
          cookie_expires: 0,
        },
        pluginConfig: {
          head: false,
          respectDNT: true,
          exclude: ["/preview/**", "/do-not-track/me/too/"],
        },
      },
    },
  ],
}

Because of the SSR, you may also have to send your custom events as shown below.

typeof window !== "undefined" && window.gtag("event", "click", { ...data })

Adding GTAG Script in Next.js

In the folder where your Next.js application is located, you can open the .env.local file, so that you can add your Measurement ID.

NEXT_PUBLIC_GOOGLE_ANALYTICS=<Your_tracking_ID>

You can easily add this variable in the .env.local file, for example if you are using Vercel.

Using Vercel Next Env file

Then it will be enough to add the snippet into the _document.js file.

import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

To pull custom events, you should use this following method;

export const event = ({ action, params }) => {
  window.gtag('event', action, params)
}

As you can see, there are different Google Analytics 4 integration methods according to different frameworks.

However, no matter what React framework you are using, you must first understand how Google Analytics pulls data from any web application. This will prevent possible measurement and integration errors on your website.

Gtag and GA4 Working Principle

You can access the source on how Google Analytics 4 works on the Gtag script here.