Adding Google Analytics to Next.js – with pages and screens
You can just drop the HTML code with the JavaScript tags into Next.js quite easily.
There are a few amendments to make, of course, converting the HTML embed code to JSX.
You’d add it to your custom _app.js file like this.
import Script from "next/script"
const gtag = `window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-XXXXXXXXXX');`
export default function MyApp({ Component, pageProps }) {
return <>
<Script strategy="afterInteractive" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX" />
<Script id="ga" strategy="afterInteractive" dangerouslySetInnerHTML={{ __html: gtag }} />
<Component {...pageProps} />
</>
}
But remember, when your users navigate between pages in your Next.js website or app, they’re not actually moving between pages.
What I mean is that the browser doesn’t do a full, proper page load. It’s all handled by JavaScript and Next.js. This makes for a much faster website with users not even being able to tell they’ve moved from one page to the next, in terms of visible page loading time.
So we need to tell Google Analytics each time the page changes.
This is how to do it.
import { useRouter } from "next/router"
import Head from "next/head"
import { useEffect } from "react"
import Script from "next/script"
const gtag = `window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-XXXXXXXXXX');`
export default function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = url => {
window.gtag("config", "G-XXXXXXXXXX", { page_path: url })
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
return (
<>
<Head>
<link rel="dns-prefetch" href="https://www.googletagmanager.com/" />
</Head>
<Script strategy="afterInteractive" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX" />
<Script id="ga" strategy="afterInteractive" dangerouslySetInnerHTML={{ __html: gtag }} />
<Component {...pageProps} />
</>
)
}
And that’s it. Now, each time a user navigates between pages – or more accurately ‘routes’ – Google Analytics will record a visit to it.
