How to Integrate Google Analytics to A Next.js Project

Tutorial
Web Development
Blog
Studiofru
Studiofru
Cover Image for How to Integrate Google Analytics to A Next.js Project

We have talked about the love we have for PostHog before by examining the pricing tag and the method of implementing the tool in our Next.js project. While it’s true that we are using PostHog mainly as our product analytic tool to understand our users behaviour, there’s still a need to use another platform to better understand our users. And, what else is there if it’s not Google Analytics? 

Google Analytics from the start has become one of the important tools which needed to be integrated into websites. Website owners around the world are using it no matter if they are using other product analytics for their website. Google Analytics has seemingly been a must for every website on the planet.

Next.js has made it easy for developers to connect Google Analytics to the Next.js project. They even have a third party library or @next/third-parties with some ability specifically for Google. 

Until the present day through the third party library that is provided by the Next.js we can use components such as the GoogleTagManager which will integrate our project easily into the Google Tag Manager, GoogleMapsEmbed which will help to add the Google Maps component to a page in the project, and YouTubeEmbed which will help to display a YouTube video or playlist to a page in the project. All of the components are using lazy load that eventually will help increase the loading speed of the pages. 

But unfortunately, we don’t use them in our projects as it isn’t that easy and relevant with the design of our websites. Instead, for Google Analytics, we are using the optimization method which is also provided by the Next.js team. While the documentation also said that we might need to use next/script to optimize script loading, the experience that we have did not support this method to implement it with Google Analytics as Google Analytics doesn’t seem like recognize it let alone record the analytics from the websites. 

After trials and errors for a few days, we have finally found the way to solve the issue and successfully connected both sides between our Next.js project and Google Analytics without any harm. 

First, we need to write our Google Analytics Tracking ID on the environment variables

NEXT_PUBLIC_GA_ID=<Your Google Analytics ID>

Second, write down some code to record website events and send them to Google Analytics on /lib/gtag.js

export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  })
}

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  })
}

Finally, put down the Google Analytics embed code on /_document.js

import Document, { Html, Head, Main, NextScript } from 'next/document'
import * as gtag from '../lib/gtag'

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>  
            {/* Global Site Tag (gtag.js) - Google Analytics */}
            <script
              dangerouslySetInnerHTML={{
              __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('config', '${gtag.GA_TRACKING_ID}', {
                  page_path: window.location.pathname,
                });
              `,
              }}
            /> 
            {/* Global Site Tag (gtag.js) - Google Analytics */}
            <script
              strategy="afterInteractive"
              src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
            />                   
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

External Link

Share this article