谷歌分析与 nextjs 13?

Ton*_*han 5 javascript google-analytics next.js next.js13

有人成功让谷歌分析在 NextJS 13 上工作吗?

我关注了这个主题:How to Implement Google Analytics with NextJS 13? 但是当我在我的应用程序上执行同样的操作时,Google Analytics 上什么也没有显示。我在应用程序中也没有收到任何错误,并且当我检查页面时脚本加载正确。

我想在上面的帖子中发表评论,但我没有足够的声誉:/

小智 7

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

安装 gtag

npm install @types/gtag.js
Run Code Online (Sandbox Code Playgroud)

.env.production

NEXT_PUBLIC_GA_ID="G-XXXXXXXXX"
Run Code Online (Sandbox Code Playgroud)

@/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, ]);
};
Run Code Online (Sandbox Code Playgroud)

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,
                    });
                    `,
                }}
                />
            </>
            )} 
        </>
    )
}
Run Code Online (Sandbox Code Playgroud)

app/layout.tsx

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