jay tang
jay tang

Reputation: 21

Implementing Google Analytics in NextJS 13 app directory

Is there anyone who tried to implement Google Analytics 4 (gtag) in NextJS 13 app directory? In my previous Vanilla JS / EJS applications, I just need to add the following code to each of the page. So my understanding is, on each page initialization, this code would send a page_view event to google analytics.

<script> src={`https://www.googletagmanager.com/gtag/js?id=GAID`} <script>
<script>
   window.dataLayer = window.dataLayer || [];
   function gtag(){dataLayer.push(arguments);}
   gtag('js', new Date());
   gtag('config', 'GAID', {foo: bar}); // Where bar is a variable depending on the page
</script>

I found some similar blogs on the internet but there is no case implementing a variable in the config. I tried the following approaches but none succeeds.

Before doing these I applied in next/script already

  1. Put this code in layout.tsx
  2. Put this code in template.tsx
  3. Put this code in page.tsx
  4. Put this code in each of the first client side component of each page.
  5. Integrate gtag('js') and gtag('config') into one function like this and call window.configGA(bar) on the above pages.
<script> src={`https://www.googletagmanager.com/gtag/js?id=GAID`} <script>
<script>
   window.dataLayer = window.dataLayer || [];
   function gtag(){dataLayer.push(arguments);}
   function configGA(bar) {
       gtag('js', new Date());
       gtag('config', 'GAID', {foo: bar}); // Where bar is a variable depending on the page
   }
</script>

However, all of these trials only return me the same result: {foo: bar} where bar is the initial bar that the whole application is loaded. For example, when I first go to the home page, there is a page_view event with bar1. When I click the to page A, it still gives me bar1. Then whereever I go to, it gives me bar1 unless I reload the page.

I checked on the internet that people use next/router to work that around but there is no next/router in NextJS 13 so I was stuck there...

Anyone can explain why this is the case?

Upvotes: 2

Views: 2417

Answers (1)

Xavier G.
Xavier G.

Reputation: 21

My way to use Google Analytics with Next app directory

/components/GoogleAnalytics.tsx

    "use client";
    
    import Script from "next/script";
    import * as gtag from "@/lib/gtag";
    
    const GoogleAnalytics = () => {
      return (
        <>
          <Script
            strategy='afterInteractive'
            src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
          />
          <Script
            id='gtag-init'
            strategy='afterInteractive'
            dangerouslySetInnerHTML={{
              __html: `
                          window.dataLayer = window.dataLayer || [];
                          function gtag(){dataLayer.push(arguments);}
                          gtag('js', new Date());
                          gtag('config', '${gtag.GA_TRACKING_ID}', {
                          page_path: window.location.pathname,
                          });
                        `,
            }}
          />
        </>
      );
    };

    
    export default GoogleAnalytics;

app/layout.tsx

    import "@/styles/globals.css";
    import GoogleAnalytics from "@/components/GoogleAnalytics";
    
    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode;
    }) {
      return (
        <html lang='fr'>
          <body>
            <main>
                    <GoogleAnalytics />
                        {children}
                  </main>
          </body>
        </html>
      );
    }

lib/gtag.ts

    export const GA_TRACKING_ID: string | undefined = process.env.GA_TRACKING_ID;
    
    export const pageview = (url: string) => {
      (window as any).gtag("config", GA_TRACKING_ID, {
        page_path: url,
      });
    };
    
    export const event = ({
      action,
      category,
      label,
      value,
    }: {
      action: string;
      category: string;
      label: string;
      value: number;
    }) => {
      (window as any).gtag("event", action, {
        event_category: category,
        event_label: label,
        value: value,
      });
    };

Upvotes: 2

Related Questions