0

I'm trying to implement google analytics in Next js. I included scripts and when i type dataLayer in console I can see this

(2) [Arguments(2), Arguments(3), push: Proxy(Function)]
0
: 
Arguments(2) ['js', Mon Apr 17 2023 08:05:07 GMT+0200 (Central European Summer Time), callee: ƒ, Symbol(Symbol.iterator): ƒ]
1
: 
Arguments(3) ['config', 'G-10KHN0N9HD', {…}, callee: ƒ, Symbol(Symbol.iterator): ƒ]
push
: 
Proxy(Function) {length: 1, name: 'push'}
length
: 
2
[[Prototype]]
: 
Array(0)

so there is no events registered. When I go to realtime on the dashboard there is no data received. What could be the issue This is my _app file

import "@/styles/globals.css";
import { appWithTranslation } from "next-i18next";
import { Raleway } from "next/font/google";
import Head from "next/head";
import Script from "next/script";
import dynamic from "next/dynamic";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { pageview } from "@/lib/gtagHelper";
import CookieConsent from "react-cookie-consent";
import { useRouter } from "next/router";
const DynamicFooter = dynamic(() => import("@/components/Links"));

const raleway = Raleway({
  subsets: ["latin"],
  variable: "--font-ral",
});
const ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS;
function App({ Component, pageProps }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const router = useRouter();
  useEffect(() => {
    console.log(window.gtag);
    const handleRouteChange = (url) => {
      window.gtag("config", "G-10KHN0N9HD", { page_path: url });
    };
    router.events.on("routeChangeComplete", handleRouteChange);
    return () => {
      router.events.off("routeChangeComplete", handleRouteChange);
    };
  }, [router.events]);
  function handleAccept() {
    window.gtag("consent", "update", {
      ad_storage: "granted",
      analytics_storage: "granted",
    });
  }
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.png" />
      </Head>
      <main className={`${raleway.variable} font-ral min-h-screen w-full`}>
        <Component {...pageProps} />
        <DynamicFooter></DynamicFooter>
        <CookieConsent
          style={{
            top: "90%",
            width: "max-content",
            height: "max-content",
            left: "32%",
            "border-radius": 20,
            background: "#92a4ba",
          }}
          buttonText="Accept"
          enableDeclineButton
          onAccept={() => {
            handleAccept();
          }}
          declineButtonText="Decline"
        >
          We use cookies to improve your experience on our site.
        </CookieConsent>
        <Script id="tawk" strategy="lazyOnload">
          {`var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
         (function(){
           var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
           s1.async=true;
           s1.src='https://embed.tawk.to/64367ade4247f20fefeb2cc2/1gtqcvtgf';
           s1.charset='UTF-8';
           s1.setAttribute('crossorigin','*');
           s0.parentNode.insertBefore(s1,s0);
           })()`}
        </Script>
        <Script
          strategy="afterInteractive"
          src={`https://www.googletagmanager.com/gtag/js?id=G-10KHN0N9HD`}
        />
        <Script
          id="gtag-init"
          strategy="afterInteractive"
          dangerouslySetInnerHTML={{
            __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-10KHN0N9HD', {
              page_path: window.location.pathname,
            });
          `,
          }}
        />
      </main>
    </>
  );
}

export default appWithTranslation(App);

1 Answer 1

0

Looks like you have issues similar to this recent post: https://stackoverflow.com/questions/76092606/google-analytics-with-next-js

gtag is supposed to run on the front-end. Therefore, the debugging has to include front-end as well. A usual way to do so is to run your config function in the front-end console and see if you have a corresponding collect? call happening in the console in a few seconds (because it has a delay)

Here, like so:

enter image description here

I just sent a pageview from SO to your analytics because you left the measurement id in your code snippet. You will be able to see this hit once it's processed in a few days.

If you see the Network hits, but you still don't see the hits in your GA, then the problem is most likely your measurement id. Make sure it's correct.

2
  • My problem was ad blocker in Google Chrome. It was a simple issue, but now the issue is how to make ad blocker not blocking GA and GTM.
    – Djela Srca
    Apr 25, 2023 at 6:26
  • The solution to that is overcomplicated. And pricy. You don't want to go that route. Even large enterprises are accepting the loss from adblockers. Also, it's usually 5-10% and you don't use your analytics data for any reporting where 5-10% precision matters. And you supplement your data with your web server logs and actual sales logs, so it becomes less of a problem.
    – BNazaruk
    Apr 25, 2023 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.