How to add Google Tag Manager to Next.js

Connecting Next.js to Google Tag Manager (GTM) is easy with built-in <Script> component

Aliaksandr TsykinAliaksandr Tsykin|
How to add Google Tag Manager to Next.js

Intro

If you already have your Next.js app set up, you might want to add Google Tag Manager (GTM) to it.

You can easily do this with built-in <Script> component of Next.js.

Find and copy GTM container installation script

First, you need a script that's required for GTM to work. Here's a screenshot of where you can find this Google Tag Manager installation script:

Screenshot of where to find GTM container installation script

Screenshot of where to find GTM container installation script

After clicking on the spot that's highlighted on the screenshot, you will see a script that looks like this. Copy this script and go to the next step.
Screenshot of a popup window with GTM container installation script

Screenshot of a popup window with GTM container installation script

Add this script to main layout file

In the /app folder of your Next.js app, you will find app/layout.js or app/layout.tsx file. This is the main layout file of your app you can add the script to.
In order to add this script to <head> of your layour, you need to:
  • import <Script> component from next/script
  • add <Script> component to the <body> of the page
  • pass this script as a {children} prop to <Script> component
  • add strategy="beforeInteractive" prop to ensure that this script will be placed in the <head> of the page
Here's a code snippet that shows a sample layout file with a <Script> component added:
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <Script id="gtm" strategy="beforeInteractive">
          {`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
          new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
          j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
          'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','GTM-124RPQXB');`}
        </Script>
      </body>
    </html>
  );
}

Test if the script works

To check if the script works, you paste URL to your page in this field and click "Test".

If it works, you will see a green checkbox.

Screenshot of a popup window with option to test GTM container installation script on a given URL

Screenshot of a popup window with option to test GTM container installation script on a given URL

Congratulations! You have successfully added Google Tag Manager to your Next.js app.

Resources

Table of Contents

Blog by Aliaksandr Tsykin

Learn web development and digital marketing with me!