The beauty of Google Analytics
Tags: webdev, javascript, nextjs, googleanalytics
Published: 2022-06-22 10:47:04

##Why?
I recently completed and deployed my first portfolio site. After this, I sat back and thought about how cool it would be to be able keep track of page views in order to see how many people where clicking into my site. After searching through reddit posts and blogs, I kept seeing mention of Google Analytics.

##What is Google analytics?
Google analytics is a free analytics tool that allows you to analyse in great detail about your websites traffic. By gathering this data, we can:

- See the total number of users to the site
- See the split between new and previously viewed users
- The average number of pages a user views in your website
- The average for how long a user spends on your site
- Which countries/cities a user used to view your website
- Which operating system/browser a user used to view your website

##Requirements
Your NextJs project

- A [google analytics](https://analytics.google.com) account
- Google analytics measurement ID (can be found in admin/data streams/the stream you just set up

##Step 1
Inside your .env located in the root folder, we can add our Google ID as shown below. You could skip this step by inserting the Google ID directly into the code in step 2 but I prefer to put ID such as this in an .env file for protection.


![.env file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lnhmmiwyx5bw1sz0rdw.png)

##Step 2
Create a _document.js file in the root directory. This will be where we place the monitoring code for google analytics. Copy and paste the code below to your file.

```javascript
import Document, { Html, Head, Main, NextScript } from 'next/document';

class CustomDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html lang="en-US">
        <Head>
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
              page_path: window.location.pathname,
            });
            `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default CustomDocument;

```

##Step 3
Now on to the final step, testing. At this point you can deploy your project and head over the Google analytics website. Unfortunately it takes Google analytics 24–48 hours to populate the data, however, we can take a look the Real-time tab which will give you an insight to the active users on your site over the past 5 minutes.


![Real-time overview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5j2id1z1je2jimeyfgah.png) *Real-time overview of current users viewing the website*


After the waiting period when the data has been collected you will be able to select the Audience tab and into Overview where you can see the breakdown of your websites traffic over a selected period of time.


![Traffic overview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g9mmz3y2hunkpn4jte6c.png) 
*Overview of user traffic over two days*


##Conclusion
Congratulations, you have now setup your project with Google analytics. At this point you should now begin to see the power of GA and how you can now use this data to monitor the overall traffic and see the strengths and weaknesses of your website.

---
#Links
Google Analytics — https://analytics.google.com
NextJs — https://nextjs.org/
linkedIn — https://linkedin.com/in/adam-o-reilly-js
portfolio - https://www.adamoreilly.com/