Table of Contents
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).
Now fill in the account name:
Fill in the property details along with the time zone and currency:
Finally, fill in the business details and click on Create:
Now you will be redirected to a page with the following options. Here click on Web.
In the next step provide your website details and click on Create stream.
Now you will be provided with a measurement id. Make a note of it. It will be used in the next step.
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 id23// https://developers.google.com/analytics/devguides/collection/gtagjs/pages4export const pageview = url => {5 window.gtag("config", GA_TRACKING_ID, {6 page_path: url,7 })8}910// https://developers.google.com/analytics/devguides/collection/gtagjs/events11export 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"67export 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])1819 return (20 <>21 <Script22 strategy="afterInteractive"23 src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}24 />25 <Script26 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 thepageview
function, defined insidegtag.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:
If you have liked article, stay in touch with me by following me on twitter.
Leave a Comment