next.js: Google Tag Manager event "History change" is no longer fired in Next.js 14.0.3

Link to the code that reproduces this issue

https://github.com/manuelseisl/next-js-demo

To Reproduce

  1. Change GTM ID in layout.jsx
  2. Start application
  3. Go to GTM preview mode
  4. Navigate between pages

Current vs. Expected behavior

The Google Tag Manager event “History change” is no longer fired in Next.js 14.0.3.

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.1.0: Mon Oct  9 21:28:45 PDT 2023; root:xnu-10002.41.9~6/RELEASE_ARM64_T6020
Binaries:
  Node: 20.10.0
  npm: 10.2.3
  Yarn: 1.22.19
  pnpm: 8.8.0
Relevant Packages:
  next: 14.0.3
  eslint-config-next: 14.0.3
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.3.2
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

App Router, Routing (next/router, next/navigation, next/link)

Additional context

I tested my reproduction against different versions and canary releases, and the first one that introduced the bug was “14.0.3”, when switching back to “14.0.2” it works.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 17
  • Comments: 16 (2 by maintainers)

Commits related to this issue

Most upvoted comments

@cduff @vKongv @manuelseisl Are you having trouble keeping track of all the pages? I use import { GoogleTagManager } from “@next/third-parties/google”; and for the page to appear in Google Analytics panel, I have to refresh page manually to see that someone has visited some page

@Bart3kL Do you have it set up to trigger on History Change? This is required due to hydration.

I did it in app/template.tsx like the doc said, thought it was a default behavior to do this until I see this issue

'use client';
import { useEffect } from 'react';
import { sendGTMEvent } from '@next/third-parties/google';

export default function Template({ children }: { children: React.ReactNode }) {
  const isProd = process.env.NODE_ENV === 'production';

  useEffect(() => {
    isProd && process.env.NEXT_PUBLIC_GTM_ID && sendGTMEvent({ event: 'page_view' });
  }, [isProd]);

  return <div>{children}</div>;
}

@cduff @vKongv @manuelseisl Are you having trouble keeping track of all the pages? I use import { GoogleTagManager } from “@next/third-parties/google”; and for the page to appear in Google Analytics panel, I have to refresh page manually to see that someone has visited some page