Here's the complete Google Analytics (gtag) code for you to use:
1. Google Analytics Component (components/google-analytics.tsx):
import Script from "next/script"
const GA_TRACKING_ID = "G-5JK3VVMYPJ" // Replace with your actual GA ID
export function GoogleAnalytics() {
return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}');
`}
</Script>
</>
)
}2. Add to your layout.tsx:
import { GoogleAnalytics } from "@/components/google-analytics"
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<GoogleAnalytics />
{children}
</body>
</html>
)
}3. For plain HTML/non-Next.js sites, add this to your <head> tag:
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-5JK3VVMYPJ"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-5JK3VVMYPJ');
</script>Replace G-5JK3VVMYPJ with your actual Google Analytics Measurement ID from your Google Analytics account. You can find this in Google Analytics > Admin > Data Streams > Your Web Stream.
Done! I've updated the Google Analytics tracking ID to G-2LVQCKRKRF. Your website will now track all page views and send data to your Google Analytics account with this measurement ID. The gtag is integrated in the layout and will load automatically on every page.