How to Add Google Analytics to a React-Next.js Application 📈⚛️
Tags: javascript, programming, tutorial, react
Published: 2022-09-02 17:35:34

Data is today the world’s most valuable commodity. So understanding how your users are using your platform is crucial for taking your business to the next level.

And in the world of analytics, Google is the leader. And the great news is it’s completely free to use! 👌

Today we will see how to integrate Google analytics into a Next.js application. If you are interested in pure React, another article is for you.

## Step-1️⃣  Get the key

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssuoxta47olwl0ulpkfi.png)


Create a new account on `https://analytics.google.com/` . When you register for the first time, you will be asked to add a new property.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n7dfvt4rxp5teq6nuxwr.png)

The admin portion of your account allows you to add a new property if you already have a Google Analytics account. The next step is to construct a data stream. We will choose web as we are implementing this on the web.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scle5w1r574yp8nvhqni.png)

You will then need to give some information about your website. For now, enter some fictitious data and start the broadcast.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6yb6x09mku4jd4qiothq.png)

Now you will have to grab the `Measurement ID` which is the most important thing in the whole process.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ljytj3rl46sq7gcjv8w.png)

The pattern will resemble the following `G-XXXXXXXXXX`. Adapt that.

We may now incorporate this into the project itself. Do that, then!


## Step-2️⃣ Initialize the project 


```
npx create-next-app nextjs-google-analytics-demo
```

## Step-3️⃣ Add to Environment

Make a file called `.env.local` in the project root. Then insert the subsequent code there. Although you could do this directly in the code, environment variables are preferable. 

```
NEXT_PUBLIC_GOOGLE_ANALYTICS= 'G-LXXGTJJDFX'
```

## Step-4️⃣ Load Analytics

Open the `__app.tsx` file and add the 2 script tags there.

```
import { AppProps } from 'next/app';
import Head from 'next/head';
import React, { useEffect } from 'react';
import './styles.css';
import Script from 'next/script';
import Router from 'next/router';


function CustomApp({ Component, pageProps, router }: AppProps) {

    return (
        <>
            <Script strategy="lazyOnload" src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`} />

            <Script strategy="lazyOnload">
                {`
                    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,
                    });
                `}
            </Script>
            
            
            <Head>
                <title>Welcome!</title>
                <meta name="viewport" content="initial-scale=1, width=device-width" />
            </Head>

            <Component {...pageProps} />
        </>
    );
}


export default CustomApp;
```

## Step-5️⃣ Check the browser

Run the app using the following command

`npm run dev` or `yarn run`

And go to the URL `http://localhost:3000` and open the console.

## Step-6️⃣  Check if Analytics is Enabled

Open the console on your browser and type `dataLayer` there.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nk1hrx36ztqv1leohb0s.png)

Undefined indicates that there was a problem. Congratulations if you see something similar to the image above! Your analytics have been enabled.


**Guarapo Labs **creates digital products that assist people in developing their ideas. Our staff has all of the necessary skills to work on your web and virtual reality game projects. Our commitment to educating our clients on how to provide the finest customer experience with their solutions is reflected in the high quality of our software.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7pd7mdmk681h5uzye3a.png)