谷歌分析与nextjs 13?

qij5mzcb  于 2023-08-04  发布在  其他
关注(0)|答案(4)|浏览(128)

有人成功地让谷歌分析在NextJS 13上工作吗?
我跟踪了这个线程:How to implement Google Analytics with NextJS 13?但是当我在我的应用程序上做同样的事情时,谷歌分析上什么也没有显示。我也没有得到任何错误的应用程序和脚本加载正确时,我检查页面。
我想在上面的帖子中发表评论,但我没有足够的声誉:/

wmomyfyw

wmomyfyw1#

我在Next Docs上找到了这个。
https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals#sending-results-to-external-systems
和/或
https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics

jtjikinw

jtjikinw2#

成功设置分析配置后,如OP所示:
How to implement Google Analytics with NextJS 13?
您可以通过触发一个简单的事件来测试它,如下所示:
第一个月

'use client'
import Script from "next/script"

const GoogleAnalyticsEvent = () => {

    return (
        <Script 
            id="google-analytics-event"
            strategy="afterInteractive"
        >
            {`gtag('event', 'this_is_my_test', {
                'app_name': 'myAppName',
                'screen_name': 'Home'
                });`
            }
        </Script>
    )
}
export default GoogleAnalyticsEvent

字符串
这就是你的app/layout.js应该是这样的:

import GoogleAnalyticsInit from './components/GoogleAnalyticsInit';
import GoogleAnalyticsEvent from './components/GoogleAnalyticsEvent';

export default function RootLayout({ children }) {

  return (
    <html>
      <body>
        <GoogleAnalyticsInit />
        <GoogleAnalyticsEvent />
        {children}
      </body>
    </html>
  )
}


并且,转到Google Analytics Dashboard(报告>实时选项卡>(事件计数按事件名称)),您可以在本地刷新页面后可视化显示您的测试:


的数据

jvlzgdj9

jvlzgdj93#

这是我对Next.js 13.4和Google Analytics 4的配置。
将此添加到RootPage:

<Script
    src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_APP_GA_MEASUREMENT_ID}`}
/>
<Script id="google-analytics">
    {`
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', '${process.env.NEXT_PUBLIC_APP_GA_MEASUREMENT_ID}');

    `}
</Script>

字符串
将环境变量NEXT_PUBLIC_APP_GA_MEASUREMENT_ID替换为您自己的GA4标记。

vq8itlhq

vq8itlhq4#

以下是Next.JS 13上Google Analytics的完整代码
安装gtag

npm install @types/gtag

字符串
on .env.生产

NEXT_PUBLIC_GA_ID="G-XXXXXXXXX"


在@/lib/gtag.ts上

import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef } from "react";

export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID;

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

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

export const useGtag = () => {
  const pathname = usePathname(); // Get current route

  // Save pathname on component mount into a REF
  const savedPathNameRef = useRef(pathname);

  useEffect(() => {
    if (process.env.NODE_ENV === 'development') return;

    const handleRouteChange = (url: URL) => {
      pageview(url);
    };

    if (savedPathNameRef.current !== pathname) {
      handleRouteChange(new URL(pathname, window.location.origin));
      // Update REF
      savedPathNameRef.current = pathname;
    }
  }, [pathname, ]);
};


on components/GoogleAnalytics.tsx

'use client'

import Script from 'next/script';
import * as gtag from '@/lib/gtag';

export default function GoogleAnalytics(){

    gtag.useGtag();

    return (
        <>
            {process.env.NODE_ENV !== 'development' && (
            <>
                {/* Global Site Tag (gtag.js) - Google Analytics */}
                <Script
                strategy="afterInteractive"
                src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
                />
                <Script
                id="gtag-init"
                strategy="afterInteractive"
                dangerouslySetInnerHTML={{
                    __html: `
                    window.dataLayer = window.dataLayer || [];
                    function gtag(){dataLayer.push(arguments);}
                    gtag('js', new Date());
                    gtag('config', '${gtag.GA_TRACKING_ID}', {
                        page_path: window.location.pathname,
                    });
                    `,
                }}
                />
            </>
            )} 
        </>
    )
}


在app/layout.tsx上

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <>
    <html lang="ko">
        <GoogleAnalytics />
        <body>
                {children}
        </body>
    </html>
    </>
  )
}

相关问题