How to implement Google Analytics with Next.js?
@naomi_cronin
To implement Google Analytics with Next.js, you can follow these steps:
Next.js provides a Head
component that allows you to modify the <head>
of your pages. You can use this component to add the Google Analytics script to your pages.
1
|
npm install react-ga |
1 2 3 4 5 6 7 8 9 10 |
import ReactGA from 'react-ga'; export function initGA() { ReactGA.initialize('UA-XXXXXXXXX-X'); // Replace with your Google Analytics tracking ID } export function logPageView() { ReactGA.set({ page: window.location.pathname }); ReactGA.pageview(window.location.pathname); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { useEffect } from 'react'; import { useRouter } from 'next/router'; import { initGA, logPageView } from '../analytics'; function MyApp({ Component, pageProps }) { const router = useRouter(); // Initialize Google Analytics on client-side useEffect(() => { if (!window.GA_INITIALIZED) { initGA(); window.GA_INITIALIZED = true; } logPageView(); }, [router.pathname]); return <Component {...pageProps} />; } export default MyApp; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import Head from 'next/head'; function Home() { return ( <div> <Head> <script async src="https://www.google-analytics.com/analytics.js" ></script> </Head> {/* Your page content */} </div> ); } export default Home; |
That's it! Now, Google Analytics should be implemented with your Next.js application. You can check the Real-Time reporting in your Google Analytics dashboard to verify if the tracking is working properly.