以下是將 Google Analytics 4 添加到基於 Next.js 的網站的步驟。

首先,創建一個 Google Analytics 屬性,並將屬性 ID 保存在 NEXT_PUBLIC_GOOGLE_ANALYTICS 環境變量中。

然後,在 pages/_app.js 文件中添加一個 useEffect() 調用,其代碼如下:

import '/public/style.css'

function MyApp({ Component, pageProps }) {
    return <Component {...pageProps} />
}

修改它為:

import { useEffect } from 'react'
import { useRouter } from 'next/router'

import 'tailwindcss/tailwind.css'
import '/public/style.css'

function MyApp({ Component, pageProps }) {
    const router = useRouter()

    useEffect(() => {
        const handleRouteChange = url => {
            window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
                page_path: url,
            })
        }
        router.events.on('routeChangeComplete', handleRouteChange)
        return () => {
            router.events.off('routeChangeComplete', handleRouteChange)
        }
    }, [router.events])

    return <Component {...pageProps} />
}

export default MyApp

最後,添加一個 pages/_document.js 文件,創建一個 Next.js 自定義文檔,並注入 Google Analytics 腳本,代碼如下:

import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
    render() {
        return (
            <Html>
                <Head>
                    <script
                        async
                        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
                    />
                    <script
                        dangerouslySetInnerHTML={{
                            __html: `
                                window.dataLayer = window.dataLayer || [];
                                function gtag(){dataLayer.push(arguments);}
                                gtag('js', new Date());
                                gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
                                    page_path: window.location.pathname,
                                });
                            `,
                        }}
                    />
                </Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        )
    }
}

注意:解決方案來自 Marie Starck 在 https://mariestarck.com/add-google-analytics-to-your-next-js-application-in-5-easy-steps/ 上的文章。