Astro製サイトにGoogle Analyticsを追加する

Astro製サイトにGoogle Analyticsを追加する


Astro でもアナリティクス

調べたところ、Partytown を使うといいみたいなので、 これをインストールします。

Partytown を使うと分析や広告などのサードパーティスクリプトの遅延ロードさせることができるようになります。

If you’re using third-party scripts for things like analytics or ads, Partytown is a great way to make sure that they don’t slow down your site.

コマンドはこちら。

npx astro add partytown

いろいろ聞かれますが、Enter(Y) で OK です。 自動的に astro.config.mjs の更新までやってくれます。

途中で出てくる astro.config.mjs は各々で内容が違います。(そのため、下記の例では一部省略しています)

npx astro add partytown

 Resolving packages...

  Astro will run the following command:
  If you skip this step, you can always run it yourself later

 ╭──────────────────────────────────╮
 npm i @astrojs/partytown@^2.1.4
 ╰──────────────────────────────────╯

 Continue? ... yes
 Installing dependencies...

  Astro will make the following changes to your config file:

 astro.config.mjs ─────────────────────────────────────────────────────────────────────────╮
 // @ts-check
 import { defineConfig } from "astro/config";                                              
 ~~~~省略~~~~
 import partytown from "@astrojs/partytown";                                               
 // https://astro.build/config
 export default defineConfig({                                                             │
 ~~~~省略~~~~
   }), icon(), react(), partytown()],
   outDir: "dist",
   base: "/",
 });                                                                                       
 ╰───────────────────────────────────────────────────────────────────────────────────────────╯

 Continue? ... yes

   success  Added the following integration to your project:
  - @astrojs/partytown

Google アナリティクス側で準備した情報を設定

アナリティクス側のアカウントやプロパティの準備は省略します。

Google アナリティクスの場合、window オブジェクトにアクセスするため、追加の設定が必要になります。

type="text/partytown"を script タグに指定し、head タグ内に追加します。

YOUR-ID-HEREはアナリティクスの ID になります。

<script
  is:inline
  type="text/partytown"
  async
  src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID-HERE"
></script>
<script is:inline type="text/partytown">
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag("js", new Date());
  gtag("config", "YOUR-ID-HERE");
</script>

astro.config.mjs の設定も更新します。

    partytown({
      config: {
        forward: ['dataLayer.push'],
      },
    }),

Google Analytics で確認

アナリティクスの画面にて計測されてイベントが発生していることを確認します。

おわりに

これで完了です。簡単でいいですね。