Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Google Analytics with NextJS 13?

//GoogleAnalytics.tsx

"use client";
import Script from "next/script";

const GoogleAnalytics = ({ GA_TRACKING_ID }: { GA_TRACKING_ID: string }) => {
  return (
    <>
      <Script
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
        strategy="afterInteractive"
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
        window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', ${GA_TRACKING_ID});
        `}
      </Script>
    </>
  );
};

export default GoogleAnalytics;
//layout.tsx

import GoogleAnalytics from "@/components/molecules/GoogleAnalytics";
import { ReactNode } from "react";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <GoogleAnalytics GA_TRACKING_ID={process.env.GA_TRACKING_ID} />
      <body>      
        {children}
      </body>
    </html>
  );
}

With this code, the script tags are properly filled with my ID G-XXXXXXX. scripts tags

However, I get a "G is not defined" error in browser console when loading the page.

VM689:6 Uncaught ReferenceError: G is not defined
    at <anonymous>:6:26
    at loadScript (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/[email protected]_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/client/script.js:91:19)
    at eval (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/[email protected]_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/client/script.js:182:17)
    at commitHookEffectListMount (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/[email protected]_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:26416:26)

I have already tried placing GoogleAnalytics tag in the body, and also in the head.tsx. Same error.

like image 698
Flavien Laureau Avatar asked Sep 12 '25 06:09

Flavien Laureau


1 Answers

I found what "G is not defined" stands for. G is actually the first letter of the tracking ID. By using template strings here, I didn't realize that the final code was wrong. I am not importing a string here, but literally the tracking ID which is therefore considered a variable. enter image description here

To solve the problem, I simply added quotes :

gtag('config', '${GA_TRACKING_ID}');
like image 54
Flavien Laureau Avatar answered Sep 16 '25 08:09

Flavien Laureau