DEV Community

Cover image for Google Analytics With Next JS
Muhammad Mejanul Haque
Muhammad Mejanul Haque

Posted on • Updated on

Google Analytics With Next JS

In the old version of Nextjs, we had to add the scripts in _document.jsx which would be heavy on loading performance. Thanks to the new Script Nextjs component, we can add scripts anywhere in the app, and it will also take care of optimizing the app performance.

If you are wondering about can I implement the same strategy in other react meta frameworks, check out https://partytown.builder.io/ which works great with Astro, Gatsby, etc.

First, add your project to Google Analytics then copy the GA measurement id from Admin/Date Streams/Steam Details.

Then create a .env file and add NEXT_PUBLIC_GA_ID=YOUR_GA_MEASUREMENT ID. Restart the app if it's already running.

Finally, Add the code below in your global Jsx file like _app.jsx or _document.jsx etc.

<Script
   strategy="afterInteractive"
   src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
/>
<Script
   id="gtag-init"
   strategy="afterInteractive"
   dangerouslySetInnerHTML={{
      __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}', {
              page_path: window.location.pathname,
            });
          `,
    }}
/>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Make sure to add the environment variable in your hosting server too.

You can also check this Nextjs example from Github.

Related Article

Tailwind CSS With Next.js and Typography.

Top comments (2)

Collapse
 
nkootstra profile image
Niels Kootstra • Edited

Isn't it much easier to implement the following? github.com/vercel/next.js/tree/mas...

Collapse
 
mejanhaque profile image
Muhammad Mejanul Haque

Yes, Of course, it is. I just went with more simpler like copying the code, paste it and wrap it with dangerouslySetInnerHTML.