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,
});
`,
}}
/>
Make sure to add the environment variable in your hosting server too.
You can also check this Nextjs example from Github.
Top comments (2)
Isn't it much easier to implement the following? github.com/vercel/next.js/tree/mas...
Yes, Of course, it is. I just went with more simpler like copying the code, paste it and wrap it with
dangerouslySetInnerHTML
.