Marco Mesen profile picture

Add Google Analytics to Next.js v15 (2025) in less than 5 minutes

https://www.datocms-assets.com/41568/1740761637-nextjs-and-google-analytics.png?auto=format&fit=fill

Introduction

When I discovered how easy it is to add Google Analytics to Next.js 15 using @next/third-parties, I knew I had to share it. Not only is this package officially supported by Next.js, but it’s also optimized for performance, making it the best way to integrate GA without hassle. With just a few lines of code, you get a fully functional analytics setup, without worrying about manual script management or performance issues. Let's dive in!

1. Get Your Google Analytics Measurement ID

First, head over to Google Analytics and:

  • Create a new GA4 property if you don’t have one.

  • Go to Admin > Data Streams and grab your Measurement ID (it looks like G-XXXXXXXXXX).

2. Install @next/third-parties/google

Next.js 15 introduces official support for third-party integrations like Google Analytics with @next/third-parties/google. This package makes it even easier to integrate GA.

yarn add @next/third-parties

3. Add GA to layout.tsx

Since Next.js 15 uses the App Router, the best place to add Google Analytics is in app/layout.tsx.

Here’s how to do it:

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

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
      </body>
      <GoogleAnalytics
        gaId={process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS ?? ''}
        debugMode={process.env.NODE_ENV === 'development'}
      />
    </html>
  );
}

4. That's it!

You’ve successfully integrated Google Analytics into your Next.js 15 app using @next/third-parties. Now, you can track your visitors and gain insights into how they interact with your site.

Now, sit back and watch the analytics roll in! 📊🔥

NextJs documentation: https://nextjs.org/docs/app/building-your-application/optimizing/third-party-libraries

Happy coding! 😃