window.gtag not triggers GA call after initial load

Viewed 277

The code below contains how google stuff is imported into app. It works fine and call GA as you seen in pic below. but its not working when routing to subsequent pages.

As in the image below, it calls analytics api only hard refresh the page...

enter image description here

_app.js:

const ymkApp = ({ Component, pageProps }) => {
  const router = useRouter()

  const handleRouteChange = (url) => {
    console.log(url)
    if (typeof window !== 'undefined') {
      window.gtag('config', 'TRACKID', {
        page_path: 'https://preprod.yemek.com/tarif/kiraz-receli',
      })
    }
  }

  useEffect(() => {
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])

  return <Component {...pageProps} />
}

_document.js:

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

const { publicRuntimeConfig } = getConfig()

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="tr">
        <Head>
          {/* Google Tag Manager Start */}

          <link
            rel="dns-prefetch preconnect"
            href="https://www.google-analytics.com"
          />
          <link
            rel="dns-prefetch preconnect"
            href="https://www.googletagmanager.com"
          />

          <script
            async="async"
            src="https://www.googletagservices.com/tag/js/gpt.js"
          />
          <script
            type="text/javascript"
            dangerouslySetInnerHTML={{
              __html: `
                var googletag = googletag || {};
                googletag.cmd = googletag.cmd || [];
              `,
            }}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
                })(window,document,'script','dataLayer', 'TRACKID');`,
            }}
          />
          <noscript
            dangerouslySetInnerHTML={{
              __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${publicRuntimeConfig.gtm}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
            }}
          />
          {/* Google Tag Manager End */}
        </Head>
        <body>
          <Main />

I have checked, it calls window.gtag each roue change, but doesnt trigger call GA. What might be missing here?

0 Answers
Related