【最新】在Next.js中引入Google Analytics4(谷歌分析)

983 阅读1分钟

使用@next/third-parties/google

@next/third-parties提供的GoogleAnalytics组件,完成Google Analytics4接入

开始

安装 @next/third-parties 依赖:

npm install @next/third-parties@latest

@next/third-parties是一个Vercel官方开源的第三方程序集成库,可用于将第三方库加载到 Next.js 应用程序中,Google Analytics4就是其中之一。

除了谷歌分析之外还能接入Youtobe嵌入、谷歌地图等等

所有Google支持的第三方库都可以从@next/third-parties/ Google导入

如果你使用的是App路由

app/layout.tsx

import { GoogleTagManager } from '@next/third-parties/google'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleTagManager gtmId="GTM-XXXXXXXXXXX" />
    </html>
  )
}

如果你使用的是Page路由,或者单路由

import { GoogleTagManager } from '@next/third-parties/google'
 
export default function Page() {
  return <GoogleTagManager gtmId="GTM-XYZ" />
}

到这里,Google Analytics已经顺利接入,我们控制台检查或者查看源代码可以看到相关代码

image.png

发送事件

@next/third-parties/google提供了发送事件方法sendGAEvent

例如
app/layout.tsx

'use client'
 
import { sendGAEvent } from '@next/third-parties/google'
 
export function EventButton() {
  return (
    <div>
      <button
        onClick={() => sendGAEvent({ event: 'buttonClicked', value: 'xyz' })}
      >
        Send Event
      </button>
    </div>
  )
}

由此,我们完成了Google分析的接入和事件发送