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.
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.
Listed below is the script provided by Google. Note that there are a few modifications done to make it work with Next.js.
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.
The
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;
}
Now we have to trigger that analytics script for every page navigation.
The
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.
Log in to the GTM console.
Download Google Analytics 4 Next.js template