How to add Google Analytics to Next.js

Shen Lu
Shen Lu
Posted on Sep 02, 2023
views
2 min read (276 words)

As more and more people visited my blog, I reached the limit of data ingestion of at the end of August.

In order to continue supervising the web traffic of my blog, I decided to replace Vercel Analytics with Google Analytics.

Create Google Analytics Account

Firstly, I need a new account of google analytics. I had one, so I just need create an new id or use the id I created before. For those who do not have google analytics account yet, you can read these toturials, Google Analytics for Beginners

Test Google Analytics in Development Environment

For decoupling the Google Analytics ID with JSX page in Next.js, I set NEXT_PUBLIC_ANALYTICS_ID as environment variable in .env.development file

NEXT_PUBLIC_ANALYTICS_ID='GOOGLE_ANALYTICS_MEASUREMENT_ID'

and copy MEASUREMENT ID into it.

And substitute Vercel Analytics with a code snippets from View tag instructions as below:

{
  /* <!--  import { Analytics } from '@vercel/analytics/react'; --> */
}
import Script from "next/script";
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode,
}) {
  return (
    <html lang="en">
      <body
        suppressHydrationWarning={true}
        className={`flex flex-col h-screen ${fonts.className}`}
      >
        ...
        {/* <!--  <Analytics /> --> */}
        {/* <!-- Google tag (gtag.js) --> */}
        <Script
          async
          src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_ANALYTICS_ID}`}
        />
        <Script id="google-analytics">
          {`window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', '${process.env.NEXT_PUBLIC_ANALYTICS_ID}');
          `}
        </Script>
      </body>
    </html>
  );
}

Viewing page source and see:

Deploy Google Analytics on Production Environment

Setting the environment variable, NEXT_PUBLIC_ANALYTICS_ID with MEASUREMENT ID, in production, which will automatically inject MEASUREMENT ID in the rigit position of the page after pushing source code to GitHub repository, https://github.com/shenlu.me.

Check if it works

Success!