Using Google Analytics with React/Next.js Projects
@shaaddevDon't mind me here, I am only creating a quick note.
- Create your own Google Analytics Project
If you haven't done this part before, it as simple as signing up on the Google Analytics page, see link below:
Google Analytics for Developers
- Create your Google Analytics Component
Inside of your components
folder, create a file called google-analytics.tsx
, and add the following:
import React from "react";
import Script from "next/script";
export function GoogleAnalytics() {
return (
<>
<Script
strategy="lazyOnload"
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
/>
<Script id="" strategy="lazyOnload">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_MEASUREMENT_ID}', {
page_path: window.location.pathname,
});
`}
</Script>
</>
);
}
- Add the secrets into your
.env.local
file
# Google Analytics
NEXT_PUBLIC_GA_ID=your_google_analytics_key
NEXT_PUBLIC_MEASUREMENT_ID=your_google_analytics_key
- Add the component to your global component
Inside of app
folder, look for the file that says layout.tsx
and import the component like so:
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { GoogleAnalytics } from "@/components/google-analytics";
const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${inter.variable} antialiased`}>
<main>
{children}
// other necessary components
</main>
<GoogleAnalytics />
</body>
</html>
);
}
El fin. :)