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.