This article explains how to integrate Google Analytics 4 Tag Manager (GTM) with a Next.js template. You can Download this project here
The complete template is available to download at the end of this article. This integration method does not require a history change trigger. If you want to integrate Google Analytics 4 into an existing Next.js site, the article Next js google tag manager: 3 ways to use Google analytics in Nextjs explains how to do that.
1. GA 4 Ready Next.js Template Layout
Our template consists of a header, body, and footer. The header and footer components are shared amongst all the pages and are reused throughout the application.
2. Where to place Google Analytics Script
2.1 Next.js ready Google Analytics script
Listed below is the script provided by Google. Note that there are a few modifications done to make it work with Next.js.
2.2 Multiple installations of google tag manager detected
That is a problem most SPAs (single-page applications) face.
To solve that issue, we check to see if the GTM script already exists on the page. if(!scriptExists(scr))
does that. Without that check, there will be an instance of GTM created every time internal navigation happens.
The analytics.tsx
file contains this code in our template. The analytics.tsx
is just a standalone file to separate analytics code from application code.
export const analytics = ((w: Window, d: Document, s: string, l: string, i: string) => {
(w as any).dataLayer = (window as any).dataLayer || [];
(w as any).dataLayer.push({'gtm.start':new Date().getTime(),event:'gtm.js'});
var dl = l != 'dataLayer' ? '&l='+l : '';
var scr = 'https://www.googletagmanager.com/gtm.js?id='+i+dl;
/*
To avoid Multiple installations of google tag manager detected warning
*/
if(!scriptExists(scr)){
var f = d.getElementsByTagName(s)[0],
j: HTMLScriptElement = d.createElement("script")
j.async = true;
j.src = scr;
f?.parentNode?.insertBefore(j,f);
}
})
const scriptExists = (url: string) => {
var scripts = document.getElementsByTagName('script');
for (var i = scripts.length; i--;) {
if (scripts[i].src == url) return true;
}
return false;
}
2.3 Triggering the Analytics script for page navigations
Now we have to trigger that analytics script for every page navigation.
The _app.tsx
is a good candidate to trigger the analytics script. I pick the _app.tsx
component to do that.
A simple useEffect
hook is sufficient to call the analytics script.
useEffect(() => {
analytics(window, document, 'script', 'dataLayer', 'GTM-AA12345');
})
Ensure the analytics function is called on every page navigation.
You can replace the GTM-AA12345 with your GTM tag. It's simple as that. Now let's test if our setup works.
3. Testing the setup on the GTM console
Log in to the GTM console.
- Click the Preview button on the top right. This will open a Tag assistant window.
- Enter your app url on the website url text box. Don't worry, the localhost address works perfectly fine.
- Click Connect. The tag assistant will open your web app in a separate browser tab. It is important to follow below two steps.
- Use the browser tab opened by the tag assistant to do the testing.
- Go back to the tag assistant browser tab and click Continue.
- Look for the success message once the tag assistant connects successfully.
- Navigate through your pages and see the data flowing to the tag manager.
4. Conclusion
We can use the Google Analytics 4 script directly in our Next.js application. There are a few advantages to doing that.- There is no need to create a history change trigger.
- Allows us to solve Multiple installations of google tag manager detected warning message.
Download Google Analytics 4 Next.js template