Google Analytics 4与Next.js

huangapple go评论66阅读模式
英文:

Google analytics 4 with Next js

问题

我尝试将Google Analytics添加到我的页面,并期望在Google Analytics仪表板上实时看到变化。

英文:

The problem that I have is that I'm trying to add Google Analytics to My Next.js app and there are two problems. The first problem is that I can't see collect message in network tab in Chrome but in Microsoft Edge is visible. Also dataLayer in Chrome when logged to the console doesn't show any events while Edge shows events.
The second problem is that I still have "No data received" in my Google Analytics dashboard and Realtime doesn't show anything. This is my code
_app.js

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 GoogleAnalytics from "@/components/GoogleAnalyitics";
const CookieBanner = dynamic(() => import("../components/CookieBanner"), {
  ssr: false,
});
const raleway = Raleway({
  subsets: ["latin"],
  variable: "--font-ral",
});
const ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS;
function App({ Component, pageProps }) {
  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} />
        <CookieBanner></CookieBanner>
        <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>
        <GoogleAnalytics GA_MEASUREMENT_ID={ID}></GoogleAnalytics>
      </main>
    </>
  );
}

export default appWithTranslation(App);

GoogleAnalytics.js

import Script from "next/script";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { pageview } from "@/lib/gtagHelper";
export default function GoogleAnalytics({ GA_MEASUREMENT_ID }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    const url = pathname + searchParams.toString();

    pageview(GA_MEASUREMENT_ID, url);
  }, [pathname, searchParams, GA_MEASUREMENT_ID]);
  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('consent', 'default', {
                    'analytics_storage': 'denied'
                });
                
                gtag('config', '${GA_MEASUREMENT_ID}', {
                    page_path: window.location.pathname,
                });
                `,
        }}
      />
    </>
  );
}

gtagHelper.js

export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS;

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
  window.gtag("config", GA_TRACKING_ID, {
    page_path: url,
  });
};

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
  window.gtag("event", action, {
    event_category: category,
    event_label: label,
    value: value,
  });
};

CookieBanner.js

import Link from "next/link";
import { getLocalStorage, setLocalStorage } from "@/lib/storageHelper";
import { useState, useEffect } from "react";
export default function CookieBanner() {
  const [cookieConsent, setCookieConsent] = useState(false);

  useEffect(() => {
    const storedCookieConsent = getLocalStorage("cookie_consent", null);

    setCookieConsent(storedCookieConsent);
  }, [setCookieConsent]);

  useEffect(() => {
    const newValue = cookieConsent ? "granted" : "denied";

    window.gtag("consent", "update", {
      analytics_storage: newValue,
    });

    setLocalStorage("cookie_consent", cookieConsent);
  }, [cookieConsent]);
  return (
    <div
      className={`${
        cookieConsent !== null ? "hidden" : "flex"
      } my-10 mx-auto w-max fixed bottom-0 left-0 right-0  px-3 md:px-4 py-3 justify-between items-center flex-col sm:flex-row gap-4 bg-gray-200 rounded-lg shadow`}
    >
      <div className="text-center">
        <Link href="/info/cookies">
          <p className="whitespace-nowrap">
            We use{" "}
            <span className="font-bold text-sky-400 mx-1"> cookies </span> on
            our site.
          </p>
        </Link>
      </div>

      <div className="flex gap-2">
        <button
          onClick={() => setCookieConsent(false)}
          className="px-5 py-2 text-gray-700 rounded-md border-gray-900"
        >
          Decline
        </button>
        <button
          onClick={() => setCookieConsent(true)}
          className="bg-primary px-5 py-2 text-white rounded-lg whitespace-nowrap"
        >
          Allow Cookies
        </button>
      </div>
    </div>
  );
}

I tried to add Google Analyitics to my page and I was expecting to see changes in realtime on Google Analytics dashboard

答案1

得分: 1

在您的_app.js代码中可能有帮助,但在导入中有一个拼写错误:

import GoogleAnalytics from "@/components/GoogleAnalyitics";

"Analyitics" 拼写错误在末尾。

英文:

Not sure if this is going to help, but in your _app.js code, there's a typo in the import:

import GoogleAnalytics from "@/components/GoogleAnalyitics";

Spelt "Analytics" wrong at the end.

huangapple
  • 本文由 发表于 2023年4月17日 19:29:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定