Jonas Cardoso

Available

AuthorJonas Cardoso
Return

Integrating Google Analytics with Next.js 14

Before diving into integrating Google Analytics into your Next.js app, you'll need to establish a Google Analytics account and acquire a tracking ID. Once you've secured your tracking ID, you can proceed with the following steps.

Installing the Google Analytics Library

Next.js simplifies the integration of Google third-party libraries into your application using npm or yarn. Install the package, which offers a React-friendly interface for Google Analytics.

Terminal

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

Initializing your Google Analytics Tag

The GoogleTagManager component allows you to set up a Google Tag Manager container on your page. To ensure that Google Tag Manager is loaded for all routes, simply include the component directly within your root layout and provide your GTM container ID as a prop.

app/layout.tsx

import { GoogleTagManager } from '@next/third-parties/google'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleTagManager gtmId="GTM-XYZ" />
    </html>
  )
}

Verifying Your Google Analytics Setup

To verify that your Google Analytics setup is functioning correctly, navigate to the Realtime section of your Google Analytics dashboard. Once there, you should see your own visit to your website, navigate through your website, explore various pages, and confirm that page views and other metrics are being accurately recorded.

Published on 01/03/2024By Jonas Cardoso