跳至內容
文件錯誤使用 Google Analytics 與 Next.js (透過 `next/script`)

使用 Google Analytics 與 Next.js (透過 `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 加入您的頁面。預設情況下,它會在頁面上發生 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 文件以了解更多資訊。