Add Google Analytics to your Next.js site or web app

Learn how to add Google Analytics to a site or web app built with Next.js in order to track web traffic.
September 23, 2023Next.js
3 min read

Google Analytics makes it quick and easy to start tracking web traffic on your Next.js site or web app. First, log into your Google Analytics account and create a new property for the Next.js site or web app that you want to add analytics to. Copy the Measurement ID of the Web Data Stream.

Environment variable

Add the Google Analytics Measurement ID as an environment variable to your Next.js project, either in a .env file or a .env.production file, depending on what you're using for your project. Make sure to also add it as an environment variable wherever your site or web app is being deployed.

.env.production
NEXT_PUBLIC_GOOGLE_ANALYTICS=G-...

Tracking page views

Google Analytics will not report virtual page changes that do not require a full page load in Next.js. To fix this, we'll create a pageview helper method. It will report a new page view to Google Analytics. We'll call this method whenever there is a change in page.

lib/gtag.ts
export const pageview = (id: string, url: string) => {
  ;(window as any).gtag("config", id, {
    page_path: url,
  })
}

Google Analytics component

Next, let's create a Google Analytics component to store the gtag.js code that is provided to us by Google Analytics.

google-analytics.tsx
"use client"

import { useEffect } from "react"
import { usePathname, useSearchParams } from "next/navigation"
import Script from "next/script"

import { pageview } from "@/lib/gtag"

const GoogleAnalytics = ({ id }: { id?: string }) => {
  const pathname = usePathname()
  const searchParams = useSearchParams()

  useEffect(() => {
    if (id) {
      const url = pathname + searchParams.toString()
      pageview(id, url)
    }
  }, [pathname, searchParams, id])

  if (!id) {
    return null
  }

  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${id}`}
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '${id}', {
            page_path: window.location.pathname,
          });
          `,
        }}
      />
    </>
  )
}

export default GoogleAnalytics

This component receives the Google Analytics Measurement ID as a prop. We specified use client at the top of the file in order to ensure that it will run on the client rather than on the server. We then used Next.js Script tag to implement the scripts that Google Analytics provides us with.

We used the React useEffect Hook to listen to changes on both the pathname and searchParams of the URL. Whenever either of these change, we call the pageview helper method that we created earlier, passing to it the Measurement ID and the current URL.

Using the Google Analytics component

Next, let's import our new GoogleAnalytics component into our root layout component, app/layout.tsx.

layout.tsx
import { Metadata } from 'next';

import '@/styles/globals.css';
import GoogleAnalytics from './google-analytics';

interface RootLayoutProps {
  children: React.ReactNode
}

export const metadata: Metadata = {
  //...
};

export default async function RootLayout({ children }: RootLayoutProps) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <GoogleAnalytics id={process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS} />
      </head>
      <body className='min-h-screen bg-background font-sans antialiased'>
        {children}
      </body>
    </html>
  );
}

Conclusion

Your Next.js site or web app is now ready to track and report web traffic, thanks to Google Analytics.

As a reminder, be sure to set NEXT_PUBLIC_GOOGLE_ANALYTICS to the Measurement ID that was generated for the new Google Analytics property for your Next.js site or web app.

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.