How to set up Next.js with google analytics


This article will show you how to set up google analytics with Next.js framework, in the following we suppose that the purpose is to add your google annalytics to a website.
Step 1: Login to google analytics using gmail account
The first thing to do is create your property on google analytics, you can do so by heading to google analytics website, it will ask you to login using one of your gmail accounts.
Step 2: Set up your property
Step 3: get your google Measurement ID
Once finished, head again to "data streams" on the "Web" section, and click on the data stream you have named, it will pop up a screen and show you your measurement ID, copy it because we will need it later, you can also scroll down, and you will find your global site tag, you can click on it and it will give you a code snippet where you can put it in the head of your html files.
Step 4: Set up Next.js with google analytics
Now the fun part! let's browse our Next.js project, so Next.js have a folder structure where each page that need to be served is contained under "pages" folder by default, so in order for google analytics to analyze our pages, it should be added on every single page, however with Next.js, this is much easier since all pages are inherited from Document class.
Step 5: Create _document.js
Next.js dictate that in order to overwrite the template on which pages are served, you need to declare your _document.js under pages folder, like so, every page served by Next.js will have the same template, so let's take a look :
import Document, { Html, Head, Main, NextScript } from "next/document";
import { G_TAG } from "../lib/constants";
export default class MyDocument extends Document {
render() {
const url = "https://www.googletagmanager.com/gtag/js?id=" + `${G_TAG}`;
return (
<Html lang="en">
<Head>
<script async src={`${url}`}></script>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${G_TAG}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
Step 6: Create your gtag constant
The next thing to do is to define you measurement ID which i asked to save, so for my example i am keeping this values on a separate file for maintenance facility, so it should look like :export const G_TAG = {
development: "dev-mode",
production: "YOUR-MEASUREMENT-ID-FROM-GANALYTICS",
}[process.env.NODE_ENV];
So in order to separate developement from deployement, we define two variables, i call it developement mode 'dev-mode', that way i'm not submitting anything to google while i am working on my app, and the production mode once the application is deployed, and this is orchestrated by the value of the "process.env.NODE_ENV".
Keep in mind that running "npm run build" will set the environement to production.
Testing everything is fine
Once done, you can browse any page of yours, on chrome navigator under windows OS, you can press "ctrl+u", it will pop up the page source code, then check whether the google tag on the html head is well configured, and it takes into account node environment. Also you can check your google analytics account, and see if it starts collecting data.
It could take sometimes if it is the first time you set it up, just be patient, and make sure whenever you check the html source code of any page of yours that your google tag is visible.