跳到内容
文档错误在 Next.js 中使用 Google Analytics(通过 `next/script`)

在 Next.js 中使用 Google Analytics(通过 `next/script`)

使用 Google Analytics 的内联脚本时,优先使用 next/script 组件。

此错误发生的原因

以前,Google Analytics 曾使用内联脚本,这可能会影响您网页的性能。现在,我们建议通过 `@next/third-parties` 库使用 next/script

可能的解决方法

使用 @next/third-parties 添加 Google Analytics

@next/third-parties 是一个库,它提供了一系列组件和实用程序,可以提高您的 Next.js 应用程序加载流行的第三方库的性能和开发体验。它与 Next.js 14 一起提供(安装 next@latest)。

GoogleAnalytics 组件可用于通过 Google 代码 (gtag.js) 将 Google Analytics 4 包含到您的页面中。默认情况下,它在页面水合后获取原始脚本。

建议:如果您的应用程序中已经包含了 Google 跟踪代码管理器,您可以直接使用它配置 Google Analytics,而不是将 Google Analytics 作为单独的组件包含进来。请参阅 文档,了解有关跟踪代码管理器和 gtag.js 之间差异的更多信息。

要为所有路由加载 Google Analytics,请将组件直接包含在您的根布局中并传入您的衡量 ID

app/layout.tsx
import { GoogleAnalytics } from '@next/third-parties/google'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleAnalytics gaId="G-XYZ" />
    </html>
  )
}

要为单个路由加载 Google Analytics,请将组件包含在您的页面文件中

app/page.js
import { GoogleAnalytics } from '@next/third-parties/google'
 
export default function Page() {
  return <GoogleAnalytics gaId="G-XYZ" />
}

须知

  • 如果您使用的是 Pages Router,请参阅pages/ 文档
  • @next/third-parties 还支持Google 标签管理器和其他第三方。
  • 不强制要求使用 @next/third-parties。您也可以直接使用 next/script 组件。请参阅next/script 文档以了解更多信息。