DEV Community

Marco Valsecchi
Marco Valsecchi

Posted on

How to add Google Analytics gtag to Next.js using Partytown 🎉

First of all I'd like to thank you Paul Scanlon of Gatsby for his article that helped me a lot 🙏.

You had just finished your super fast Next.js website, all the performance metrics point to the higher level but then you have to add Google Analytics and the dream to get the PageSpeed Insights' fireworks become impossible to achieve... this message sounds familiar right 😭:

Reduce the impact of third-party code

Who you gonna call? Partytown 🎉
Yes, with this incredible library you can "delegate" the execution of the external scripts like analytics to a service worker, reducing the impact of third-party code!

Ok we can start from the example found on the Next.js canary branch creating a new Next.js application along with Google Analytics:

yarn create next-app --example with-google-analytics with-google-analytics-app
Enter fullscreen mode Exit fullscreen mode

Now it's the Partytown turn; in the 12.1.1 version Next.js add an experimental support to its Script component: the worker strategy. Thanks to this native implementation you can add Partytown easily to your Next.js project.

As any experimental feature you must enable it in the nextjs.config.js file:

module.exports = {
  experimental: {
    nextScriptWorkers: true,
  },
}
Enter fullscreen mode Exit fullscreen mode

Then, to complete the setup, you need to add the Partytown library to your dependencies with your favorite package manager:

yarn add @builder.io/partytown
Enter fullscreen mode Exit fullscreen mode

How to move the Google Analytics execution to the service worker?
We need to open the _app.js file on the pages folder and make some edit:

  • first of all we need to change the strategy for the Universal Site Tag with the worker one
<Script
   strategy="worker"
   src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
/>
Enter fullscreen mode Exit fullscreen mode
  • then change the inline script with this one:
 <script
    type="text/partytown"
    dangerouslySetInnerHTML={{
        __html: `
            window.dataLayer = window.dataLayer || [];
            window.gtag = function gtag(){window.dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', '${gtag.GA_TRACKING_ID}', { 
                page_path: window.location.pathname,
            });
        `,
    }}
/>
Enter fullscreen mode Exit fullscreen mode

I'd like to use the Script component for the second script too but I think that is not supported yet so I used a "normal" script tag but with the custom type "text/partytown".

This code seems like the original one from the Google guide but there is a little difference:

- function gtag(){window.dataLayer.push(arguments);}
+ window.gtag = function gtag(){window.dataLayer.push(arguments);}
Enter fullscreen mode Exit fullscreen mode

Defining the gtag as a global function we can let Partytown to reference it. We just need to create a custom document page and adding this script in the Head component:

<script
    data-partytown-config
    dangerouslySetInnerHTML={{
      __html: `
          partytown = {
            lib: "/_next/static/~partytown/",
            forward: ["gtag"]           
          };
        `,
    }}
/>
Enter fullscreen mode Exit fullscreen mode

With these simple steps now we have a fully Google Analytics support in our Next.js app... but executed in a separated service worker 🚀

Top comments (2)

Collapse
 
athammer profile image
Aaron Hammer • Edited

It might be me but has anyone gotten this to work? I tried in my own repo then retried by cloning the repo in the tutorial with-google-analytics and still no luck.

Seems like weird behavior from the service worker. I guess I'll wait until it's more stable unless anyone else has better luck.

edit: nvm looks to work google analytics just took forever to register it? not sure

Collapse
 
kumarsuresh25 profile image
kumarsuresh25

@valse Have you also faced cors issue with Google Analytics?
If yes how you resolved that because i'm facing the same.