Hossein Fallah
Hossein Fallah

Reputation: 2539

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.

Upvotes: 3

Views: 3461

Answers (1)

MarioG8
MarioG8

Reputation: 5921

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.

Upvotes: 3

Related Questions