Harnessing the Power of Google Tag Script in Next.js

After researching How to load Google Tag Manager with the next/script component (Next.js 11) and reviewing this documentation page, my issue remains unresolved.

I am looking to implement Google Tag on multiple websites developed using nextjs, so I created a basic reusable component:

import Script from 'next/script'

const GoogleTag = ({ identifier }) => {
    if (!identifier || !identifier.startsWith('G-')) {
        throw new Error('Google tag id is not correct;');
    }
    return <>
        <Script
            src={`https://www.googletagmanager.com/gtag/js?id=${identifier}`}
            strategy="afterInteractive"
        />
        <Script id="google-analytics" strategy="afterInteractive">
            {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){window.dataLayer.push(arguments);}
          gtag('js', new Date());

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

export default GoogleTag;

In each of my sites, I utilize this component in the _app.js file as follows:

import Head from 'next/head';
import GoogleTag from '../Base/GoogleTag';

export default function MyApp({ Component, pageProps }) {

return (
        <>
            <Head>
                <GoogleTag identifier='G-9XLT855ZE0' />
            </Head>
            <div>
                Application code goes here.
            </div>
        </>
    )
}

Despite these efforts, I have noticed that the Google Tag script does not appear to be loaded in Chrome's Dev Tools under the Networks tab.

Answer №1

If you want to utilize the Google Tag in your Next.js application effectively, it's essential to insert the GTM script into _document.js within the Head section.

For a sample code snippet for _document.js, check out the source link.

import Document, { Html, Head, Main, NextScript } from 'next/document'

import { GA_TRACKING_ID } from '../lib/gtag'

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

To implement Google Analytics page view for a single-page app and explore alternative methods of integrating GT in Next.js, refer to these resources: Source1, Source2.

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

After closing and reopening the jQuery modal, the name does not appear

I crafted a custom modal window to display images along with comments and the owner's name. The issue arises when I close the current modal and reopen it; the owner's name disappears. Oddly enough, the name is displayed the first time the modal i ...

Encountering a code ELIFECYCLE error when running npm run dev

In my current project, I am utilizing the nextjs framework along with various npm package modules. Initially, everything was working smoothly during development. However, upon restarting the application using the command npm run dev, I encountered an error ...

How can I transfer a selected value from a unique dropdown component to react-hook-form?

I am utilizing react-hook-form for form validation in this Gatsby project. However, my dropdown component is not a <select> tag but a customized component created with divs and an unordered list. This design choice was made to meet our specific custo ...

Why doesn't jQuery ajax work when sourcing the URL from a variable but works with a hard-coded URL?

During my experimentation with setting and getting the URL for a jQuery Ajax (post) call, I realized the value of dynamically setting the destination URL for the request. Here's how I attempted to achieve this: To set the URL to 'store.php' ...

Using callback functions to initiate server actions

Currently, I am diving into server actions within the Next.js 14 app router. Server actions are mainly used for making post requests to the server. But, I am curious if there is a way for server actions to trigger a function on the client side. My goal is ...

Operating a React application in the background

Being a novice in the world of deploying front-end code, I have encountered a challenging situation that requires assistance. I am currently working on a React App that needs to be operated as a background process. However, I'm facing some confusion r ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

Having trouble with error handling in Js Node Selenium Try-Catch? Let's troubleshoot

My goal is to simulate the action of clicking on an element that is displayed after a specific iteration of document.readyState = 'complete'. To overcome the readyState issue, I considered using try-catch with the executeScript command to keep re ...

Trouble with Add To Cart feature in React app due to issues with Context API

I have been following a tutorial located here. I followed the steps exactly and even checked the code on the related github repository, which matches. However, when I try to add a product to the cart by clicking the button, the state does not update. In Re ...

Managing form submissions using Material UI and Next.js

Can someone provide insights on using Material UI with Next Js? I am experimenting with a Login template from Material UI, but I am facing an issue where query params are added to the URL upon Submit. For example: localhost:3000/auth/login changes to: ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

Creating a Dynamic Dependent Dropdown with Jquery and Ajax in PHP

As a newbie in coding, I stumbled upon some valuable information to enhance my register form using Ajax. While the PHP files seem to be functioning correctly, I suspect that the JS file is not performing as expected. In the register form, you'll find ...

Step-by-step guide for dynamically including dropdown options

Is there a way to dynamically add a dropdown using JavaScript? I currently have a dropdown with numbers that creates another dropdown when selected. However, I want to add the dynamic dropdown through JavaScript. How can I achieve this? Below is the PHP ...

Communication through HTTP requests is not supported between docker containers

I currently have two applications running as services within a docker-compose environment. My React App A Node.js server In an attempt to make an HTTP request from my React app to the Node.js server, I am using: fetch("http://backend:4000/") However, w ...

Error: express is missing a closing parenthesis for the argument list

When running this code in the VS Code terminal, be sure to verify any errors that may occur. var express = require('express'); var app = express(); app.get('/', function(request, response) { response.send("hello world"); }); app.li ...

Use jQuery to retrieve the number of items that have been selected in an ASP ListBox

Struggling to find a way to calculate the count of selected items from an ASP listbox using jQuery. Currently, encountering an issue where I am receiving "Cannot get property length of undefined or null reference" on the selectedOptions property. The var l ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

How can I implement jQuery autocomplete with customized settings?

In my Drupal project, I am looking to implement jQuery's auto complete feature to search for nodes based on their titles. I am having trouble finding examples that align with my specific requirements: The URL structure should be: /api/node/title/{wh ...