Add Google Analytics 4 (GA4) to your Next.js app — without breaking performance, respecting GDPR consent, and tracking page views correctly with the App Router.
In this guide
Go to analytics.google.com → Admin → Create Property → GA4. Add your website URL. Go to Data Streams → Web → Add stream → enter your URL. You will get a Measurement ID that starts with G- (e.g., G-XXXXXXXXXX). Store it as NEXT_PUBLIC_GA_MEASUREMENT_ID in your .env. It must be prefixed with NEXT_PUBLIC_ to be accessible in the browser.
In your root layout: import Script from "next/script"; then add inside <body>: <Script src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}`} strategy="afterInteractive" /> <Script id="ga-init" strategy="afterInteractive">{`window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag("js", new Date()); gtag("config", "${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}");`}</Script>. The afterInteractive strategy loads after hydration, avoiding performance impact.
The App Router does not trigger page view events automatically on client-side navigation. Create a client component that uses the usePathname hook: "use client"; import { usePathname } from "next/navigation"; import { useEffect } from "react"; export function Analytics() { const pathname = usePathname(); useEffect(() => { gtag("event", "page_view", { page_path: pathname }); }, [pathname]); return null; }. Add <Analytics /> to your root layout.
Track meaningful user actions: gtag("event", "book_call_click", { event_category: "conversion", event_label: "hero_cta" }). In GA4, go to Reports → Engagement → Events to see your custom events. Create Conversions in GA4 Admin → Events → Mark as conversion for events that represent goal completions (form submission, booking confirmed, payment completed). These show in Conversions reports and can be used for Google Ads optimization.
In the EU, loading GA before cookie consent violates GDPR. Gate the script behind consent: only render the Script components after the user accepts analytics cookies. Store consent in localStorage (cookieConsent: true/false). Use the GA4 consent mode API to anonymize data by default and fully activate after consent: gtag("consent", "default", { analytics_storage: "denied" }) — then gtag("consent", "update", { analytics_storage: "granted" }) after acceptance.
Need Help?
Our engineering team handles implementations like this every week. Get a free scoping call — we will tell you exactly what it takes and what it costs.
Book a free callCompetitive Intelligence
Efficiency Modeling
© 2026 NexWorldTech — Built for Global Dominance.