Next.js で Google Analytics を設置したい

NEXT.JS

Next.js 15 のサイトに Google Analytics を設置したい場合には、.env.local ファイルに環境変数として GA の ID を追加する。

NEXT_PUBLIC_GA_ID=G-xxxxxxxxx

@next/third-parties@latest をインストールする

npm install @next/third-parties@latest

layout.tsx で import して、次のコードを追加して完了。

import { GoogleAnalytics } from '@next/third-parties/google';

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const gaId = process.env.NEXT_PUBLIC_GA_ID;
  return (
    <html lang="ja">
      <body>
        {children}
        {gaId && <GoogleAnalytics gaId={gaId} />}
      </body>
    </html>
  );
}
ページの先頭へ