I read How to load Google Tag Manager with next/script component (Next.js 11)? and I also read this doc page.
But none of them solved my problem.
I want to include Google Tag on many of my sites that are developed using nextjs. Thus I have creatd a simple reusable component:
import Script from 'next/script'
const GoogleTag = ({ identifier }) => {
if (!identifier || !identifier.startsWith('G-')) {
throw new Error('Google tag id is not correct;');
}
return <>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${identifier}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${identifier}');
`}
</Script>
</>
}
export default GoogleTag;
And I use it in each of my sites, in the _app.js
file, this way:
import Head from 'next/head';
import GoogleTag from '../Base/GoogleTag';
export default function MyApp({ Component, pageProps }) {
return (
<>
<Head>
<GoogleTag identifier='G-9XLT855ZE0' />
</Head>
<div>
application code comes here
</div>
</>
)
}
But I don’t see Google Tag script being loaded in the Chrom’s Dev Tools, int Networks tab.