Google Analytics 4

60-90 minAdvanced

Set up Google Analytics 4 (GA4) tracking in Next.js applications.

Prerequisites

  • GA4 Measurement ID (G-XXXXXXX)
Beginner Recommended

Next.js Third Parties

Official library.

1

GoogleAnalytics Component

1

Install @next/third-parties if not already installed.

2

Add <GoogleAnalytics> to your root layout.

Example
import { GoogleAnalytics } from '@next/third-parties/google'

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleAnalytics gaId="G-XYZ" />
    </html>
  )
}
2

Sending Events

1

Use sendGAEvent to track custom user interactions.

Example
import { sendGAEvent } from '@next/third-parties/google'

<button
  onClick={() => sendGAEvent({ event: 'buttonClicked', value: 'xyz' })}
>
  Click me
</button>

Verification Checklist

  • Check the Realtime report in your Google Analytics dashboard.
  • Verify requests to google-analytics.com in the Network tab.