From 515055ab2446aaf226b1a2943874148247a4442b Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Wed, 13 Nov 2024 12:18:35 -0800 Subject: [PATCH] Fix: (third-parties) sendGTMEvent not queueing events before GTM init (#68683) (#72111) Backports: https://github.com/vercel/next.js/pull/68683 Co-authored-by: Develliot --- packages/third-parties/src/google/gtm.tsx | 25 ++++++++--------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/packages/third-parties/src/google/gtm.tsx b/packages/third-parties/src/google/gtm.tsx index 1203525cc1e34..5a3d7d97ca211 100644 --- a/packages/third-parties/src/google/gtm.tsx +++ b/packages/third-parties/src/google/gtm.tsx @@ -5,14 +5,12 @@ import Script from 'next/script' import type { GTMParams } from '../types/google' -let currDataLayerName: string | undefined = undefined +let currDataLayerName = 'dataLayer' export function GoogleTagManager(props: GTMParams) { const { gtmId, dataLayerName = 'dataLayer', auth, preview, dataLayer } = props - if (currDataLayerName === undefined) { - currDataLayerName = dataLayerName - } + currDataLayerName = dataLayerName const gtmLayer = dataLayerName !== 'dataLayer' ? `&l=${dataLayerName}` : '' const gtmAuth = auth ? `>m_auth=${auth}` : '' @@ -53,17 +51,10 @@ export function GoogleTagManager(props: GTMParams) { ) } -export const sendGTMEvent = (data: Object) => { - if (currDataLayerName === undefined) { - console.warn(`@next/third-parties: GTM has not been initialized`) - return - } - - if (window[currDataLayerName]) { - window[currDataLayerName].push(data) - } else { - console.warn( - `@next/third-parties: GTM dataLayer ${currDataLayerName} does not exist` - ) - } +export const sendGTMEvent = (data: Object, dataLayerName?: string) => { + // special case if we are sending events before GTM init and we have custom dataLayerName + const dataLayer = dataLayerName || currDataLayerName + // define dataLayer so we can still queue up events before GTM init + window[dataLayer] = window[dataLayer] || [] + window[dataLayer].push(data) }