Connect google analytics to Next.js App

Tags:
Date:

Saturday 23/07/2022

I assume that you already create your google analytics property and now you want to connect it to your Next.js app.

Let's open _app file and import Script from next/app:

import Script from 'next/script'

Then we will get the code from google analytics page and add it to our JSX:

<Script
	strategy="lazyOnload"
	src="https://www.googletagmanager.com/gtag/js?id=YOUR_GOOGLE_CODE"
/>

<Script id="gtag-next" strategy="lazyOnload">
	{`window.dataLayer = window.dataLayer || [];
	function gtag(){dataLayer.push(arguments);}
	gtag('js', new Date());

	gtag('config', 'YOUR_GOOGLE_CODE');`}
</Script>

And basically that is all.

You can use env variables and store YOUR_GOOGLE_CODE in there.

Another thing - to get more accurate data you should use it only in production environment.

© 2023 Vadim Alakhverdov