How to add Google Tag Manager to Next.js on blended blue and black background, with logos.

How to add Google Tag Manager (GTM) to Next.js 13 + 14

· 20 min read

Table of Contents

    Introduction (with Next 14 update)

    Next.js, a popular React framework supporting server-side rendering, has been widely adopted by developers to build robust applications. GTM, on the other hand, has become an indispensable tool for SEO specialists and digital marketers, allowing for efficient tracking of user interactions and metrics on websites, thereby enabling data-informed decision-making and strategies.

    Update 10/26 2023 - Next.js 14 Released

    Next.js 14 has been released, including Server Actions (Stable) and Partial Prerendering (Preview). The guidance in this post still applies.

    GTM is pivotal for adding Google Analytics (now Google Analytics 4) to your website, and its implementation in Next.js 13 / 14 can be a source of confusion due to multiple methods available. This guide aims to demystify this process and give a straightforward approach to integrating GTM with Next.js 13 / 14.

    We will provide a step-by-step guide on creating GTM and GA4 accounts, configuring the right tags and triggers, and adding the GTM script to your Next.js 13 / 14 app, leveraging the built-in tracking and Enhanced Event Measurement features of GA4. We also address common issues faced during the implementation process and suggest solutions to help ensure a smooth integration.

    Whether you're a web developer eager to expand your Next.js knowledge, an SEO specialist interested in accurate tracking, or a digital marketer looking to optimize data-driven strategies, this guide has everything you need to successfully add GTM to Next.js 13 / 14.

    Understanding Google Tag Manager and its Role in Analytics

    Google Tag Manager (GTM) is a powerful tool designed to enable web developers, SEO specialists, and digital marketers to effectively and efficiently manage and deploy tags on a website or mobile app. Tags, in this context, refer to snippets of JavaScript code or tracking pixels from third-party tools that support various functionalities including analytics, advertising campaigns tracking, testing, and more.

    GTM greatly simplifies the process of managing these tags by providing a unified platform where all tags are centrally managed, eliminating the need for hard-coding tags directly into your website's codebase. This not only makes your codebase cleaner, but also reduces the likelihood of human error while simultaneously speeding up your website's load time – a factor directly correlating with website performance and user experience.

    In the world of analytics, GTM plays a key role. It provides an easy way to track various user interactions and metrics, from simple ones like page views and clicks, to more complex ones such as ecommerce transactions, user login status, or interaction with a specific webpage element.

    For instance, when integrated with Google Analytics, GTM allows SEO specialists and digital marketers to gain valuable insights about their audience, including where they come from, how they behave on the website, and what actions they take. These data points can be instrumental in making data-informed decisions, tailoring user experience, and optimizing marketing strategies.

    It’s worth noting that as the web evolves, so does the tracking technology. One notable evolution is the migration from Google Analytics Universal Analytics (UA) to Google Analytics 4 (GA4). The new GA4 is built on the foundation of the 'App + Web' property introduced by Google in 2019 and represents a more holistic approach to data collection across websites and mobile apps.

    When adding GTM to Next.js 13 / 14, it's crucial to ensure GA4 is set up correctly within GTM. GA4 has several built-in tracking features, including the Enhanced Event Measurement feature, which automatically detects and tracks specific user interactions, such as scrolls, video engagement, file downloads, and more, without needing to manually code each event. This is part of the reason why the implementation of GTM with GA4 in Next.js 13 / 14 is a beneficial move for any website looking to harness the power of advanced analytics.

    In the next sections, we will guide you step-by-step on how to add GTM to a Next.js 13 / 14 application, effectively paving the way for a successful GA4 setup and a future-proof approach to website tracking and analytics. Stay tuned.

    Why integrate GTM with Next.js 13 / 14?

    Integrating Google Tag Manager (GTM) with Next.js 13 / 14 combines the power of one of the most popular JavaScript frameworks with the comprehensive analytical tooling provided by GTM. This fusion offers several benefits to web developers, SEO specialists, and digital marketers.

    Next.js 13 ( and 14) is a versatile framework that empowers developers to build scalable, high-performance, and SEO-friendly web applications. It brings features such as server-side rendering (SSR), static site generation (SSG), and API routes, allowing for a seamless blend of server-side and client-side rendering depending on the application needs. This versatility makes Next.js a preferred choice for many developers, making it essential for GTM to work seamlessly within this framework.

    As we dive into the reasons for integrating GTM with Next.js 13 / 14, it's important to acknowledge that the interplay between web development and digital marketing has grown tighter over the years. The success of most modern web applications and marketing campaigns heavily relies on data-driven strategies and decisions. Here's where GTM shines.

    By integrating GTM with Next.js 13 / 14, developers and marketers alike can leverage GTM's capability to manage and deploy tags, thereby capturing important user metrics and interactions. Such data is invaluable for improving website performance, optimizing user engagement, and tailoring marketing strategies.

    With GTM, you can add, update, or remove tags without going through the lengthy process of changing the source code and deploying your Next.js application. This speeds up the process of managing and implementing changes, enabling faster response to marketing requirements and improving overall website maintainability.

    However, the primary reason for integrating GTM with Next.js 13 / 14 is the need for thorough and accurate tracking. Implementing GTM correctly helps to ensure that the data collected is reliable and meaningful for decision-making. GTM's advanced features, including event tracking and variables, provide insights into the behavior of your users, helping you understand what works and what needs improvement.

    Moreover, during the transition to Google Analytics 4 (GA4), the role of GTM is becoming increasingly vital. GA4, built for a future of privacy-focused measurement, offers new ways to track user interactions such as the 'Enhanced Event Measurement'. This feature, as mentioned earlier, has the ability to automatically track certain events without the need for additional coding, making GA4 with GTM an efficient and future-proof solution for analytics.

    In summary, integrating GTM with Next.js 13 / 14 aids in the accurate tracking of user interactions, simplifies tag management, accelerates development and marketing cycles, and prepares your applications for future analytics improvements. In the following sections, we will guide you through the process of setting up GTM with Next.js 13 / 14, so that you can reap all these benefits and more.

    Setting up GTM and GA4 accounts

    Before starting the integration process, you need to have active Google Tag Manager (GTM) and Google Analytics 4 (GA4) accounts. Let's go through the process of setting up both.

    Setting Up GTM Account:

    1. Visit the Google Tag Manager homepage and click on 'Start for Free' if you are a new user. Existing users can 'Sign in'.

    2. Enter the requested account details including the name of your company, the country of your location, and options for data sharing.

    3. Next, you need to set up a container for your website. Enter the name of your website in the 'Container name' field and select 'Web' for 'Where to Use Container'.

    4. Click 'Create' and accept the GTM Terms of Service Agreement for your country of residence.

    5. A pop-up with a GTM container snippet will appear on your screen. You'll need this GTM ID when integrating GTM with your Next.js 13 / 14 application. For now, keep it saved or leave the window open, as you might need to refer back to it.

    Setting Up GA4 Account:

    1. Go to Google Analytics and sign in to your account. If you don't have one, you will need to create it.

    2. Click on the 'Admin' option at the bottom left corner of the page.

    3. In the account column (the first column), click on '+ Create Account', then enter your account details such as your account name and how you plan to use your Google Analytics account.

    4. Proceed to 'Property Setup' where you'll need to provide information on your industry category and reporting time zone, along with selecting GA4 as your preferred property type.

    5. Click 'Next' and provide more information about your business, then click 'Create'. Confirm your settings and agreements as prompted.

    6. Once done, you'll be directed to the new GA4 property with a 'Data Stream' section where you can enter your website URL and stream name.

    7. A GA4 measurement ID will be generated for you – like the GTM container snippet, this ID is important for integrating GA4 with Next.js 13 / 14. Keep this ID handy.

    With your GTM and GA4 accounts set up, you are now ready for the next step: integrating GTM into your Next.js 13 / 14 application. Stay tuned as we delve into the specifics of this process in the coming segments of this guide.

    Adding the GTM Script to Your Next.js 13 / 14 Application

    Now that our GTM and GA4 accounts are ready, we're going to learn how to incorporate the GTM script into our Next.js 13 / 14 application. This step is crucial and must be done correctly to ensure that our GTM is operating as envisaged.

    Here's a summary of the steps required:

    6 steps for adding GTM to a Next.js 13 application

    As you can see from the first step - before we begin, you must gather your Google Tag Manager (GTM) ID that you saved earlier from your GTM account. It should look like `GTM-XXXX`.

    1. Install Next.js Script Component

    To allow us to use GTM, we'll first need to install Next.js script component in our application. This provides us the best and optimized way of loading scripts in our Next.js application.

    You can add it to your project by running the following command in your project directory:

    npm install next/script

    2. Create a GTM Component

    Create a component in /components called gtmComponent.js:

    // create a client component
    "use client"
    import { pageview } from "lib/gtm"
    import { usePathname, useSearchParams } from "next/navigation"
    import Script from "next/script"
    import { useEffect } from "react"
    
    export default function Analytics() {
      const pathname = usePathname()
      const searchParams = useSearchParams()
    
      useEffect(() => {
        if (pathname) {
          pageview(pathname)
        }
      }, [pathname, searchParams])
    
      if (process.env.NEXT_PUBLIC_VERCEL_ENV !== "production") {
        return null
      }
    
      return (
        <>
          <noscript>
            <iframe
              src={`https://www.googletagmanager.com/ns.html?id=GTM-xxxx`}
              height="0"
              width="0"
              style={{ display: "none", visibility: "hidden" }}
            />
          </noscript>
          <Script
            id="gtm-script"
            strategy="afterInteractive"
            dangerouslySetInnerHTML={{
              __html: `
        (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-xxxx");
      `,
            }}
          />
        </>
      )
    }

    In the script source URL, replace `GTM-xxxx` with your actual GTM ID. If you're planning on pushing your code to a public repository, consider using environment variables to hide sensitive data like your GTM ID.

    3. Create a gtm.js file

    Add the following DataLayer to gtm.js within /lib (as you saw, this was imported into the component in the previous step):

    type WindowWithDataLayer = Window & {
      dataLayer: Record<string, any>[]
    }
    
    declare const window: WindowWithDataLayer
    
    export const pageview = (url: string) => {
      if (typeof window.dataLayer !== "undefined") {
        window.dataLayer.push({
          event: "pageview",
          page: url,
        })
      } else {
        console.log({
          event: "pageview",
          page: url,
        })
      }
    }

    3. Import the component and render in your app/layout.tsx

    The extra code in your app/layout.tsx should be

    import Analytics from '@/components/gtmComponent';
    import { Suspense } from 'react'
    
    // To be placed within the <body> tag of your layout.tsx
    
    <Suspense>
    <Analytics />
    </Suspense>

    With the steps above, you've included GTM into your Next.js 13 / 14 application. The application now sends data to your GTM container which you can use to track events or user behavior. However, as you move ahead, the GTM integration may lead to various issues depending upon the complexity of your Next.js application. Later on, we'll look at some common issues and resolve them.

    Leveraging built-in tracking and Enhanced Event Measurement features of GA4

    As mentioned earlier, the transition from Google Universal Analytics to Google Analytics 4 (GA4) brings in a whole slew of new features designed to improve your tracking capabilities. One of these is the Enhanced Event Measurement feature. This section is dedicated to helping you understand and leverage these features with Next.js 13 / 14 and GTM.

    Enhanced Event Measurement allows automatic tracking of specific user interactions, such as scrolls, video engagement, file downloads, outbound clicks, and more. The beauty of this feature is that it automatically tracks these events without you needing to manually code each one. In essence, it makes your tracking efforts more efficient and robust.

    To enable or disable Enhanced Event Measurement, you'll need to follow these steps:

    1. Log in to your GA4 account and navigate to 'Admin'.
    2. In 'Property column', select 'Data Streams'.
    3. Click on your web data stream.
    4. Scroll down to find 'Enhanced Measurement', click on the settings gear icon to open the 'Enhanced Measurement' configuration page.
    5. Here, you can toggle on or off any of the available events as per your needs.

    Remember, leveraging these features effectively requires that your GTM is properly integrated and is capturing the desired data accurately. Errors in integrating GTM and GA4 can compromise the quality of the data collected, leading to less reliable insights.

    In the context of Next.js 13 / 14, it's crucial to ensure the GTM script is properly embedded within your application. Missed or incorrect implementation can lead to data not being sent or registered within your GA4 account. Also, be sure to regularly monitor and test your GTM setup using GTM's preview mode to spot and rectify any potential errors early.

    Essentially, it's about making the best of both worlds. With Next.js 13 / 14, you get a fast, efficient, user-friendly application, while with GA4 and its Enhanced Event Measurement, you get a powerful tracking and analysis tool. Together with a correctly integrated GTM, you'll have a wealth of actionable data at your disposal.

    Finally, it's worth mentioning that while GA4's automated tracking is incredibly useful, it doesn't mean you can't still track custom events. GA4 is versatile and allows you to define and track custom events based on specific activities relevant to your application, providing even more granularity and control over your data.

    In the next sections of this guide, we will walk you through some common issues that might arise during the GTM integration process with Next.js 13 / 14and how to troubleshoot them in order to ensure smooth and accurate data tracking.

    Troubleshooting common issues in GTM integration with Next.js 13 / 14

    As you stride ahead with the integration of GTM in your Next.js 13 / 14 application, you might encounter some common issues. These could range from GTM not loading correctly, tracking inconsistencies, to even Next.js specific problems such as duplicate tags being injected on every page navigation. Troubleshooting these issues is an integral part of ensuring accurate and effective tracking. In this section, we'll go through some common challenges and provide potential solutions.

    GTM Not Loading Properly

    One of the primary issues developers face during the integration process is the GTM script not loading properly or not appearing on the front end. This is often an indication that the GTM code is not properly injected.

    If you're experiencing this, first ensure that the GTM container ID (GTM-XXXX) has been correctly inserted into your source code.

    Also, verify that the GTM script is included in the proper file in your Next.js project. For most Next.js 13 / 14 applications, it's best to import the component into the `layout.tsx` file within the `app` directory. If this file doesn't exist in your project, simply create it and add the script as discussed in the previous section.

    Tracking Inconsistencies

    Another common issue involves inconsistencies with tracking events or user behaviors. This might be due to misconfigured events in GTM.

    For complex event tracking, like user clicks or form submissions, make sure you set up the right trigger conditions in GTM. For example, a click event should ideally be triggered by an 'All Elements' click trigger, and you should specify the correct conditions to match the clicked element.

    If you're still experiencing inconsistencies, try using the 'Preview' option in GTM. This opens your website in a new tab with a debug window at the bottom. The debug window shows all tags, triggers, and variables for each page, allowing you to identify any issues or discrepancies.

    Duplicate Tags on Page Navigation

    You might encounter the issue of duplicate tags being injected on every page navigation. This issue stems from the new Script component's default behavior in Next.js.

    To solve this problem, set an `id` attribute for the Script component to avoid duplication. The Next.js script component will then ensure that only one script with the matching ID is included, eliminating the issue of duplicate tags.

    Furthermore, for eslint users, remember to install eslint for your Next.js project and adjust your configurations as necessary to handle the added scripts and tag management integration.

    Interference from Browser Extensions

    Occasionally, browser extensions can interfere with tracking scripts, blocking them from loading and running correctly. This issue can be challenging to pinpoint because it can appear as though your tracking scripts have been installed incorrectly when they're merely being blocked.

    If you notice that your tracking isn't working, try using an Incognito or Private window without any extensions active to see if the issue persists.

    Lack of Suspense Boundary (IMPORTANT GOTCHA)

    DO NOT REMOVE THE SUSPENSE BOUNDARY FROM LAYOUT.TSX WHEN YOU RENDER THE COMPONENT.

    If you do and you check 'view source', it will say there is a Next.js error (as follows):

    __next_error_ in view source after adding GTM within Next 13 / 14

    The application will fall back to client-side rendering. This is quite difficult to pick up without specifically looking for the error (I know from painful experience).

    Summary

    Whilst it's true that integrating GTM with Next.js 13 / 14 may present some challenges, with the right guidance, it can be tackled effectively. Remember to keep referring to GTM logs and the 'Preview' mode to debug any inconsistencies or issues. Ideally, with attention to detail and careful implementation, your GTM should be up and running smoothly with Next.js 13 / 14, tracking events and user interactions that will help inform your marketing strategies and optimize user experience.

    Richard Lawrence

    About Richard Lawrence

    Constantly looking to evolve and learn, I have have studied in areas as diverse as Philosophy, International Marketing and Data Science. I've been within the tech space, including SEO and development, since 2008.
    Copyright © 2024 evolvingDev. All rights reserved.