How to Integrate Google Analytics in NextJS Simple way

How to Integrate Google Analytics in NextJS Simple way

Looking to add Google Analytics to your Next.js project? With @next/third-parties, the process is simpler than ever. This library offers a collection of components and utilities designed to enhance performance and streamline the integration of popular third-party libraries, including Google services.

Getting Started
To begin, install the @next/third-parties library by running the following command in your terminal:

npm install @next/third-parties@latest next@latest

Note: @next/third-parties is currently an experimental library, so we recommend installing it with the latest or canary flags for the most up-to-date features and improvements.

Google Analytics

Integrate Google Analytics 4 into your Next.js application with ease using the GoogleAnalytics component. Simply include this component in your layout or pages and specify your measurement ID:

// file location: src/app/layout.tsx
import { GoogleAnalytics } from '@next/third-parties/google';
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <GoogleAnalytics gaId="G-XYZ" />
      <body>{children}</body>
    </html>
  );
}

Sending Events and Tracking Pageviews

Utilize the sendGAEvent function to measure user interactions and track pageviews with Google Analytics. Ensure that the GoogleAnalytics component is included in your layout or page to utilize these features effectively. By following these simplified steps, you can seamlessly integrate Google Analytics into your Next.js project and gain valuable insights into user behavior and website performance.

'use client'
 // page.tsx
import { sendGAEvent } from '@next/third-parties/google'
 
export function EventButton() {
  return (
    <div>
      <button
        onClick={() => sendGAEvent({ event: 'buttonClicked', value: 'xyz' })}
      >
        Send Event
      </button>
    </div>
  )
}
  • #NextJS
  • #Analytics