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

Issue: Experiencing multiple re-renders when attempting to send a post request to the backend using

export default function CRouter() { const [token, setToken] = useLocalStorage('auth', '') const [user, setUser] = useState(false); const GetUser = () => { if (token !== "" && !user) { axios.post(&apo ...

Frontend unable to fetch cookie from backend (ExpressJS using Passport authentication with PostgreSQL database)

I've been stuck on this issue for quite some time now. My setup includes a NextJS frontend running on localhost:3000 and an ExpressJS backend running on localhost:3001. The problem arises when I try to implement a login flow. I send an axios login re ...

Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure. I need a way to navigate between these objects by following the array and then back again. What would be the most ...

Using Vue.js watchers can sometimes cause an endless loop

I'm working on a unique aspect ratio calculator. How can I ensure my code doesn't get stuck in an endless loop when dealing with 4 variables that are dependent on each other? To address this, I implemented 4 watchers, each monitoring a specific ...

The compatibility issue between jQuery Tabs and Sliding effect

Hey there, I'm currently working on a website that requires a vertical tab system. I also have an arrow image that shows which tab or thumbnail the user has selected, and it should smoothly slide between the two thumbnails. You can check out the pro ...

Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link ...

Tips for setting multiple states simultaneously using the useState hook

Exploring the use of multiple states handled simultaneously with the useState hook, let's consider an example where text updates based on user input: const {useState} = React; const Example = ({title}) => { const initialState = { name: &a ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Information not reaching the server from the form

Whenever a user clicks on a button within the search results of a query, a form pops up in a modal. This form consists of three input fields and additional fields that are added to it through ajax when the submit button is clicked. In my Django application ...

Enhancing Element Generation and Data Association through jQuery

Currently, I am seeking a more streamlined approach to generate DOM alterations and update the object within .data(). At the moment, data is being supplied in an array of objects. I construct strings piecemeal, appending them to the table body, and affixi ...

Stop allowing the entry of zero after a minus sign

One of the features on our platform allows users to input a number that will be automatically converted to have a negative sign. However, we want to ensure that users are unable to manually add a negative sign themselves. We need to find a solution to pre ...

Unable to modify the color of the alert notification in JavaScript using React

I've been attempting to create an alert component, but I'm facing an issue with adjusting the color of the alert message. Upon enabling dark mode in the navbar (located at the bottom of the navbar component code), an alert message confirming the ...

Mongoose Alert Utility Directive

const mongoose = require('mongoose'); module.exports = { init: () => { const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false, reconnectTries: Number.MA ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Encountering an Express.js HTTP 500 ERROR when using res.send("Some text"); is working on the page, however, the error occurs when trying to use res.render('file');

My website has a page located at /request that features a form. The form's method is POST and the action leads to /request. In the POST handler in request.js, the intention is to take action with the form data, like storing it in a database, and then ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

JavaScript Filtering Technique

Attempting to compose an array of names for a search output page The json arrangement looks like this: data = { "artists": [ { "artistName": "a" }, { "artistName": "b" }, { "artistName": "c" }, { "artistName": "d" }, { "artistName" ...

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

What is the best way to make a bootstrap component (container) stretch to the full width and height of the window when it first loads, and which

I am looking to achieve something similar to the design on a certain website: The goal is to have a container with a background and a form inside that resizes proportionally based on the size of the window it is opened in. The resizing should be smooth an ...