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 an…


This content originally appeared on DEV Community and was authored by Marco Valsecchi

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

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,
  },
}

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

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}`}
/>
  • 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,
            });
        `,
    }}
/>

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);}

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"]           
          };
        `,
    }}
/>

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


This content originally appeared on DEV Community and was authored by Marco Valsecchi


Print Share Comment Cite Upload Translate Updates
APA

Marco Valsecchi | Sciencx (2022-03-29T00:00:49+00:00) How to add Google Analytics gtag to Next.js using Partytown ๐ŸŽ‰. Retrieved from https://www.scien.cx/2022/03/29/how-to-add-google-analytics-gtag-to-next-js-using-partytown-%f0%9f%8e%89/

MLA
" » How to add Google Analytics gtag to Next.js using Partytown ๐ŸŽ‰." Marco Valsecchi | Sciencx - Tuesday March 29, 2022, https://www.scien.cx/2022/03/29/how-to-add-google-analytics-gtag-to-next-js-using-partytown-%f0%9f%8e%89/
HARVARD
Marco Valsecchi | Sciencx Tuesday March 29, 2022 » How to add Google Analytics gtag to Next.js using Partytown ๐ŸŽ‰., viewed ,<https://www.scien.cx/2022/03/29/how-to-add-google-analytics-gtag-to-next-js-using-partytown-%f0%9f%8e%89/>
VANCOUVER
Marco Valsecchi | Sciencx - » How to add Google Analytics gtag to Next.js using Partytown ๐ŸŽ‰. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/29/how-to-add-google-analytics-gtag-to-next-js-using-partytown-%f0%9f%8e%89/
CHICAGO
" » How to add Google Analytics gtag to Next.js using Partytown ๐ŸŽ‰." Marco Valsecchi | Sciencx - Accessed . https://www.scien.cx/2022/03/29/how-to-add-google-analytics-gtag-to-next-js-using-partytown-%f0%9f%8e%89/
IEEE
" » How to add Google Analytics gtag to Next.js using Partytown ๐ŸŽ‰." Marco Valsecchi | Sciencx [Online]. Available: https://www.scien.cx/2022/03/29/how-to-add-google-analytics-gtag-to-next-js-using-partytown-%f0%9f%8e%89/. [Accessed: ]
rf:citation
» How to add Google Analytics gtag to Next.js using Partytown ๐ŸŽ‰ | Marco Valsecchi | Sciencx | https://www.scien.cx/2022/03/29/how-to-add-google-analytics-gtag-to-next-js-using-partytown-%f0%9f%8e%89/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.