Search code examples
next.jsgoogle-tag-manager

How to load GTM with NextJS Script component?


I recently came across the script component in NextJS (https://nextjs.org/docs/basic-features/script)

I wanted to know if it's possible to load Google tag manager using this component.


Solution

  • You can add the following <Script> tags within your _app.tsx file.

    // pages/_app.tsx
    export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
      const getLayout = Component.getLayout ?? ((page) => page)
    
      return getLayout(
        <>
          <Script id="google-site-tag"
            strategy='lazyOnload'
            src={`https://www.googletagmanager.com/gtag/js?id=${GOOGLE_TAG_ID}`}
          />
          <Script id="google-analytics" strategy='lazyOnload'>
            {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', '${GOOGLE_TAG_ID}');
            `}
          </Script>
          <Component {...pageProps} />
        </>
      )
    }