Adding Google Tag Manager to a NextJS TypeScript project can be tricky, especially when encountering the error message "window.dataLayer is not

I am currently setting up GTM on my website, but I am facing a challenge as my NextJS project is in Typescript. I followed the example on Github provided by Vercel, but I encountered this error: TypeError: window.dataLayer is not a function

Below is the content of my gtm.js file:

export const GTM_ID = process.env.TAG_MANAGER

export const pageview = (url) => {
  window.dataLayer({
    event: 'pageview',
    page: url,
  })
}

Yes, my GTM is in JavaScript, while the rest of my project is in TypeScript (ts/tsx).

My _app.tsx and my _document.tsx files are identical to the example provided by Vercel. I have created the necessary components and the .env file with the ID.

Everything seems to be in place based on the example, so this issue is puzzling.

EDIT

I made some changes:

My _document.tsx:

import Document, { DocumentContext, DocumentInitialProps, Head, Html, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
import favicon from '../assets/favicon.ico'
import { GA_TRACKING_ID } from '../lib/gtag'
import { GTM_ID } from '../lib/gtm'

// Code for _document.tsx continues...

My _app.tsx:

import { AppProps } from 'next/app'
import GlobalStyles  from '../styles/GlobalStyles'
import dynamic from 'next/dynamic'
import { traducao } from '../translate/index'
import { useRouter, Router } from "next/router"
import * as gtag from '../lib/gtag'
import { GTMPageView } from '../lib/gtm'
import React, { useEffect } from 'react';

// Code for _app.tsx continues...

My new gtm.ts:

export const GTM_ID = process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID

// Code for gtm.ts continues...

WORKED WELL

However, I am unsure if it is fully functional on GTM since my website is still under development (localhost)...

The window.dataLayer script error has been resolved, but my Lighthouse report now shows some Google best practices errors.

Answer №1

If you're looking to streamline your life, consider utilizing the React Google Tag Manager bundle.

https://github.com/alinemorelli/react-gtm

Implementing it is a breeze:

Simply integrate the following code snippet within the function component definition of your _app.js file

React.useEffect(() => {

    if (typeof window !== 'undefined') {
      console.log("init GTM")
      TagManager.initialize({ gtmId: 'YOUR_GTM_ID' });
    } else {
      console.log("GTM server side - ignorning")
    }

}, [])

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

Transformation of Python code into Blockly blocks

As the founder of edublocks.org, I am interested in adding Python to Blocks functionality on the platform. At the moment, users can only transition from Blocks to Python. Is there anyone who has experience with this and can provide guidance on how to achi ...

Tips for receiving a linter/compiler warning when comparing a function without its call being made?

Often, I find myself making a common mistake when writing TypeScript code: class Foo { constructor() { } public get isFoo(): boolean { return true; } // getter public isBar(): boolean { return false; } // normal function } let foo = new Foo(); if ( ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Troubleshooting a Problem with AppCheck Firebase reCaptcha Configuration

Currently integrating Firebase with my Next.js project. I've been attempting to configure AppCheck reCaptcha following the documentation and some recommendations, but I encounter an issue when running yarn build The build process fails with the foll ...

Automating the process of rewirting git commit messages on a branch using Git

Is there a way to automate the rewriting of commit messages containing a specific substring on a particular branch? For example, in a repository like this: https://i.sstatic.net/3e4bW.png I want to modify all commit messages on the mybranch branch (not o ...

Exploring Node Stream.Writable Extension in Typescript 4.8

I'm attempting to craft a basic class that implements Node stream.Writable, but it seems like I can't quite grasp the correct syntax - the compiler keeps throwing errors: https://i.stack.imgur.com/UT5Mt.png https://i.stack.imgur.com/Z81eX.png ...

Sending data from view to controller in Angular using TypeScript

I am currently working with AngularJS and TypeScript, and I have encountered an issue with passing a parameter from the view to the controller. In my attempts to solve this problem, I have utilized ng-init as follows: <div class="col-md-9" ng-controlle ...

Guide on showing error message according to personalized validation regulations in Angular 2?

Utilizing a template-driven strategy for constructing forms in Angular 2, I have successfully implemented custom validators that can be utilized within the template. However, I am facing an issue with displaying specific error messages associated with dis ...

Encountering an issue when using the Google authentication provider with Next.js version 13

I am currently working on integrating next-auth with the Google provider and Prisma in my Next.js application, but I encountered the following error: Error: Detected default export in '/MyProject/foodbrain/app/api/auth/[...nextauth]/route.ts'. Pl ...

Is there a tidier method for coding this JSX?

Is there a way to optimize these function calls for both onGoClick and onNoGoClicked within the SomeForm component? Or is it fine to keep them as they are? <SomeForm onGoClick={() => { cleanupHere(props) }} o ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

Next.js experiencing hydration error due to dynamic component

Having an issue with my RandomShape component, where it should display a random SVG shape each time the page is reloaded. However, I am encountering a hydration error on the client side. import React from "react"; import shapes, { getRandomShape ...

What is the best way to combine several packed props simultaneously?

After attempting the following, I encountered the following error: Unhandled Runtime Error TypeError: navbar.makeButtonClick is not a function Source .next/static/chunks/pages/index.js (19:29) @ onClick 17 | return( 18 | <button href='#&apo ...

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...

What is the best way to access parameters directly in layout.js when using app-router mode in next.js 14, similar to how it is done

Working on a website using next.js, I am still learning react and nextjs. One issue I am facing is how to easily retrieve params in layout.js similar to page.js. // app/page.js export default async function Home({ params }) { console.log('params:& ...

Is there a way to turn off the pinch-to-zoom trackpad gesture or disable the Ctrl+wheel zoom function on a webpage

Take a look at this example - While zooming in on the image by pressing ctrl + scroll, the image zooms but the page itself does not scale. Only the image is affected by the zoom. I am attempting to replicate this functionality on my Next.js page. I have ...

Steps to automatically make jest mocked functions throw an error:

When using jest-mock-extended to create a mock like this: export interface SomeClient { someFunction(): number; someOtherFunction(): number; } const mockClient = mock<SomeClient>(); mockClient.someFunction.mockImplementation(() => 1); The d ...

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...

Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case? Here is my code snippet: const verifyValue = () => { const selector = 'nz-option-container nz-option-item&apo ...

Scroll-triggered switching of images in a React application using Styled Components

In my Next.js application, I have implemented styled components to create a day/night mode feature based on the time of day that a user visits the site. Everything has been working well so far. However, on certain pages, I have a dark hero section, which m ...