Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use Google Tag script in Next.js?

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.

like image 252
Hossein Fallah Avatar asked Nov 20 '25 19:11

Hossein Fallah


1 Answers

To properly use the google tag in your next.js app, You should add the GTM script to _document.js in the Head section.

example code _documents.js, source.

import Document, { Html, Head, Main, NextScript } from 'next/document'

import { GA_TRACKING_ID } from '../lib/gtag'

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

To set up google analytics page view for single page app, and other methods of using GT in next.js. You can visit this source1, source2.

like image 91
MarioG8 Avatar answered Nov 22 '25 08:11

MarioG8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!