跳至內容
文件錯誤在 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 Google Analytics 4 納入您的頁面。預設情況下,它會在頁面完成 hydration 後擷取原始指令碼。

建議:如果您的應用程式中已經包含 Google Tag Manager,您可以直接使用它來設定 Google Analytics,而不是將 Google Analytics 作為一個獨立的元件包含進來。請參閱文件以瞭解更多關於 Tag Manager 和 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 Tag Manager 和其他第三方服務。
  • 並非一定要使用 @next/third-parties。您也可以直接使用 next/script 元件。參考 next/script 文件 以了解更多資訊。