Skip to content

[BUG] Improve Google Analytics & GTM Initialization in Head #5016

@Deepanshu1230

Description

@Deepanshu1230

Describe the bug.

Why do we need this improvement?

Currently, Google Analytics (ReactGA) and Google Tag Manager (GTM) are initialized during the render phase of HeadComponent. Since this component can re-render multiple times, this results in:

  • Multiple initializations of GA and GTM
  • Duplicate pageview events
  • Inflated and inaccurate analytics data
  • Side effects occurring during render, which goes against React and Next.js best practices

In addition, Next.js Strict Mode and re-renders during navigation can further amplify this issue.

How could it be implemented / designed?

The fix can be implemented by restructuring the analytics logic as follows:

  1. Move GA & GTM initialization into a useEffect
  • Run once on mount using an empty dependency array
  • Use a useRef guard to prevent double initialization

2.Track pageviews in a separate useEffect

  • Trigger only when the route/path changes
  • Avoid firing pageviews on every render
  1. Keep hostname checks intact
  • Ensure analytics only runs on asyncapi.com

Expected behavior

  • Prevent duplicate initialization of Google Analytics and GTM
  • Ensure accurate pageview tracking, only firing when the route actually changes
  • Align with React & Next.js best practices by moving side effects into useEffect
  • Improve analytics data quality by avoiding over-counting
  • Make the component safer and more predictable during re-renders

Screenshots

NILL

How to Reproduce

The fix can be implemented by restructuring the analytics logic as follows:

  1. Move GA & GTM initialization into a useEffect
  • Run once on mount using an empty dependency array
  • Use a useRef guard to prevent double initialization

2.Track pageviews in a separate useEffect

  • Trigger only when the route/path changes
  • Avoid firing pageviews on every render
  1. Keep hostname checks intact
  • Ensure analytics only runs on asyncapi.com

🖥️ Device Information [optional]

No response

👀 Have you checked for similar open issues?

  • I checked and didn't find similar issue

🏢 Have you read the Contributing Guidelines?

Are you willing to work on this issue ?

Yes I am willing to submit a PR!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    In progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions