フロントエンド開発の先端を突っ走るNext.js
next.js アプリの初期化( npx create-next-app@latest <アプリ名> ) または yarn create next-app <アプリ名> または bun create next-app <アプリ名> )

next.js で Google Analytics

● react-ga4 を使用する場合

npm i react-ga4

src/googleAnalytics/GoogleAnalytics.tsx

'use client';

import ReactGA from 'react-ga4';
import { usePathname, useSearchParams } from 'next/navigation';
import { useEffect } from 'react';

export const GOOGLE_ANALYTICS_ID =
  process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID ?? '';

ReactGA.initialize(GOOGLE_ANALYTICS_ID, {
  // testMode: true,
});

export const GoogleAnalytics = () => {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (!GOOGLE_ANALYTICS_ID) return;

    const url = pathname + searchParams.toString();
    // react-ga4:pageview
    ReactGA.send({ hitType: 'pageview', page: url });

    // react-ga4 : set
    // ReactGA.set({ UserID: 123456798 });
    
  }, [pathname, searchParams]);

  return null;
};

src/app/layout.tsx

import { GoogleAnalytics } from '@/googleAnalytics/GoogleAnalytics';

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <GoogleAnalytics />
      <body className={inter.className}>{children}</body>
    </html>
  );
}
No.2517
05/17 17:51

edit