How to Integrate Google Analytics into Your NextJS Application in 5 Easy Steps
To add Google Analytics to your NextJS application, using NextJS third parties library, just follow these 5 easy steps:
Log into your Google Account and create a new project on Google Analytics web page https://analytics.google.com
Get your Google Measurement ID. It looks like this: "G-32J****23"
Install NextJS third party library package:
npm install @next/third-parties
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> ) }
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