GoogleAnalytics in NextJS app is not sending data to GA

I have in my _app.js the following :

import GoogleAnalytics from "../src/components/GoogleAnalytics";

const App = ({ Component, pageProps }) => {
  return (
    <Fragment>
      <Head>
        ...
        <GoogleAnalytics />
      </Head>
      <Component {...pageProps} />
    </Fragment>
  );
};
export default App;

GoogleAnalytics.js :

import React from 'react';
import Script from 'next/script';

const GoogleAnalytics = () => {
    return (
        <>
            <Script
                strategy='afterInteractive'
                src={`https://www.googletagmanager.com/gtag/js?id=AW-xxx`}
            />
            <Script
                strategy='afterInteractive'
                src={`https://www.googletagmanager.com/gtag/js?id=G-xxx`}
            />
            <Script id='google-analytics-ads' strategy='afterInteractive'>
                {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', 'G-xxx');
              gtag('config', 'AW-xxx', { page_path: window.location.pathname, });
                `}
            </Script>
        </>
    );
};

export default GoogleAnalytics;

But GA has been empty for the last 2 days.

In my browser console, dataLayer is showing as not defined.

1 Like

I had to move GA outside of Head to make it work :

      <Head>
        ...
      </Head>
      <GoogleAnalytics />

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.