Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

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

Riya Amemiya561650d6f9cb
diff --git a/client/src/common/types.ts b/client/src/common/types.ts
index b969346e70..461dfcbe48 100644
--- a/client/src/common/types.ts
+++ b/client/src/common/types.ts
@@ -540,3 +540,9 @@ export type TVectorStore = {
};
export type TThread = { id: string; createdAt: string };
+
+declare global {
+ interface Window {
+ google_tag_manager?: unknown;
+ }
+}
\ No newline at end of file
diff --git a/client/src/components/Chat/Footer.tsx b/client/src/components/Chat/Footer.tsx
index d4b04698e2..b534aee018 100644
--- a/client/src/components/Chat/Footer.tsx
+++ b/client/src/components/Chat/Footer.tsx
@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import TagManager from 'react-gtm-module';
import { Constants } from 'librechat-data-provider';
@@ -34,13 +34,6 @@ export default function Footer({ className }: { className?: string }) {
</a>
);
- if (config?.analyticsGtmId != null) {
- const tagManagerArgs = {
- gtmId: config.analyticsGtmId,
- };
- TagManager.initialize(tagManagerArgs);
- }
-
const mainContentParts = (
typeof config?.customFooter === 'string'
? config.customFooter
@@ -50,6 +43,15 @@ export default function Footer({ className }: { className?: string }) {
localize('com_ui_latest_footer')
).split('|');
+ useEffect(() => {
+ if (config?.analyticsGtmId != null && typeof window.google_tag_manager === 'undefined') {
+ const tagManagerArgs = {
+ gtmId: config.analyticsGtmId,
+ };
+ TagManager.initialize(tagManagerArgs);
+ }
+ }, [config?.analyticsGtmId]);
+
const mainContentRender = mainContentParts.map((text, index) => (
<React.Fragment key={`main-content-part-${index}`}>
<ReactMarkdown
diff --git a/client/src/hooks/Config/useAppStartup.ts b/client/src/hooks/Config/useAppStartup.ts
index 79b6e986d5..8074ee1d6f 100644
--- a/client/src/hooks/Config/useAppStartup.ts
+++ b/client/src/hooks/Config/useAppStartup.ts
@@ -100,10 +100,12 @@ export default function useAppStartup({
setAvailableTools({ pluginStore, ...mapPlugins(tools) });
}, [allPlugins, user, setAvailableTools]);
- if (startupConfig?.analyticsGtmId) {
- const tagManagerArgs = {
- gtmId: startupConfig?.analyticsGtmId,
- };
- TagManager.initialize(tagManagerArgs);
- }
+ useEffect(() => {
+ if (startupConfig?.analyticsGtmId != null && typeof window.google_tag_manager === 'undefined') {
+ const tagManagerArgs = {
+ gtmId: startupConfig.analyticsGtmId,
+ };
+ TagManager.initialize(tagManagerArgs);
+ }
+ }, [startupConfig?.analyticsGtmId]);
}