How to Integrate Google Analytics and Other Third-Party Services in Next.js?
Integrate Google Analytics and Google Tag Manager in Next JS.
Table of contents
In this article, we will learn how to integrate Google Analytics and Google Tag Manager into a Next.js application in an optimized and recommended way as suggested by Next.js.
A. Integrate Google Analytics via @next/third-parties/google
Step 1 : Install required dependency @next/third-parties/google.
npm install @next/third-parties/google
Step 2: Get your Google Analytics ID which you will find in the dashboard of Google Analytics, Login your Google Analytics Account and go to dashboard.Take your Measurement ID G - XXXXXXXXXX
.
Step 3: Open your layout.tsx
and import the provided dependency in your
import { GoogleAnalytics } from '@next/third-parties/google'
Step 4: Inside the HTML Tag of Root Layout add <GoogleAnalytics gaId=’Measurement ID’/>
with measure ID which you imported before so that it will activate analytics over your application.
Example - Added an Code Snippet of Layout.tsx
for easy understanding of
import type { Metadata } from "next";
import localFont from "next/font/local";
import "./globals.css";
import { GoogleAnalytics } from '@next/third-parties/google'
const geistSans = localFont({
src: "./fonts/GeistVF.woff",
variable: "--font-geist-sans",
weight: "100 900",
});
const geistMono = localFont({
src: "./fonts/GeistMonoVF.woff",
variable: "--font-geist-mono",
weight: "100 900",
});
export const metadata: Metadata = {
title: {
default:"Home | Pratham Saxena",
template:"%s | Pratham",
},
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<GoogleAnalytics gaId={'G-XXXXXXXXXX'}/>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}