How to add Google Analytics gtag to Next.js using Partytown 🎉
Tags: nextjs, partytown, react, tutorial
Published: 2022-03-29 00:00:49

First of all I'd like to thank you [Paul Scanlon](https://www.twitter.com/@PaulieScanlon) of Gatsby for [his article](https://www.gatsbyjs.com/blog/how-to-add-google-analytics-gtag-to-gatsby-using-partytown/) 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](https://partytown.builder.io/) 🎉
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](https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics) 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](https://nextjs.org/docs/basic-features/script#off-loading-scripts-to-a-web-worker-experimental): 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:
```js
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
```js
<Script
   strategy="worker"
   src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
/>
```
- then change the inline script with this one:
```js
 <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:
```diff
- 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](https://nextjs.org/docs/advanced-features/custom-document) and adding this script in the `Head` component:
```js
<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 🚀