Adding Google Analytics to a Next.js App
Track page views and events in Next.js with Google Analytics 4.
When adding Google Analytics to a regular website you paste the tracking
snippet into the <head> and you're done. A Next.js app needs a little more
work because route changes happen on the client, so Google Analytics only sees
the first page load.
Next.js 11 added the next/script component, which makes loading third party
scripts like this much easier. Let's set it up with a Google Analytics 4
property.
Step 1: Add your measurement ID
In Google Analytics create a GA4 property and a web data stream. The data
stream gives you a measurement ID that starts with G-. Add it to .env.local:
NEXT_PUBLIC_GA_ID=G-XXXXXXXXXX
The NEXT_PUBLIC_ prefix makes it available in the browser, which is where the
tracking code runs.
Step 2: Create gtag helpers
Create a small file to wrap the global gtag function that the Google script
adds to window:
// lib/gtag.jsexport const GA_ID = process.env.NEXT_PUBLIC_GA_ID// Send a page view for the new urlexport const pageview = (url) => {if (!window.gtag) returnwindow.gtag("config", GA_ID, {page_path: url,})}// Send a custom eventexport const event = ({ action, category, label, value }) => {if (!window.gtag) returnwindow.gtag("event", action, {event_category: category,event_label: label,value,})}
pageview calls config again with the new path, which sends a page view.
event lets you track anything else, like button clicks or form submissions.
The window.gtag check means the helpers do nothing when the script isn't
loaded, like in development.
Step 3: Load the script in _app.js
The scripts go in _app.js so they load on every page (see
Next.js _app.js example for more on this file):
// pages/_app.jsimport { useEffect } from "react"import { useRouter } from "next/router"import Script from "next/script"import * as gtag from "../lib/gtag"const isProduction = process.env.NODE_ENV === "production"const MyApp = ({ Component, pageProps }) => {const router = useRouter()useEffect(() => {if (!isProduction) returnconst handleRouteChange = (url) => {gtag.pageview(url)}router.events.on("routeChangeComplete", handleRouteChange)return () => {router.events.off("routeChangeComplete", handleRouteChange)}}, [router.events])return (<>{isProduction && (<><Scriptstrategy="afterInteractive"src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_ID}`}/><Scriptid="gtag-init"strategy="afterInteractive"dangerouslySetInnerHTML={{__html: `window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag("js", new Date());gtag("config", "${gtag.GA_ID}", {page_path: window.location.pathname,});`,}}/></>)}<Component {...pageProps} /></>)}export default MyApp
There are a few things going on here:
- The first
Scriptloads the Google tag library.strategy="afterInteractive"loads it after the page becomes interactive, so it doesn't slow down the first render. - The second
Scriptis the inline config from the Google snippet. It sets upwindow.gtagand sends the page view for the first page load. - The
useEffectlistens forrouteChangeComplete, which fires every time the user navigates to a new page withnext/linkorrouter.push. We remove the listener in the cleanup function. - Everything is wrapped in
isProductionso visits fromnpm run devdon't show up in your reports.
Note: GA4 data streams have enhanced measurement turned on by default, which can also track page changes from browser history events. If you see double page views, turn off "Page changes based on browser history events" in the data stream settings, since the router listener already handles it.
Step 4: Track custom events
With the helper in place, tracking an event is just a function call:
import * as gtag from "../lib/gtag"const SignupButton = () => {const handleClick = () => {gtag.event({action: "sign_up",category: "engagement",label: "Header button",})}return <button onClick={handleClick}>Sign up</button>}
action becomes the event name in GA4, and the other values are sent along
as event parameters.
Testing it
Run npm run build and npm start to test the production build locally. Open
the Realtime report in Google Analytics and click around the app. You should
see a page view for each page you visit.
Have some feedback on this post? .