How to Integrate Google Analytics into Your NextJS Application in 5 Easy Steps

How to Integrate Google Analytics into Your NextJS Application in 5 Easy Steps

ยท

1 min read

To add Google Analytics to your NextJS application, using NextJS third parties library, just follow these 5 easy steps:

  1. Log into your Google Account and create a new project on Google Analytics web page https://analytics.google.com

  2. Get your Google Measurement ID. It looks like this: "G-32J****23"

  3. Install NextJS third party library package: npm install @next/third-parties

  4. Import the GoogleTagManager component inside your Root layout

     import { GoogleTagManager } from '@next/third-parties/google'
    
     export default function RootLayout({
       children,
     }: {
       children: React.ReactNode
     }) {
       return (
         <html lang="en">
           <body>{children}</body>
           <GoogleTagManager gtmId="G-32J****23" />
         </html>
       )
     }
    
  5. Deploy.

To load Google Tag Manager for a single route, add the Google Tag Manager component to a single page. Like this:

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

export default function AboutPage() {
  return (
    <>
        <h1>About Us</h1>
        <GoogleTagManager gtmId="G-32J****23" />
    </>
  )
}

Now, your NextJS app is set up with Google Analytics for tracking and analyzing user interactions.

Happy Tracking ๐ŸŽ‰

Reference:

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

ย