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
17.87k stars 2.96k forks source link

🐛 fix(analytics): prevent multiple GTM initializations #4174

Closed riya-amemiya closed 1 week ago

riya-amemiya commented 1 week ago

Summary

This PR addresses the issue of multiple unnecessary initializations of Google Tag Manager (GTM) in the LibreChat application. Currently, TagManager.initialize is being called redundantly, resulting in GTM being added every time the Chat screen is opened. This PR implements a check to ensure GTM is initialized only once per session, improving performance and preventing potential analytics data inconsistencies.

Closes https://github.com/danny-avila/LibreChat/issues/4171

Change Type

Testing

To test this change:

  1. Clone the updated branch
  2. Run the application locally
  3. Open the Chat screen multiple times
  4. Use browser developer tools to verify that GTM is initialized only once

Checklist

Changes

This PR modifies two files:

  1. client/src/components/Chat/Footer.tsx
  2. client/src/hooks/Config/useAppStartup.ts

In both files, the GTM initialization logic has been updated to check for the existence of window.google_tag_manager before calling TagManager.initialize.

Footer.tsx

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

useAppStartup.ts

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

These changes ensure that GTM is initialized only if it hasn't been already, preventing multiple unnecessary initializations.

danny-avila commented 1 week ago

lgtm, thanks for the PR!