Logo
BlogAboutContact

© Yui Sato's Tech. All Rights Reserved 2024-2025

This site uses Google Analytics. For more information, please see How Google uses information from sites or apps that use our services.

Next.jsで構築したアプリケーションにGoogle Analyticsを導入する方法

  • #Next.js
  • #Google Analytics

Next.jsで構築したアプリケーションにGoogle Analyticsを導入する方法をご紹介します。

2024/07/16

当ブログはNext.jsで構築されていますがアクセス解析ツールとしてGoogle Anayticsを使用しています。

Google Analyticsは基本的にscriptタグをアプリケーションに埋め込むことで動作しますが、Next.jsで構築されたアプリケーションではそのままタグを埋め込むことはできずエラーになってしまいます。

今回はscriptタグのエラーを回避して、Next.jsで構築したアプリケーションにGoogle Analyticsを導入する方法をご紹介します。

実行環境

⚠️ App Routerを使用してます。

"next": "^14.2.5",

結論

@next/third-partiesライブラリのGoogleAnalyticsコンポーネントをimportして実装します。

サンプルコード

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

...省略

export default async function RootLayout({ children }: Props) {
  return (
    <html lang="ja">
      <GoogleAnalytics gaId="<GoogleAnayticsId>" />
      <body>
      ....省略
      </body>
    </html>
  );
}

解説

@next/third-partiesはNext.jsが公式で出しているライブラリでGoogle AnalyticsやGoogle Map、Youtube等のサードパーティ製のタグや埋め込みをパフォーマンス最適化した状態でサポートしています。実験的なライブラリではあるため(2024年7月現在)、latestをつけて最新のバージョンのインストールが推奨されています。詳しくは以下の記事をご覧ください。

補足として、next/scriptによるScriptタグの使用もできるので、そちらのサンプルコードも載せておきます。

サンプルコード

...省略
import Script from 'next/script';

...省略

export default async function RootLayout({ children }: Props) {
  const tags = await getTagList({
    limit: LIMIT,
  });
  return (
    <html lang="ja">
      <Script id='ga'>
      {`
        window['dataLayer'] = window['dataLayer'] || [];
        function gtag(){window['dataLayer'].push(arguments);}
        gtag('js', new Date());
        gtag('config', '<GoogleAnayticsId>');
      `}
      </Script>
      <body>
      ....省略
      </body>
    </html>
  );
}

参考記事

  • Using Google Analytics with Next.js (through next/script)
  • Third Party Libraries - google-analytics
  • Script Optimization - Inline Scripts