Next.jsプロジェクトにGoogle Analyticsを導入する
Typescript + Next.jsのプロジェクトにGoogle Analyticsを導入した。
公式サンプルを参考にしつつ、Typescript用に一部調整する必要があったので対応。
- lib/gtag.ts を追加
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_TRACKING_ID || ''
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url: string) => {
window.gtag('config', GA_TRACKING_ID, {
page_path: url,
})
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
type GaEventProps = {
action: string
category: string
label: string
value?: number
}
export const event = ({ action, category, label, value }: GaEventProps) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
})
}
- next-env.d.ts にgtag型定義を追加
/// <reference types="next" />
/// <reference types="next/types/global" />
interface Window {
gtag(type: 'config', googleAnalyticsId: string, { page_path: string })
gtag(
type: 'event',
eventAction: string,
fieldObject: {
event_label: string
event_category: string
value?: number
}
)
}
- pages/_document.tsx にgtag設定を追加
import Document, { DocumentContext, Head, Html, Main, NextScript } from 'next/document'
import React from 'react'
import { GA_TRACKING_ID } from '@/lib/gtag'
export default class MyDocument extends Document<WithNonceProp> {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
}
}
render() {
return (
<Html>
<Head nonce={nonce}>
<script
async={true}
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
- pages/_app.tsx にclient側でのページ遷移時にpageviewが発火されるようにuseEffectを追加
import { AppProps } from 'next/app'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import React from 'react'
import * as gtag from '@/lib/gtag'
function MyApp({ Component, pageProps }: AppProps): JSX.Element {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url: string) => {
gtag.pageview(url)
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
return <Component {...pageProps} />
}
export default MyApp
PageやComponent内で独自のGA Eventを発火させたい場合は↓のようにしてgtag.eventを呼び出せばOK。
import * as gtag from '@/lib/gtag
gtag.event({
action: 'some_action',
category: 'engagement',
label: 'Some',
})
これでNext.jsプロジェクトにGoogle Analyticsが導入できた。