Next.jsのサイトにGoogle Analyticsを導入する

## 1. Googla Analytics
### (1) アカウント作成
![image (7).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/369162/7ebbf479-1bf4-c38c-4e8c-fb85df9dfc1d.png)

### (2)プロパティ作成
![image (8).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/369162/2aea7a65-ff0e-5774-c345-0b1399c4d39e.png)

### (3)ビジネスの概要
![image (9).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/369162/b3f779fb-3c02-56b5-a06e-84cf4ed1cf7a.png)

### (4)choose a platform
![image (13).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/369162/30fda540-6ae4-148a-b6de-8c4c8fe6ea11.png)


### (5)ウェブサイトを定義
![image (10).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/369162/eb85ebb4-3890-d977-cd56-1ff8d4a2923f.png)

## 2. Editor作業
### (1)Google AnalyticsのIDを.envに記述する
#### Analytics IDの場所
管理/データストリーム/ウェブ ストリームの詳細/測定 ID
#### .env.production等に下記貼り付け
```env:.env.ptoduction
NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=UA-SOME_ANALYTICS_ID-1
```
UA-SOME_ANALYTICS_ID-1 = 先ほどのAnalytics ID

### (2)GAイベントを発火させる関数を作成する
・src/hooks/usePageView.ts
・src/lib/gtag.ts
・src/types/googleAnalytics/event.ts
作成
#### usePageView.ts
```ts:src/hooks/usePageView.ts
import { useEffect } from 'react'
import { useRouter } from 'next/router'

import * as gtag from '../lib/gtag'

export default function usePageView() {
  const router = useRouter()
  console.log(gtag.GA_ID)
  useEffect(() => {
    if (!gtag.existsGaId) {
      return
    }

    const handleRouteChange = (path, { shallow }) => {
      if (!shallow) {
        gtag.pageview(path)
      }
    }

    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])
}
```
#### gtag.ts
```ts:src/lib/gtag.ts
export const GA_ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID ?? ''

// IDが取得できない場合を想定する
export const existsGaId = GA_ID !== ''

// PVを測定する
export const pageview = (path) => {
  window.gtag('config', GA_ID, {
    page_path: path,
  })
}

// GAイベントを発火させる
export const event = ({ action, category, label, value = '' }) => {
  if (!existsGaId) {
    return
  }

  window.gtag('event', action, {
    event_category: category,
    event_label: JSON.stringify(label),
    value,
  })
}
```

#### event.ts

```ts:src/types/googleAnalytics/event.ts
type ContactEvent = {
  action: 'submit_form'
  category: 'contact'
  label: string
}

type ClickEvent = {
  action: 'click'
  category: 'other'
  label: string
}

export type Event = ContactEvent | ClickEvent
```

### _document.tsxにGAのスクリプトを書き込む
```tsx:_document.tsx
import Document, { Head, Main, NextScript } from 'next/document'
import { existsGaId, GA_ID } from '../src/lib/gtag'

export default class MyDocument extends Document {
  render() {
    return (
      <html lang="ja">
        <Head>
          {/* Google Analytics */}
          {existsGaId && (
            <>
              <script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} />
              <script
                dangerouslySetInnerHTML={{
                  __html: `
                  window.dataLayer = window.dataLayer || [];
                  function gtag(){dataLayer.push(arguments);}
                  gtag('js', new Date());
                  gtag('config', '${GA_ID}', {
                    page_path: window.location.pathname,
                  });`,
                }}
              />
            </>
          )}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}
```

### _app.tsxにPVをカウントするイベントを記述する
```tsx:app.tsx
import { AppProps } from 'next/app'
import '../styles/globals.scss'
import HeadCompo from '../components/domains/HeadCompo'
import React from 'react'
+ import usePageView from '../src/hooks/usePageView'

const App = ({ Component, pageProps }: AppProps) => {
+ usePageView()
  return (
    <>
      <HeadCompo />
      <Component {...pageProps} />
    </>
  )
}

export default App
```

### GAイベントをReactコンポーネントに設定する
```tsx
import React, { useState } from 'react'
import Link from 'next/link'
+ import * as gtag from '../../../src/lib/gtag'

const Profile: React.FC<Props> = () => {
  const ClickEvent = () => {
    gtag.event({
      action: 'click_event',
      category: 'link_button',
      label: 'event',
    })
  }

  return (
    <div>
	  <Link href="https://www.facebook.com/example">
	    <a target="_blank" 
+	    onClick={ClickEvent}>
	      <IconButton/>
	    </a>
	  </Link>
    </div>
  )
}

export default Profile
```

### TypeScript対応をする
```ts:next-env.d.ts
interface Window {
  // pageviewのため
  gtag(type: 'config', googleAnalyticsId: string, { page_path: string })
  // eventのため
  gtag(
    type: 'event',
    eventAction: string,
    fieldObject: {
      event_label: string
      event_category: string
      value?: string
    },
  )
}
```

## Analytics Debug Viewで確認する

### (1)localhost立上げ
```yarn dev```

### (2)Debug Viewの拡張機能を追加　ONに
https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna/support?hl=ja

![image (11).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/369162/e3a288b0-2fac-bb71-e028-f4a07f2bb36e.png)

![image (12).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/369162/d66df76c-5226-e4d9-b5a2-02d1a7c864c0.png)


このように出れば成功