danny-avila / LibreChat

Enhanced ChatGPT Clone: Features Anthropic, AWS, OpenAI, Assistants API, Azure, Groq, o1, GPT-4o, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, langchain, DALL-E-3, ChatGPT Plugins, OpenAI Functions, Secure Multi-User System, Presets, completely open-source for self-hosting. Actively in public development.
https://librechat.ai/
MIT License
18.98k stars 3.15k forks source link

[Bug]: Multiple Initializations of Google Tag Manager #4171

Closed riya-amemiya closed 1 month ago

riya-amemiya commented 1 month ago

What happened?

The TagManager.initialize function from the react-gtm-module is being called unnecessarily multiple times. As a result, Google Tag Manager (GTM) is being added every time the Chat screen is opened. This leads to redundant GTM initializations and potentially affects the performance and accuracy of analytics data.

The expected behavior is for GTM to be initialized only once per session, regardless of how many times the Chat screen is opened.

The problematic initializations are occurring in two places:

In the Footer component: https://github.com/danny-avila/LibreChat/blob/be44caaab15d145a5ffbd7399b36d554fb7ef17b/client/src/components/Chat/Footer.tsx#L41

In the useAppStartup hook: https://github.com/danny-avila/LibreChat/blob/be44caaab15d145a5ffbd7399b36d554fb7ef17b/client/src/hooks/Config/useAppStartup.ts#L107

Steps to Reproduce

  1. Open the application
  2. Navigate to the Chat screen
  3. Close and reopen the Chat screen multiple times
  4. Check the network tab in browser developer tools or inspect the DOM for multiple GTM script injections

What browsers are you seeing the problem on?

Firefox, Chrome, Safari, Microsoft Edge, Mobile (iOS), Mobile (Android)

Relevant log output

No response

Screenshots

(No screenshots provided for this issue as it's primarily a code-level problem. If visual evidence of multiple GTM initializations is needed, screenshots of the network tab or DOM could be added here.)

Code of Conduct

riya-amemiya commented 1 month ago

Proposed Solution

To prevent unnecessary initializations, we can check for the existence of window.google_tag_manager before calling TagManager.initialize. Here's an example of how this could be implemented:

useEffect(() => {
  if (config?.analyticsGtmId != null && typeof window.google_tag_manager === 'undefined') {
    const tagManagerArgs = {
      gtmId: config.analyticsGtmId,
    };
    TagManager.initialize(tagManagerArgs);
  }
}, [config?.analyticsGtmId]);

This change should be applied to both locations where TagManager.initialize is currently being called.

danny-avila commented 1 month ago

PRs welcome

riya-amemiya commented 1 month ago

OK, I'll work on this fix.