Skip to content

Next.js 中添加 Google Analytics 最佳实践

google-analytics


google-analytics.tsx
"use client";
import Script from "next/script";
import * as gtag from "@/lib/gtag";
const GoogleAnalytics = () => {
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gtag.GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
);
};
export default GoogleAnalytics;

lib/gtag.ts
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GOOGLE_ID
export const pageview = (url: string) => {
window.gtag("config", GA_TRACKING_ID, {
page_path: url,
})
}
export const event = ({ action, category, label, value }:any) => {
window.gtag("event", action, {
event_category: category,
event_label: label,
value: value,
})
}
types/index.d.ts
interface Window {
gtag: (...args: any[]) => void;
}
.env
NEXT_PUBLIC_GOOGLE_ID=

layout.tsx
export const runtime = "nodejs";
import type { Metadata } from "next";
import "./globals.css";
import { RootProvider } from 'fumadocs-ui/provider';
import GoogleAnalytics from "@/components/google-analytics";
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body>
<GoogleAnalytics />
<RootProvider>
{children}
</RootProvider>
</body>
</html>
);
}

谷歌分析