在 Next.js 14 项目中集成 Google Analytics 的完整指南
2024-07-03
本文介绍了如何在 Next.js 14 项目中通过安装依赖、配置 `app/layout.tsx` 和 `next.config.js` 文件来集成 Google Analytics。
1. 安装依赖
首先,安装必要的依赖包:
npm install @vercel/analytics @next/third-parties
2. 配置 app/layout.tsx
或 app/layout.js
在你的 app
目录下的 layout.tsx
或 layout.js
文件中引入 Google Analytics 组件,并配置 GA ID。
import "./globals.css"; import { Inter } from "next/font/google"; import type { Metadata } from "next"; import { Analytics } from "@vercel/analytics/react"; import { GoogleAnalytics } from "@next/third-parties/google"; const inter = Inter({ subsets: ["latin"] }); export const metadata: Metadata = { metadataBase: new URL("https://chromeai.org"), title: "Chrome Built-In AI Gemini Nano Test Page", description: "Run Chrome built-in large language model AI locally in your browser.", keywords: [ "chrome", "built-in", "chrome built-in", "chrome built-in ai", "chrome gemini", "chrome ai", "chrome gemini nano", "native AI", "chrome AI", "built-in AI", "on-device AI", "window AI", ], openGraph: { type: "website", url: "https://chromeai.org", title: "Chrome Built-In AI Gemini Nano Test Page", description: "Run Chrome built-in large language model AI locally in your browser.", siteName: "Chrome Built-In AI Gemini Nano Test Page", images: [ { url: "https://aqaya8xrbp4jczd0.public.blob.vercel-storage.com/og-image-1200x630%20(1)-sVlNmUM0XYOX7EP81AqvQT3tzCgF8D.jpg", }, ], }, }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={inter.className}> {children} <Analytics /> <GoogleAnalytics gaId="YOUR_GA_ID" /> </body> </html> ); }
将 YOUR_GA_ID
替换为你的 Google Analytics ID。
3. 配置 next.config.js
确保在 next.config.js
文件中配置好你的域名:
module.exports = { reactStrictMode: true, async rewrites() { return [ { source: "/script.js", destination: "https://plausible.io/js/plausible.js", }, ]; }, };