Skip to content
next

How to add Google Analytics to Next.js app

Mar 18, 2023Abhishek EH3 Min Read
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:

1npx create-next-app@latest next-ga-integration

Adding Google Analytics

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

1export const GA_TRACKING_ID = "G-226MBLFR8V" //replace it with your measurement id
2
3// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
4export const pageview = url => {
5 window.gtag("config", GA_TRACKING_ID, {
6 page_path: url,
7 })
8}
9
10// https://developers.google.com/analytics/devguides/collection/gtagjs/events
11export const event = ({ action, category, label, value }) => {
12 window.gtag("event", action, {
13 event_category: category,
14 event_label: label,
15 value: value,
16 })
17}

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:

1import "@/styles/globals.css"
2import Script from "next/script"
3import { useRouter } from "next/router"
4import { useEffect } from "react"
5import * as gtag from "gtag"
6
7export default function App({ Component, pageProps }) {
8 const router = useRouter()
9 useEffect(() => {
10 const handleRouteChange = url => {
11 gtag.pageview(url)
12 }
13 router.events.on("routeChangeComplete", handleRouteChange)
14 return () => {
15 router.events.off("routeChangeComplete", handleRouteChange)
16 }
17 }, [router.events])
18
19 return (
20 <>
21 <Script
22 strategy="afterInteractive"
23 src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
24 />
25 <Script
26 id="gtag-init"
27 strategy="afterInteractive"
28 dangerouslySetInnerHTML={{
29 __html: `
30 window.dataLayer = window.dataLayer || [];
31 function gtag(){dataLayer.push(arguments);}
32 gtag('js', new Date());
33 gtag('config', '${gtag.GA_TRACKING_ID}', {
34 page_path: window.location.pathname,
35 });
36 `,
37 }}
38 />
39 <Component {...pageProps} />;
40 </>
41 )
42}

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

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com