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) }