Install Google Analytics Library

npm install @next/third-parties@latest

Configure Your Environment Variable

Ensure your GA4 Measurement ID is set in your .env.local file:

NEXT_PUBLIC_GA_ID=G-XXXXXXXXXX

Update pages/_app.tsx

Import and place the <GoogleAnalytics /> component directly inside your custom _app.tsx file.

import type { AppProps } from 'next/app';
import { GoogleAnalytics } from '@next/third-parties/google';
import '@/styles/globals.css'; // Your global styles

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GA_ID ?? ""} />
    </>
  );
}

Optional: Custom Events in Pages Router

You can trigger custom events anywhere in your components using the same sendGAEvent function:

import { FormEvent } from 'react';
import { sendGAEvent } from '@next/third-parties/google';

export default function ContactForm() {
  
  // 1. Create a combined handler function
  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault(); // Prevents page reload if using an actual HTML <form>

    try {
      // 2. Do your other application logic first (e.g., API call)
      const response = await fetch('/api/contact', {
        method: 'POST',
        body: JSON.stringify({ message: "Hello" }),
      });

      if (response.ok) {
        // 3. Send event to GA only after a successful form submission
        sendGAEvent({ 
          event: 'form_submit_success', 
          value: 'contact_page' 
        });

        // 4. Run any UI updates (e.g., redirect user or clear input)
        alert('Message sent successfully!');
      }
    } catch (error) {
      // Optional: Track errors in GA to debug form drops
      sendGAEvent({ 
        event: 'form_submit_error', 
        value: 'network_failure' 
      });
      console.error(error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Your form inputs go here */}
      <button type="submit">Submit Form</button>
    </form>
  );
}

References