DEV Community

Edwin Nuñez
Edwin Nuñez

Posted on

How to Add Google Analytics to a React-Next.js Application 📈⚛️

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

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

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

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

Image description

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

Image description

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
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

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

Top comments (0)