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: Load Google Tag Manager Only After Analytics Consent (#16999)

Marco Berettac3989de3864e
diff --git a/client/src/common/types.ts b/client/src/common/types.ts
index a3e0a9b319..8ddd11b6e7 100644
--- a/client/src/common/types.ts
+++ b/client/src/common/types.ts
@@ -683,6 +683,8 @@ export type TThread = { id: string; createdAt: string };
declare global {
interface Window {
google_tag_manager?: unknown;
+ /** Google Tag Manager's command queue, present once the container has loaded. */
+ dataLayer?: unknown[];
/** Answers the server emits with the document, ahead of the app's own
* scripts, for questions the first render must not guess at. */
__LIBRECHAT_CONFIG__?: {
diff --git a/client/src/components/Chat/Footer.tsx b/client/src/components/Chat/Footer.tsx
index f92aeed314..c172ee59e9 100644
--- a/client/src/components/Chat/Footer.tsx
+++ b/client/src/components/Chat/Footer.tsx
@@ -1,5 +1,4 @@
-import React, { useEffect, memo } from 'react';
-import TagManager from 'react-gtm-module';
+import React, { memo } from 'react';
import ReactMarkdown from 'react-markdown';
import { Constants, hasConfiguredFooter } from 'librechat-data-provider';
import type { TStartupConfig } from 'librechat-data-provider';
@@ -19,7 +18,7 @@ type FooterProps = {
configuredOnly?: boolean;
};
-type FooterStartupConfig = Pick<Partial<TStartupConfig>, 'analyticsGtmId' | 'customFooter'> & {
+type FooterStartupConfig = Pick<Partial<TStartupConfig>, 'customFooter'> & {
interface?: Pick<NonNullable<TStartupConfig['interface']>, 'privacyPolicy' | 'termsOfService'>;
};
@@ -87,15 +86,6 @@ function Footer({ className, startupConfig, configuredOnly = false }: FooterProp
const mainContent = configuredFooter ?? genericFooter;
const mainContentParts = mainContent === '' ? [] : mainContent.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/components/Chat/__tests__/Footer.spec.tsx b/client/src/components/Chat/__tests__/Footer.spec.tsx
index 5613b03a4f..a61644c5b5 100644
--- a/client/src/components/Chat/__tests__/Footer.spec.tsx
+++ b/client/src/components/Chat/__tests__/Footer.spec.tsx
@@ -3,11 +3,6 @@ import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Footer from '../Footer';
-jest.mock('react-gtm-module', () => ({
- __esModule: true,
- default: { initialize: jest.fn() },
-}));
-
jest.mock('~/data-provider', () => ({
useGetStartupConfig: jest.fn(() => ({ data: undefined, isFetching: false, error: null })),
}));
diff --git a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx
index 0ee2b9b9a7..e6b62614a9 100644
--- a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx
+++ b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx
@@ -29,6 +29,7 @@ const ctx: SettingsContextValue = {
replyTabBadgeAllowed: true,
replyNotificationsAllowed: true,
replyNotificationSoundAllowed: true,
+ analyticsConfigured: false,
};
function setup(extra: Partial<SettingsContextValue> = {}, query = '') {
diff --git a/client/src/components/Nav/Settings/__tests__/registry.spec.ts b/client/src/components/Nav/Settings/__tests__/registry.spec.ts
index 14dc63b0c4..22439a9d86 100644
--- a/client/src/components/Nav/Settings/__tests__/registry.spec.ts
+++ b/client/src/components/Nav/Settings/__tests__/registry.spec.ts
@@ -31,6 +31,7 @@ const settingsContext: SettingsContextValue = {
replyTabBadgeAllowed: true,
replyNotificationsAllowed: true,
replyNotificationSoundAllowed: true,
+ analyticsConfigured: false,
};
const policyProviders = ['local', 'ldap', null, undefined];
@@ -67,6 +68,12 @@ describe('settings registry', () => {
}
});
+ it('offers the analytics consent toggle only when GTM is configured', () => {
+ const entry = registry.find((e) => e.id === 'analyticsConsent');
+ expect(entry?.show?.(settingsContext)).toBe(false);
+ expect(entry?.show?.({ ...settingsContext, analyticsConfigured: true })).toBe(true);
+ });
+
describe('two-factor security visibility', () => {
const twoFactorEntry = registry.find((entry) => entry.id === 'twoFactor');
const backupCodesEntry = registry.find((entry) => entry.id === 'backupCodes');
diff --git a/client/src/components/Nav/Settings/context.tsx b/client/src/components/Nav/Settings/context.tsx
index 1ad6ebd3eb..6a2db1bb55 100644
--- a/client/src/components/Nav/Settings/context.tsx
+++ b/client/src/components/Nav/Settings/context.tsx
@@ -11,6 +11,7 @@ import useProviderKeys from '../SettingsTabs/ProviderKeys/useProviderKeys';
import { useHasAccess, useAuthContext, useGetAgentsConfig } from '~/hooks';
import usePersonalizationAccess from '~/hooks/usePersonalizationAccess';
import { useGetStartupConfig } from '~/data-provider';
+import { hasAnalyticsGtmId } from '~/store/analytics';
import store from '~/store';
export function useSettingsContext(): SettingsContextValue {
@@ -55,6 +56,7 @@ export function useSettingsContext(): SettingsContextValue {
replyConfigLoaded && replyNotificationsConfig?.desktop !== false;
const replyNotificationSoundAllowed =
replyConfigLoaded && replyNotificationsConfig?.sound !== false;
+ const analyticsConfigured = hasAnalyticsGtmId(startupConfig?.analyticsGtmId);
const hasRemoteAgentsBool = hasRemoteAgents === true;
const hasMultiConvoBool = hasMultiConvo === true;
const hasPromptsBool = hasPrompts === true;
@@ -88,6 +90,7 @@ export function useSettingsContext(): SettingsContextValue {
replyTabBadgeAllowed,
replyNotificationsAllowed,
replyNotificationSoundAllowed,
+ analyticsConfigured,
}),
[
balanceEnabled,
@@ -113,6 +116,7 @@ export function useSettingsContext(): SettingsContextValue {
replyTabBadgeAllowed,
replyNotificationsAllowed,
replyNotificationSoundAllowed,
+ analyticsConfigured,
],
);
}
diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsx
index d6df7713e2..ff7e713747 100644
--- a/client/src/components/Nav/Settings/registry.tsx
+++ b/client/src/components/Nav/Settings/registry.tsx
@@ -28,6 +28,7 @@ import EnableTwoFactorItem from '../SettingsTabs/Account/TwoFactorAuthentication
import LangfuseConnection from '../SettingsTabs/Integrations/LangfuseConnection';
import ClockFormatSelector from '../SettingsTabs/General/ClockFormatSelector';
import ImportConversations from '../SettingsTabs/Data/ImportConversations';
+import AnalyticsConsentToggle from '../SettingsTabs/Data/AnalyticsConsent';
import WeekStartSelector from '../SettingsTabs/General/WeekStartSelector';
import { ArchiveAllChats } from '../SettingsTabs/Data/ArchiveAllChats';
import { toggleControl, ThemeSetting, LangSetting } from './controls';
@@ -725,6 +726,15 @@ export const registry: SettingEntry[] = [
keywords: ['archive', 'chats', 'conversations', 'bulk'],
Component: ArchiveAllChats,
},
+ {
+ id: 'analyticsConsent',
+ tab: DATA,
+ section: 'data',
+ labelKey: 'com_ui_analytics_consent_setting',
+ keywords: ['analytics', 'cookies', 'consent', 'tracking', 'privacy', 'google', 'gtm'],
+ show: (ctx) => ctx.analyticsConfigured,
+ Component: AnalyticsConsentToggle,
+ },
// Data controls · API keys
{
id: 'providerApiKeys',
diff --git a/client/src/components/Nav/Settings/types.ts b/client/src/components/Nav/Settings/types.ts
index 037be18a7e..145bd7b809 100644
--- a/client/src/components/Nav/Settings/types.ts
+++ b/client/src/components/Nav/Settings/types.ts
@@ -62,6 +62,7 @@ export interface SettingsContextValue {
replyTabBadgeAllowed: boolean;
replyNotificationsAllowed: boolean;
replyNotificationSoundAllowed: boolean;
+ analyticsConfigured: boolean;
}
export interface SettingEntry {
diff --git a/client/src/components/Nav/SettingsTabs/Data/AnalyticsConsent.tsx b/client/src/components/Nav/SettingsTabs/Data/AnalyticsConsent.tsx
new file mode 100644
index 0000000000..617520e7ea
--- /dev/null
+++ b/client/src/components/Nav/SettingsTabs/Data/AnalyticsConsent.tsx
@@ -0,0 +1,36 @@
+import { useId } from 'react';
+import { useAtom } from 'jotai';
+import { Switch } from '@librechat/client';
+import { analyticsConsentAtom } from '~/store/analytics';
+import { useLocalize } from '~/hooks';
+
+/** Changes the answer given to the analytics consent banner. Shown only when the
+ * deployment configured Google Tag Manager. Loading happens in `useAnalytics`;
+ * turning it off cannot unload a container already on the page, which the
+ * description tells the reader a reload completes. */
+export default function AnalyticsConsentToggle() {
+ const localize = useLocalize();
+ const id = useId();
+ const [consent, setConsent] = useAtom(analyticsConsentAtom);
+ const labelId = `${id}-label`;
+ const descriptionId = `${id}-description`;
+
+ return (
+ <div className="flex items-center justify-between">
+ <div>
+ <div id={labelId}>{localize('com_ui_analytics_consent_setting')}</div>
+ <div id={descriptionId} className="text-text-secondary mt-1 text-xs">
+ {localize('com_ui_analytics_consent_setting_description')}
+ </div>
+ </div>
+ <Switch
+ checked={consent === 'granted'}
+ onCheckedChange={(checked: boolean) => setConsent(checked ? 'granted' : 'denied')}
+ className="ml-4"
+ aria-labelledby={labelId}
+ aria-describedby={descriptionId}
+ data-testid="analytics-consent-switch"
+ />
+ </div>
+ );
+}
diff --git a/client/src/components/Nav/SettingsTabs/Data/__tests__/AnalyticsConsent.spec.tsx b/client/src/components/Nav/SettingsTabs/Data/__tests__/AnalyticsConsent.spec.tsx
new file mode 100644
index 0000000000..423fd1b908
--- /dev/null
+++ b/client/src/components/Nav/SettingsTabs/Data/__tests__/AnalyticsConsent.spec.tsx
@@ -0,0 +1,47 @@
+import { Provider } from 'jotai';
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom/extend-expect';
+import AnalyticsConsentToggle from '../AnalyticsConsent';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+const renderToggle = () =>
+ render(
+ <Provider>
+ <AnalyticsConsentToggle />
+ </Provider>,
+ );
+
+describe('AnalyticsConsentToggle', () => {
+ beforeEach(() => localStorage.clear());
+
+ it('reads as off until the viewer has granted consent', () => {
+ renderToggle();
+ const toggle = screen.getByRole('switch', { name: 'com_ui_analytics_consent_setting' });
+ expect(toggle).toHaveAttribute('aria-checked', 'false');
+ expect(toggle).toHaveAccessibleDescription('com_ui_analytics_consent_setting_description');
+ });
+
+ it('grants and then withdraws consent', () => {
+ renderToggle();
+ const toggle = screen.getByRole('switch', { name: 'com_ui_analytics_consent_setting' });
+
+ fireEvent.click(toggle);
+ expect(toggle).toHaveAttribute('aria-checked', 'true');
+ expect(localStorage.getItem('analyticsConsent')).toBe(JSON.stringify('granted'));
+
+ fireEvent.click(toggle);
+ expect(toggle).toHaveAttribute('aria-checked', 'false');
+ expect(localStorage.getItem('analyticsConsent')).toBe(JSON.stringify('denied'));
+ });
+
+ it('reflects a consent given through the banner', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ renderToggle();
+ expect(
+ screen.getByRole('switch', { name: 'com_ui_analytics_consent_setting' }),
+ ).toHaveAttribute('aria-checked', 'true');
+ });
+});
diff --git a/client/src/components/Share/ShareView.tsx b/client/src/components/Share/ShareView.tsx
index 254f747c8f..96f936d494 100644
--- a/client/src/components/Share/ShareView.tsx
+++ b/client/src/components/Share/ShareView.tsx
@@ -27,6 +27,7 @@ import {
import SharedSubagentActivityDialog from '~/components/Chat/Subagents/SharedSubagentActivityDialog';
import { cn, DEFAULT_APP_TITLE, getResponseStatus, selectActiveBranchTail } from '~/utils';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
+import AnalyticsConsentToggle from '../Nav/SettingsTabs/Data/AnalyticsConsent';
import { useDeploymentThemeOverride } from '~/Providers/DeploymentTheme';
import { useLocalize, useDocumentTitle, useAuthContext } from '~/hooks';
import { ThemeSelector, LangSelector } from '~/components/Appearance';
@@ -34,6 +35,8 @@ import { ShareMessagesProvider } from './ShareMessagesProvider';
import { useForkSharedConvoMutation } from '~/data-provider';
import { useGetSharedStartupConfig } from '~/data-provider';
import { ShareArtifactsContainer } from './ShareArtifacts';
+import AnalyticsConsent from '../System/AnalyticsConsent';
+import { hasAnalyticsGtmId } from '~/store/analytics';
import AppChatSurface from '../Chat/Surface';
import { ShareContext } from '~/Providers';
import MessagesView from './MessagesView';
@@ -205,6 +208,7 @@ function SharedView() {
langfuseSessionUrl={data.langfuseSessionUrl}
onContinue={handleContinue}
isContinuing={forkShare.isLoading}
+ analyticsConfigured={hasAnalyticsGtmId(config?.analyticsGtmId)}
/>
<ShareMessagesProvider messages={data.messages}>
<MessagesView messagesTree={messagesTree} conversationId={SHARED_CONVO_KEY} />
@@ -236,6 +240,7 @@ function SharedView() {
<div className="text-text-primary relative flex h-full min-h-0 flex-col" role="presentation">
{content}
{footer}
+ <AnalyticsConsent gtmId={config?.analyticsGtmId} />
</div>
</div>
);
@@ -333,6 +338,8 @@ interface ShareHeaderProps {
onContinue: () => void;
onThemeChange: (value: string) => void;
onLangChange: (value: string) => void;
+ /** Whether the link's deployment set `ANALYTICS_GTM_ID`, which adds the consent toggle. */
+ analyticsConfigured?: boolean;
}
export function ShareHeader({
@@ -348,6 +355,7 @@ export function ShareHeader({
onContinue,
onThemeChange,
onLangChange,
+ analyticsConfigured = false,
}: ShareHeaderProps) {
const [settingsOpen, setSettingsOpen] = useState(false);
const [settingsContent, setSettingsContent] = useState<HTMLDivElement | null>(null);
@@ -440,6 +448,12 @@ export function ShareHeader({
portalElement={settingsContent}
popoverClassName="z-[150]"
/>
+ {analyticsConfigured && (
+ <>
+ <Separator orientation="horizontal" />
+ <AnalyticsConsentToggle />
+ </>
+ )}
</div>
</OGDialogContent>
</OGDialog>
diff --git a/client/src/components/System/AnalyticsConsent.tsx b/client/src/components/System/AnalyticsConsent.tsx
new file mode 100644
index 0000000000..5c0fbb6b4d
--- /dev/null
+++ b/client/src/components/System/AnalyticsConsent.tsx
@@ -0,0 +1,55 @@
+import { useId } from 'react';
+import { Button } from '@librechat/client';
+import useAnalytics from '~/hooks/Config/useAnalytics';
+import { useLocalize } from '~/hooks';
+
+type AnalyticsConsentProps = {
+ /** The deployment's `ANALYTICS_GTM_ID`, from the startup config of the page shell. */
+ gtmId?: string | null;
+};
+
+/**
+ * Loads Google Tag Manager once the viewer consents, and asks for that consent
+ * when it has not been given or refused yet. The prompt is a non-modal region at
+ * the bottom of the viewport: it does not take focus or block the page, and
+ * either answer hides it. The choice can be changed later in Settings.
+ */
+export default function AnalyticsConsent({ gtmId }: AnalyticsConsentProps) {
+ const { enabled, consent, setConsent } = useAnalytics(gtmId);
+
+ if (!enabled || consent != null) {
+ return null;
+ }
+
+ return (
+ <ConsentBanner onAccept={() => setConsent('granted')} onDecline={() => setConsent('denied')} />
+ );
+}
+
+function ConsentBanner({ onAccept, onDecline }: { onAccept: () => void; onDecline: () => void }) {
+ const localize = useLocalize();
+ const id = useId();
+ const messageId = `${id}-message`;
+
+ return (
+ <div className="pointer-events-none fixed inset-x-0 bottom-0 z-50 flex justify-center p-4">
+ <section
+ aria-label={localize('com_ui_analytics_consent_label')}
+ aria-describedby={messageId}
+ className="border-border-light bg-surface-dialog text-text-primary pointer-events-auto flex w-full max-w-xl flex-col gap-3 rounded-2xl border p-4 shadow-lg sm:flex-row sm:items-center"
+ >
+ <p id={messageId} className="text-text-secondary flex-1 text-sm">
+ {localize('com_ui_analytics_consent_message')}
+ </p>
+ <div className="flex shrink-0 gap-2">
+ <Button type="button" variant="outline" onClick={onDecline}>
+ {localize('com_ui_analytics_consent_decline')}
+ </Button>
+ <Button type="button" variant="outline" onClick={onAccept}>
+ {localize('com_ui_analytics_consent_accept')}
+ </Button>
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/client/src/components/System/__tests__/AnalyticsConsent.spec.tsx b/client/src/components/System/__tests__/AnalyticsConsent.spec.tsx
new file mode 100644
index 0000000000..5d59535e31
--- /dev/null
+++ b/client/src/components/System/__tests__/AnalyticsConsent.spec.tsx
@@ -0,0 +1,190 @@
+import { Provider } from 'jotai';
+import TagManager from 'react-gtm-module';
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom/extend-expect';
+import AnalyticsConsent from '../AnalyticsConsent';
+
+jest.mock('react-gtm-module', () => ({
+ __esModule: true,
+ default: { initialize: jest.fn() },
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+const initialize = TagManager.initialize as jest.Mock;
+
+const renderConsent = (gtmId?: string | null) =>
+ render(
+ <Provider>
+ <AnalyticsConsent gtmId={gtmId} />
+ </Provider>,
+ );
+
+const appendContainerScript = (gtmId: string) => {
+ const script = document.createElement('script');
+ script.src = `https://www.googletagmanager.com/gtm.js?id=${gtmId}`;
+ document.head.appendChild(script);
+ return script;
+};
+
+const getBanner = () => screen.queryByRole('region', { name: 'com_ui_analytics_consent_label' });
+
+describe('AnalyticsConsent', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ initialize.mockClear();
+ delete window.google_tag_manager;
+ delete window.dataLayer;
+ });
+
+ it('renders nothing and never loads GTM when no container is configured', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ renderConsent(undefined);
+ expect(getBanner()).not.toBeInTheDocument();
+ expect(initialize).not.toHaveBeenCalled();
+ });
+
+ it('asks for consent without loading GTM or taking focus', () => {
+ renderConsent('GTM-TEST');
+ const banner = getBanner();
+ expect(banner).toBeInTheDocument();
+ expect(banner).not.toContainElement(document.activeElement as HTMLElement);
+ expect(screen.getByRole('button', { name: 'com_ui_analytics_consent_accept' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'com_ui_analytics_consent_decline' })).toBeVisible();
+ expect(initialize).not.toHaveBeenCalled();
+ });
+
+ it('loads GTM after Accept and hides the banner', () => {
+ renderConsent('GTM-TEST');
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_analytics_consent_accept' }));
+ expect(initialize).toHaveBeenCalledTimes(1);
+ expect(initialize).toHaveBeenCalledWith({ gtmId: 'GTM-TEST' });
+ expect(getBanner()).not.toBeInTheDocument();
+ expect(localStorage.getItem('analyticsConsent')).toBe(JSON.stringify('granted'));
+ /** Consent defaults reach the data layer before the container loads, advertising denied. */
+ expect(Array.from(window.dataLayer?.[0] as ArrayLike<unknown>)).toEqual([
+ 'consent',
+ 'default',
+ {
+ analytics_storage: 'granted',
+ ad_storage: 'denied',
+ ad_user_data: 'denied',
+ ad_personalization: 'denied',
+ },
+ ]);
+ });
+
+ it('keeps GTM unloaded after Decline and hides the banner', () => {
+ renderConsent('GTM-TEST');
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_analytics_consent_decline' }));
+ expect(initialize).not.toHaveBeenCalled();
+ expect(getBanner()).not.toBeInTheDocument();
+ expect(localStorage.getItem('analyticsConsent')).toBe(JSON.stringify('denied'));
+ });
+
+ it('loads GTM on mount for a viewer who already consented, without asking again', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ renderConsent('GTM-TEST');
+ expect(getBanner()).not.toBeInTheDocument();
+ expect(initialize).toHaveBeenCalledWith({ gtmId: 'GTM-TEST' });
+ });
+
+ it('does not ask again or load GTM for a viewer who declined', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('denied'));
+ renderConsent('GTM-TEST');
+ expect(getBanner()).not.toBeInTheDocument();
+ expect(initialize).not.toHaveBeenCalled();
+ });
+
+ it('does not load the configured container twice', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ window.google_tag_manager = { 'GTM-TEST': {} };
+ renderConsent('GTM-TEST');
+ expect(initialize).not.toHaveBeenCalled();
+ });
+
+ it('still loads the configured container when a different one is on the page', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ window.google_tag_manager = { 'GTM-OTHER': {} };
+ renderConsent('GTM-TEST');
+ expect(initialize).toHaveBeenCalledWith({ gtmId: 'GTM-TEST' });
+ });
+
+ it('tells a loaded container that consent was withdrawn', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('denied'));
+ window.dataLayer = [];
+ window.google_tag_manager = { 'GTM-TEST': {} };
+ renderConsent('GTM-TEST');
+ expect(window.dataLayer).toHaveLength(1);
+ expect(Array.from(window.dataLayer[0] as ArrayLike<unknown>)).toEqual([
+ 'consent',
+ 'update',
+ expect.objectContaining({ analytics_storage: 'denied', ad_storage: 'denied' }),
+ ]);
+ });
+
+ it('tells a container still on the page that consent was given again', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ window.dataLayer = [];
+ window.google_tag_manager = { 'GTM-TEST': {} };
+ renderConsent('GTM-TEST');
+ expect(initialize).not.toHaveBeenCalled();
+ expect(Array.from(window.dataLayer[0] as ArrayLike<unknown>)).toEqual([
+ 'consent',
+ 'update',
+ expect.objectContaining({ analytics_storage: 'granted', ad_storage: 'denied' }),
+ ]);
+ });
+
+ it('leaves the data layer alone when the configured container is not on the page', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('denied'));
+ window.dataLayer = [];
+ window.google_tag_manager = { 'GTM-OTHER': {} };
+ renderConsent('GTM-TEST');
+ renderConsent(undefined);
+ expect(window.dataLayer).toHaveLength(0);
+ });
+
+ it('does not inject a second container while the first is still loading', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ const loading = appendContainerScript('GTM-TEST');
+ renderConsent('GTM-TEST');
+ expect(initialize).not.toHaveBeenCalled();
+ loading.remove();
+ });
+
+ it('tells a still loading container that consent was withdrawn', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('denied'));
+ window.dataLayer = [];
+ const loading = appendContainerScript('GTM-TEST');
+ renderConsent('GTM-TEST');
+ expect(window.dataLayer).toHaveLength(1);
+ loading.remove();
+ });
+
+ it('retries a container whose script failed to load', () => {
+ localStorage.setItem('analyticsConsent', JSON.stringify('granted'));
+ /** Stands in for the GTM snippet: queues the start event, then injects gtm.js. */
+ const bootstrap = ({ gtmId }: { gtmId: string }) => {
+ window.dataLayer?.push({ event: 'gtm.js' });
+ appendContainerScript(gtmId);
+ };
+ initialize.mockImplementationOnce(bootstrap).mockImplementationOnce(bootstrap);
+ const first = renderConsent('GTM-TEST');
+ const failed = document.querySelector('script[src*="gtm.js"]');
+ expect(failed).not.toBeNull();
+ failed?.dispatchEvent(new Event('error'));
+ expect(document.querySelector('script[src*="gtm.js"]')).toBeNull();
+ first.unmount();
+ renderConsent('GTM-TEST');
+ expect(initialize).toHaveBeenCalledTimes(2);
+ /** Only the retry's start event is left for the container to replay. */
+ const startEvents = (window.dataLayer ?? []).filter(
+ (entry) => (entry as { event?: unknown } | null)?.event === 'gtm.js',
+ );
+ expect(startEvents).toHaveLength(1);
+ document.querySelector('script[src*="gtm.js"]')?.remove();
+ });
+});
diff --git a/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx b/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx
index 7d2ec08db0..e96c5b3efd 100644
--- a/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx
+++ b/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx
@@ -49,11 +49,6 @@ jest.mock('~/utils/timestamps', () => ({
cleanupTimestampedStorage: jest.fn(),
}));
-jest.mock('react-gtm-module', () => ({
- __esModule: true,
- default: { initialize: jest.fn() },
-}));
-
import useAppStartup from '../useAppStartup';
const mockUser = {
diff --git a/client/src/hooks/Config/index.ts b/client/src/hooks/Config/index.ts
index 64fb1eb4f3..96e8628a4a 100644
--- a/client/src/hooks/Config/index.ts
+++ b/client/src/hooks/Config/index.ts
@@ -1,3 +1,4 @@
export { default as useAppStartup } from './useAppStartup';
export { default as useClearStates } from './useClearStates';
export { default as useSpeechSettingsInit } from './useSpeechSettingsInit';
+export { default as useAnalytics } from './useAnalytics';
diff --git a/client/src/hooks/Config/useAnalytics.ts b/client/src/hooks/Config/useAnalytics.ts
new file mode 100644
index 0000000000..56ee711447
--- /dev/null
+++ b/client/src/hooks/Config/useAnalytics.ts
@@ -0,0 +1,109 @@
+import { useEffect } from 'react';
+import { useAtom } from 'jotai';
+import TagManager from 'react-gtm-module';
+import { analyticsConsentAtom, hasAnalyticsGtmId } from '~/store/analytics';
+
+type ConsentState = 'granted' | 'denied';
+
+/**
+ * Sends a Google consent mode command (`gtag('consent', ...)`) to the data layer.
+ * The viewer answers one question, analytics, so advertising storage and ad data
+ * use stay denied whatever the answer. A loaded container cannot be unloaded, so
+ * after a withdrawal tags that ignore consent mode keep running until the page
+ * reloads; the reload is what completes the revocation.
+ */
+function pushConsent(command: 'default' | 'update', analytics: ConsentState) {
+ window.dataLayer = window.dataLayer ?? [];
+ const dataLayer = window.dataLayer;
+ /** GTM reads consent commands only in the `arguments` shape gtag pushes, not as a plain array. */
+ function gtag(..._args: unknown[]) {
+ // eslint-disable-next-line prefer-rest-params -- GTM requires the Arguments object itself
+ dataLayer.push(arguments);
+ }
+ gtag('consent', command, {
+ analytics_storage: analytics,
+ ad_storage: 'denied',
+ ad_user_data: 'denied',
+ ad_personalization: 'denied',
+ });
+}
+
+/** The `gtm.js` script of this deployment's container, while it loads or after. */
+function findContainerScript(gtmId: string): HTMLScriptElement | undefined {
+ return Array.from(document.querySelectorAll<HTMLScriptElement>('script[src*="gtm.js"]')).find(
+ (script) => {
+ try {
+ return new URL(script.src, window.location.href).searchParams.get('id') === gtmId;
+ } catch {
+ return false;
+ }
+ },
+ );
+}
+
+/** Whether this deployment's container is on the page, loading or loaded. GTM
+ * registers each container it runs under its id, so another container does not
+ * count. A script that failed to load is removed (see `initializeContainer`). */
+function isContainerPresent(gtmId: string) {
+ const registry = window.google_tag_manager as Record<string, unknown> | undefined;
+ return registry?.[gtmId] != null || findContainerScript(gtmId) != null;
+}
+
+/** Loads the container with consent defaults queued ahead of its first tag. A
+ * script that fails to load is removed together with the `gtm.js` start event
+ * the snippet queued for it, so the next grant retries without a container
+ * that loads later replaying two start events. */
+function initializeContainer(gtmId: string) {
+ /** The snippet keeps an existing data layer, so the defaults stay first in it. */
+ pushConsent('default', 'granted');
+ const queued = window.dataLayer?.length ?? 0;
+ TagManager.initialize({ gtmId });
+ const startEvent = window.dataLayer
+ ?.slice(queued)
+ .find((entry) => (entry as { event?: unknown } | null)?.event === 'gtm.js');
+ const script = findContainerScript(gtmId);
+ script?.addEventListener(
+ 'error',
+ () => {
+ script.remove();
+ const index = window.dataLayer?.indexOf(startEvent) ?? -1;
+ if (startEvent != null && index !== -1) {
+ window.dataLayer?.splice(index, 1);
+ }
+ },
+ { once: true },
+ );
+}
+
+/**
+ * The only place Google Tag Manager is initialized. It loads when the
+ * deployment set `ANALYTICS_GTM_ID` and the viewer granted consent, never before.
+ * Mount it once per page shell (the signed-in layout and the shared-link view).
+ */
+export default function useAnalytics(gtmId: string | null | undefined) {
+ const [consent, setConsent] = useAtom(analyticsConsentAtom);
+ const enabled = hasAnalyticsGtmId(gtmId);
+
+ useEffect(() => {
+ if (!enabled || consent !== 'granted') {
+ return;
+ }
+ if (isContainerPresent(gtmId)) {
+ /** Consent given again after a withdrawal in this page, or a second shell
+ * mounting: the container is already here and only needs the answer. */
+ pushConsent('update', 'granted');
+ return;
+ }
+ initializeContainer(gtmId);
+ }, [enabled, gtmId, consent]);
+
+ useEffect(() => {
+ /** Nothing is pushed unless this deployment's container is on the page; one
+ * still loading reads the update from the data layer queue when it starts. */
+ if (enabled && consent === 'denied' && isContainerPresent(gtmId)) {
+ pushConsent('update', 'denied');
+ }
+ }, [enabled, gtmId, consent]);
+
+ return { enabled, consent, setConsent };
+}
diff --git a/client/src/hooks/Config/useAppStartup.ts b/client/src/hooks/Config/useAppStartup.ts
index 8027a09903..bc631d8368 100644
--- a/client/src/hooks/Config/useAppStartup.ts
+++ b/client/src/hooks/Config/useAppStartup.ts
@@ -1,6 +1,5 @@
import { useEffect } from 'react';
import { useRecoilState } from 'recoil';
-import TagManager from 'react-gtm-module';
import { installCloudFrontImageRetry } from '@librechat/client';
import {
getTokenHeader,
@@ -80,13 +79,4 @@ export default function useAppStartup({
useEffect(() => {
return installCloudFrontImageRetry(startupConfig, { getAuthorizationHeader: getTokenHeader });
}, [startupConfig]);
-
- useEffect(() => {
- if (startupConfig?.analyticsGtmId != null && typeof window.google_tag_manager === 'undefined') {
- const tagManagerArgs = {
- gtmId: startupConfig.analyticsGtmId,
- };
- TagManager.initialize(tagManagerArgs);
- }
- }, [startupConfig?.analyticsGtmId]);
}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 293183153d..c8ddc9f4bd 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -3647,5 +3647,11 @@
"com_ui_tool_approval_connection_unavailable": "Approval cannot be remembered for this connection. Each call requires review.",
"com_ui_tool_approval_remember_disabled": "Remembered approvals are disabled. Each call requires review.",
"com_ui_tool_approval_storage_unavailable": "Remembered approval is unavailable. This approval will apply only to this call.",
- "com_ui_tool_approval_background_unavailable": "Background launches cannot teach approval. Approve a successful foreground call to remember this tool."
+ "com_ui_tool_approval_background_unavailable": "Background launches cannot teach approval. Approve a successful foreground call to remember this tool.",
+ "com_ui_analytics_consent_accept": "Allow analytics",
+ "com_ui_analytics_consent_decline": "Decline",
+ "com_ui_analytics_consent_label": "Analytics consent",
+ "com_ui_analytics_consent_message": "This site can use Google Tag Manager to measure how it is used. Analytics stay off unless you allow them, and you can change this later in Settings.",
+ "com_ui_analytics_consent_setting": "Allow analytics",
+ "com_ui_analytics_consent_setting_description": "Lets this site load Google Tag Manager. Turning this off takes full effect after you reload the page."
}
diff --git a/client/src/routes/Root.tsx b/client/src/routes/Root.tsx
index b33a53b5bc..a89e73ec6d 100644
--- a/client/src/routes/Root.tsx
+++ b/client/src/routes/Root.tsx
@@ -39,6 +39,7 @@ import KeyboardShortcutsDialog from '~/components/Nav/KeyboardShortcutsDialog';
import KeyboardDeleteDialog from '~/components/Nav/KeyboardDeleteDialog';
import { useUserTermsQuery, useGetStartupConfig } from '~/data-provider';
import { MobileDrawerScrim } from '~/components/UnifiedSidebar/mobile';
+import AnalyticsConsent from '~/components/System/AnalyticsConsent';
import useKeyboardShortcuts from '~/hooks/useKeyboardShortcuts';
import useDrawerDismiss from '~/hooks/Nav/useDrawerDismiss';
import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';
@@ -251,6 +252,7 @@ function RootLayout() {
<KeyboardShortcutsProvider />
<ReplyNotifications />
<MessagesRetention />
+ <AnalyticsConsent gtmId={config?.analyticsGtmId} />
</AgentsMapContext.Provider>
{config?.interface?.termsOfService?.modalAcceptance === true && (
<TermsAndConditionsModal
diff --git a/client/src/store/analytics.ts b/client/src/store/analytics.ts
new file mode 100644
index 0000000000..2641cf708e
--- /dev/null
+++ b/client/src/store/analytics.ts
@@ -0,0 +1,16 @@
+import { createStorageAtom } from './jotai-utils';
+
+export type AnalyticsConsent = 'granted' | 'denied';
+
+/** The viewer's answer to the analytics consent banner. `null` means they have
+ * not answered yet, which counts as no consent: Google Tag Manager loads only
+ * after an explicit `granted`. */
+export const analyticsConsentAtom = createStorageAtom<AnalyticsConsent | null>(
+ 'analyticsConsent',
+ null,
+);
+
+/** Whether the deployment configured Google Tag Manager at all. */
+export function hasAnalyticsGtmId(gtmId: string | null | undefined): gtmId is string {
+ return typeof gtmId === 'string' && gtmId.trim() !== '';
+}
diff --git a/e2e/specs/mock/scenarios/analytics-consent.spec.ts b/e2e/specs/mock/scenarios/analytics-consent.spec.ts
new file mode 100644
index 0000000000..66b83ab3f4
--- /dev/null
+++ b/e2e/specs/mock/scenarios/analytics-consent.spec.ts
@@ -0,0 +1,248 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ sendMessageAndWaitForCompletion,
+ selectMockEndpoint,
+ getAccessToken,
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+} from '../helpers';
+import { openSettings } from './ui-scale.helpers';
+
+/**
+ * A deployment that sets `ANALYTICS_GTM_ID` used to load Google Tag Manager on
+ * the first render. It now loads only after the viewer allows it, on the signed-in
+ * app and on a shared link alike, and the answer can be withdrawn in Settings.
+ *
+ * The id reaches the client through `/api/config` and `/api/share/:shareId/config`,
+ * so it is layered over the real responses here instead of restarting the shared
+ * harness server with a different environment. Requests to Google Tag Manager are
+ * answered locally with an empty script and counted: a request is the observable
+ * the consent decision controls.
+ */
+
+const GTM_ID = 'GTM-E2ETEST';
+
+type Probe = { requests: () => number };
+
+/** Stands in for gtm.js: registers the container under its id, as GTM does once loaded. */
+const GTM_STUB = `(() => {
+ const id = new URL(document.currentScript.src).searchParams.get('id');
+ window.google_tag_manager = window.google_tag_manager || {};
+ window.google_tag_manager[id] = {};
+})();`;
+
+/** A request that should not happen has no event to wait on, so absence is
+ * observed over a short settle window after the config arrived; the page holds
+ * open streams, so `networkidle` never fires. */
+const SETTLE_MS = 1500;
+
+async function expectNoGtm(page: Page, gtm: Probe, expected: number) {
+ await page.waitForTimeout(SETTLE_MS);
+ expect(gtm.requests()).toBe(expected);
+ await expect(page.locator('script[src*="googletagmanager.com"]')).toHaveCount(0);
+}
+
+async function serveGtmId(page: Page, gtmId: string | null = GTM_ID): Promise<Probe> {
+ const withId = (payload: Record<string, unknown>) => {
+ const served = { ...payload };
+ delete served.analyticsGtmId;
+ if (gtmId !== null) {
+ served.analyticsGtmId = gtmId;
+ }
+ return served;
+ };
+ await page.route(
+ (url) => url.pathname === '/api/config' || /^\/api\/share\/[^/]+\/config$/.test(url.pathname),
+ async (route) => {
+ const response = await route.fetch();
+ await route.fulfill({ response, json: withId(await response.json()) });
+ },
+ );
+ let requests = 0;
+ await page.route('**://*.googletagmanager.com/**', async (route) => {
+ requests += 1;
+ await route.fulfill({ status: 200, contentType: 'text/javascript', body: GTM_STUB });
+ });
+ return { requests: () => requests };
+}
+
+const banner = (page: Page) => page.getByRole('region', { name: 'Analytics consent' });
+const allowButton = (page: Page) => banner(page).getByRole('button', { name: 'Allow analytics' });
+const declineButton = (page: Page) => banner(page).getByRole('button', { name: 'Decline' });
+
+/** The app shell is up once the composer renders and the startup config, which
+ * carries the tag manager id, has arrived. */
+async function openNewChat(page: Page) {
+ await Promise.all([
+ page.waitForResponse((res) => new URL(res.url()).pathname === '/api/config' && res.ok()),
+ page.goto(NEW_CHAT_PATH, { timeout: 15000 }),
+ ]);
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({
+ timeout: 20000,
+ });
+}
+
+async function openDataSettings(page: Page) {
+ await openSettings(page);
+ const dialog = page.getByRole('dialog');
+ await dialog.getByRole('tab', { name: 'Data & Privacy' }).click();
+ return dialog.getByRole('switch', { name: 'Allow analytics' });
+}
+
+/** The last consent mode answer the page gave a loaded container, if any. */
+const lastConsentUpdate = (page: Page) =>
+ page.evaluate(() =>
+ ((window as Window & { dataLayer?: unknown[] }).dataLayer ?? []).reduce<string | null>(
+ (last, entry) => {
+ const args = entry as ArrayLike<unknown> | null;
+ if (args == null || typeof args !== 'object' || args[0] !== 'consent') {
+ return last;
+ }
+ const state = args[2] as { analytics_storage?: string } | undefined;
+ return args[1] === 'update' ? (state?.analytics_storage ?? last) : last;
+ },
+ null,
+ ),
+ );
+
+async function createSharedLink(page: Page): Promise<string> {
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await sendMessageAndWaitForCompletion(page, `Shared analytics ${Date.now()}`);
+ await expect(page).toHaveURL(/\/c\/(?!new)[0-9a-fA-F-]{36}$/);
+ const conversationId = new URL(page.url()).pathname.split('/').pop();
+ const token = await getAccessToken(page);
+ const response = await page.request.post(`/api/share/${conversationId}`, {
+ headers: { Authorization: `Bearer ${token}` },
+ data: {},
+ });
+ expect(response.ok()).toBeTruthy();
+ const { shareId } = (await response.json()) as { shareId?: string };
+ if (!shareId) {
+ throw new Error('Expected create-share response to include a shareId');
+ }
+ return shareId;
+}
+
+test.describe('analytics consent', () => {
+ test('Google Tag Manager loads only after the viewer allows analytics @scenario:gtm-loads-only-after-consent', async ({
+ page,
+ }) => {
+ test.setTimeout(90000);
+ const gtm = await serveGtmId(page);
+ await openNewChat(page);
+
+ await expect(banner(page)).toBeVisible();
+ expect(gtm.requests()).toBe(0);
+
+ await allowButton(page).click();
+ await expect(banner(page)).toHaveCount(0);
+ await expect.poll(gtm.requests).toBeGreaterThan(0);
+
+ /** The answer persists: no second prompt, and the container loads on the next visit. */
+ const before = gtm.requests();
+ await openNewChat(page);
+ await expect.poll(gtm.requests).toBeGreaterThan(before);
+ await expect(banner(page)).toHaveCount(0);
+ });
+
+ test('declining keeps Google Tag Manager off across reloads @scenario:gtm-stays-off-after-decline', async ({
+ page,
+ }) => {
+ test.setTimeout(90000);
+ const gtm = await serveGtmId(page);
+ await openNewChat(page);
+
+ await declineButton(page).click();
+ await expect(banner(page)).toHaveCount(0);
+
+ await openNewChat(page);
+ await expect(banner(page)).toHaveCount(0);
+ await expectNoGtm(page, gtm, 0);
+ });
+
+ test('a shared link asks before loading Google Tag Manager @scenario:shared-link-gtm-waits-for-consent', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ /** Create the link without an id configured, so the app shell never asks first. */
+ await serveGtmId(page, null);
+ const shareId = await createSharedLink(page);
+ await page.unrouteAll({ behavior: 'wait' });
+
+ const gtm = await serveGtmId(page);
+ await page.goto(`/share/${shareId}`, { timeout: 15000 });
+ await expect(page.getByTestId('messages-view')).toBeVisible({ timeout: 20000 });
+ await expect(banner(page)).toBeVisible();
+ expect(gtm.requests()).toBe(0);
+
+ await allowButton(page).click();
+ await expect(banner(page)).toHaveCount(0);
+ await expect.poll(gtm.requests).toBeGreaterThan(0);
+
+ /** A viewer who never signs in withdraws from the shared view's own Settings. */
+ await page.getByRole('button', { name: 'Settings', exact: true }).click();
+ const toggle = page.getByRole('dialog').getByRole('switch', { name: 'Allow analytics' });
+ await expect(toggle).toBeChecked();
+ await toggle.click();
+ await expect(toggle).not.toBeChecked();
+ await expect.poll(() => lastConsentUpdate(page)).toBe('denied');
+ });
+
+ test('turning analytics off in Settings withdraws consent @scenario:settings-revokes-analytics-consent', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const gtm = await serveGtmId(page);
+ await openNewChat(page);
+ await allowButton(page).click();
+ await expect.poll(gtm.requests).toBeGreaterThan(0);
+
+ const toggle = await openDataSettings(page);
+ await expect(toggle).toBeChecked();
+ await toggle.click();
+ await expect(toggle).not.toBeChecked();
+ /** The loaded container is told immediately; the reload completes it. */
+ await expect.poll(() => lastConsentUpdate(page)).toBe('denied');
+
+ /** Given again in the same page, the container still here is told so and
+ * no second one is requested. */
+ const loaded = gtm.requests();
+ await toggle.click();
+ await expect(toggle).toBeChecked();
+ await expect.poll(() => lastConsentUpdate(page)).toBe('granted');
+ await toggle.click();
+ await expect(toggle).not.toBeChecked();
+ await expect.poll(() => lastConsentUpdate(page)).toBe('denied');
+ expect(gtm.requests()).toBe(loaded);
+
+ const before = gtm.requests();
+ await openNewChat(page);
+ await expect(banner(page)).toHaveCount(0);
+ await expectNoGtm(page, gtm, before);
+
+ /** And it can be given again from the same place. */
+ const again = await openDataSettings(page);
+ await expect(again).not.toBeChecked();
+ await again.click();
+ await expect(again).toBeChecked();
+ await expect.poll(gtm.requests).toBeGreaterThan(before);
+ });
+
+ test('a deployment without a tag manager id shows no prompt and no setting @scenario:no-gtm-id-no-consent-ui', async ({
+ page,
+ }) => {
+ test.setTimeout(90000);
+ const gtm = await serveGtmId(page, null);
+ await openNewChat(page);
+ await expect(banner(page)).toHaveCount(0);
+
+ await openSettings(page);
+ const dialog = page.getByRole('dialog');
+ await dialog.getByRole('tab', { name: 'Data & Privacy' }).click();
+ await expect(dialog.getByRole('button', { name: 'Archive all chats' })).toBeVisible();
+ await expect(dialog.getByRole('switch', { name: 'Allow analytics' })).toHaveCount(0);
+ expect(gtm.requests()).toBe(0);
+ });
+});