DEV Community

Cover image for How to add Google Analytics to Next.js app
collegewap
collegewap

Posted on • Originally published at codingdeft.com

How to add Google Analytics to Next.js app

If you have started working with Next.js recently and wanted to add Google Analytics to your website, then you are at the right place!

Creating a Google Analytics tag

Login to https://analytics.google.com/analytics/web/ with your Google account.

Now click on the Settings Icon (βš™οΈ Admin) at the bottom and click on Create Account
(If you already have an account, you can click on Create Property).

ga admin page

Now fill in the account name:

ga account name

Fill in the property details along with the time zone and currency:

ga property details

Finally, fill in the business details and click on Create:

ga create tag

Now you will be redirected to a page with the following options. Here click on Web.

ga choose web

In the next step provide your website details and click on Create stream.

ga create stream

Now you will be provided with a measurement id. Make a note of it. It will be used in the next step.

ga copy tag

Creating a Next.js app

Now create a Next.js app, if you do not have one, using the following command:

npx create-next-app@latest next-ga-integration
Enter fullscreen mode Exit fullscreen mode

Adding Google Analytics

Create a file named gtag.js with the following content (replace GA_TRACKING_ID value with yours):

export const GA_TRACKING_ID = "G-226MBLFR8V" //replace it with your measurement 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,
  })
}
Enter fullscreen mode Exit fullscreen mode

We have 2 functions here:

  • pageview: To track users navigating to different pages.
  • event: To track events like add to cart, place order, etc.

Now open _app.js and include the following code:

import "@/styles/globals.css"
import Script from "next/script"
import { useRouter } from "next/router"
import { useEffect } from "react"
import * as gtag from "gtag"

export default function App({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = url => {
      gtag.pageview(url)
    }
    router.events.on("routeChangeComplete", handleRouteChange)
    return () => {
      router.events.off("routeChangeComplete", handleRouteChange)
    }
  }, [router.events])

  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="afterInteractive"
        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,
            });
          `,
        }}
      />
      <Component {...pageProps} />;
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

In the above code:

  • We have included the Google Analytics script and loading it after the page becomes interactive so that it doesn't affect the page loading time.
  • We have a useEffect where we listen to route changes and call the pageview function, defined inside gtag.js. This is required since in Next.js, whenever routing happens, the page doesn't completely reload and Google Analytics will not be able to pick up the route change automatically.

Now your application is setup with Google Analytics and you can track the live users:

ga live user

Top comments (4)

Collapse
 
_eduard26 profile image
Eduard Constantin

I think this way is safer:

<Script id="gtag-init" strategy="afterInteractive">
          {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', '${gtag.GA_TRACKING_ID}');
        `}
</Script>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ricsala profile image
Ric Sala

Indeed...wouldn't it be more useful if you used GTM and then add Analytics there?

Collapse
 
tauleshwar profile image
Tauleshwar Thakur

How do we do it in app route

Collapse
 
bassem97 profile image
bassem jadoui

Put the code in Global Layout.tsx