Analytics
Implementing Google Analytics 4 (gtag) in Next.js App Router
Arun Tyagi
September 13, 2025
6 min read
#GA4#Analytics#Next.js#gtag
Why GA4 with Next.js?
Google Analytics 4 provides more flexible event-based tracking. With the Next.js App Router, we can inject the gtag
script once in the root layout and reliably track route changes.
1) Add the gtag Script in app/layout.tsx
Place the gtag script in <head>
and initialize it with your measurement ID. Avoid adding it in individual pages.
2) Track Route Changes
Next.js App Router triggers client-side navigations. GA4 captures pageviews automatically when the config
is set, but for advanced tracking you can dispatch custom events:
gtag('event', 'page_view', { page_location: window.location.href });
3) Best Practices
- Use a single source of truth for your measurement ID via environment variables
- Avoid duplicate tags (do not include both GTM and GA4 unless you manage via GTM only)
- Respect user consent and privacy requirements
Conclusion
With a clean layout-level integration, GA4 will track your pages and enable deeper analytics without cluttering your codebase.