Adding Google Analytics to Next.js
Here’s a nice easy one – but with a trickier conclusion.
Google Analytics is almost a no brainer. You won’t find any other services offering as much as Google for free.
Once you’ve signed up for an account, you can get your tracking code which will look like this.
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
Unfortunately, you can’t just paste that into Next.js and Google Analytics doesn’t offer a specific code snippet either.
We can make some small changes to the tracking code and add it to our _app.js file.
Default app
This is what you get with Next.js by default.
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
New app
Here’s how you add it (code below):
- Open _app.js
- Wrap the default
<Component>JSX tag with aReact fragment - Import
next/script - Add the Google Analytics code via two
<Script />components
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-XXXXXXXX" />
<Script id="ga" strategy="afterInteractive" dangerouslySetInnerHTML={{ __html: gtag }} />
<Component {...pageProps} />
</>
}
And cookies?
Google Analytics uses cookies, so to comply with General Data Protection Regulation (or GDPR), you must:
- show a message notifying users that your website uses cookies,
- enable users to opt-in or opt-out of cookies,
- not track a user until they have opted-in.
On this website, the Google tracking code is conditionally added to a page only if the user has opted-in to cookies.
On the one hand, I almost certainly lose some users in my web analytics, but on the other, I’m compliant with the law.
