Setting up Google Analytics within the NextJS 13 application directory

Has anyone successfully integrated Google Analytics 4 (gtag) in a NextJS 13 app directory? In my previous Vanilla JS / EJS applications, I simply added the following code to each page. My understanding is that this code sends a page_view event to Google Analytics on each page initialization.

<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 have come across similar blogs online, but none of them mention implementing a variable in the config. I have tried different approaches without success:

Prior to these attempts, I had already applied in next/script

  1. Putting this code in layout.tsx
  2. Putting this code in template.tsx
  3. Putting this code in page.tsx
  4. Putting this code in the first client-side component of each page
  5. Integrating gtag('js') and gtag('config') into one function like so, and calling 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 attempts only yield the same result: {foo: bar}, where bar remains constant unless the page is reloaded. For example, when I visit the home page for the first time, the page_view event has bar1. Navigating to page A still shows bar1. This persists across all pages until a reload occurs.

I have seen suggestions of using next/router for a workaround, but NextJS 13 does not include next/router, leaving me stuck. Can someone explain why this is happening?

Answer №1

Utilizing Google Analytics with Next app directory

/components/GoogleAnalytics.tsx

    "use client";
    
    import Script from "next/script";
    import * as gtag from "@/lib/gtag";
    
    const GoogleAnalyticsComponent = () => {
      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 GoogleAnalyticsComponent;

app/layout.tsx

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

lib/gtag.ts

    export const GA_TRACKING_ID: string | undefined = process.env.GA_TRACKING_ID;
    
    export const trackPageview = (url: string) => {
      (window as any).gtag("config", GA_TRACKING_ID, {
        page_path: url,
      });
    };
    
    export const sendEvent = ({
      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,
      });
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with website rendering and CSS/ReactJS on NextJS and Vercel deployment platform

Our team is currently testing out Vercel to deploy our new landing pages built with React & NextJS. While everything works fine locally (using yarn dev), we're encountering issues with CSS and React when deployed on Vercel. Here's how the pr ...

Discover the power of Next.js by creating URLs with the format domain.com/category/post

I'm struggling to grasp the concept of dynamic URL routing that fits my specific needs, especially since most examples I find only cover structures like: domain.com/categories/category1, domain.com/posts/post-1. As indicated by the title, what I reall ...

Having trouble getting React Next.js useEffect to work on the initial page render?

I'm working on a React project where I have multiple pages. My goal is to have all the filters cleared whenever I navigate to any page other than the 'Football' page. Currently, the filters are retained when I switch between non-Football pag ...

The 'jsx' property in tsconfig.json being overridden by Next.js and TypeScript

Is there a way to prevent NextJS from changing the 'jsx' property in my tsconfig.json file from 'react' to 'preserve' when running the development server? This is how my tsconfig.json file looks: "compilerOptions": { " ...

Passing props from a Next.js React page down to all of its child components

Is it feasible to pass all the page props to its child components without explicitly passing them as parameters? I am looking for a solution like this: export default function Home({ user }) { if (!user) { return ( <> <comp ...

What could be causing the SyntaxError message: "Cannot use import statement outside a module"?

I am attempting to incorporate the Google Calendar API into my NextJs application using the gapi-script (https://www.npmjs.com/package/gapi-script), but I encountered an error when importing the gapi-script: SyntaxError: Cannot use import statement outsi ...

Secure access with Next.js, next-auth, and backend with Node.js

Once a user is logged in on the frontend using next-auth and Next.js, my goal is to transmit the cookie generated by next-auth to the backend Node.js for validation before allowing the user to perform actions such as adding posts. The main objective is to ...

The Link tag in the Hero.jsx file of Next.js is malfunctioning and failing to redirect to the intended URL

Having a problem with the button in my Hero.jsx component, part of the Page.js implementation. The button uses a Link tag to redirect to the url.js page, but it's not working as expected and showing an Error 404 page instead. I'm new to Next.js s ...

Prevent Event Bubbling in Next.js for a Link Element within a Nested Component

I'm encountering an issue with clickable tiles on my site. These tiles have a button inside that should direct the user to an internal page, while clicking anywhere else on the tile should send them to an external page. However, I'm facing a prob ...

Attempting to convert undefined or null into an object presents an error in Next.js and React

An error message is currently being received stating Cannot convert undefined or null to object The data that the app is trying to retrieve is sourced from initial props. It appears that during the initial check, no data is found, leading to this error. ...

Setting up Scss and purgeCss configuration in Next.js custom postCSS configuration: A step-by-step guide

My current project is using Scss in combination with Bootstrap for design. I have implemented purgeCss to remove unused Css, and customized my postcss.config.js file as follows: module.exports = { plugins: [ "postcss-flexbugs-fixes", [ " ...

Having issues with NextJs app router and redux-toolkit not resetting to initial state after server-side rendering (SSR)

I am facing a challenge in my NextJs project with the app router and redux/toolkit for state management. When navigating from one page to another, the data fetched on the previous page remains in the redux state even though it wasn't fetched on the cu ...

Is the graphql codegen accurately generating the types?

I'm in the process of developing a basic Next.js application with TypeScript by integrating Strapi as a headless CMS. The main goal is to use Strapi and GraphQL, along with TypeScript, to display content on the Next.js app. Within Strapi, there is a ...

What are the best practices for setting access permissions when using Azure AD authorization flow?

I am in the process of creating a small Next.js application with the following structure: Authenticate a user via Azure AD using Next-Auth Allow the user to initiate a SQL Database Sync by clicking a button within the app with the access token obtained du ...

Is there a method I can use to merge similar functions in redux-toolkit?

Is there a way to streamline setting the cart state to true and others to false in one action? For example, if payload == "cart, true", then set cart to true and all other states to false. const initialState = { cart: false, addNewAddress: false, ad ...

What could be the reason behind Strapi v4 only displaying the initial 25 articles? Discussing Next.js and React

I've encountered a peculiar bug while working with Strapi v4. The technology stack being used is React and Next.js I've set up a dynamic pagination system with the format /page/[slug]. It's functioning almost perfectly, except for one majo ...

I'm having an issue with the Next.js Image component not functioning properly on the server

The issue with Next.js Image not working on the server but working fine on localhost has been puzzling me. My assumption was that it could be related to permissions, as I fetch images from a third-party domain. However, when I load images using a regular ...

What is the best way to deploy Material UI icons on Vercel?

I am currently in the process of deploying my website on Vercel. Everything is functioning properly on my localhost3000, however, when I attempt to deploy it on Vercel, I continuously receive the following error message: "Module not found: Can't resol ...

Troubleshooting in Next.js 13: Issue with module not being found while trying to reference a package containing CSS

Currently working with Next.js version 13.4.2 and I have included an npm package that comes with CSS styles and fonts. The issue arises when trying to utilize one of the CSS files within my application. In the layout.tsx file, I imported the CSS file as fo ...

Creating a 301 Redirect in NextJS on Vercel - Step by Step Guide

Is there a way to create 301 redirects from one URL to another in NextJS application hosted on Vercel? I attempted to implement custom express server using server.js file but the redirects only function locally. Upon further research, I discovered this me ...