Dan Stroot

Google Tag Manager

Implementing Google Tag Manager in Nextjs.

Date:


Let's cover how to set up Next.JS with Google Analytics using the latest versions (Next.JS 12, Google Tag Manager, and Google Analytics 4).

Background

Google Tag Manager software from Google that allows you to deploy various types of code (tags) to your website. Some good examples of tags would be Google Analytics tracking codes, Google Analytics event codes, Google Ads conversion script and remarketing tags. There are many more types of code that can be added to your website using GTM, including custom codes.

Google Tag Manager and Google Analytics explanation:

Google Tag Manager does not replace Google Analytics. Instead, it helps you easily add Google Analytics tracking to a website and define rules when each tag fires. In other words Google Tag Manager and Google Analytics work together!

Prior to GTM, GA tracking codes had to be hard-coded by a web developer on each individual page. Having hundreds of events is very difficult when it comes to maintaining/updating them. But Google Tag Manager solves this problem because all your tags are stored in one place – your GTM account.

Google Tag Manager also lets you test your tags to make sure they are triggered when you load the right page or click a particular button. Another great benefit: you can change your tags and the way they work without actually changing the source code of your website – instead you just edit tags in GTM user interface and publish changes with a click of a button.

Note in order the setup GTM and GA you will need both a GTM Container ID from your Tag Manager Account (which looks like "GTM-XXXXXXX") and a Google Analytics account and property and a measurement ID. A Google Analytics GA4 ID will look like "G-XXXXXXXXXX". To add GTM to your Nextjs site you will only need the GTM Container ID - the rest of the configuration is done via the GTM UI.

Here we go:

1

Create a Google Tag Manager Account

Create an account, or use an existing account, at Google Tag Manager. A new container is created by default, and you can create additional containers within each account.

A Tag Manager account represents the topmost level of organization. Typically, only one account is needed per company. A Tag Manager account contains one or more containers, and there are specific container types that may be used for websites, AMP pages, Android apps, and iOS apps.

2

Create an Account/Container inside Tag Manager

In Tag Manager, click Accounts and then Create account.

  • Enter an account name and indicate whether you'd like to share data anonymously with Google and others.
  • Enter a descriptive container name and select the type of content: Web, AMP, Android, or iOS. For our purposes choose web..
  • Click Create.
  • Review the Terms of Service and click Yes.

When your new container first loads, you will be prompted with the web container installation code snippet. All you need here is the GTM Container ID.

3

Install the container in your Nextjs app

This is surprisingly the simplest step. Next has an example here. All you have to do is inject the GTM script in your pages\_app.js file using the next/script component.

The Next example also shows that you can manually fire a page view based on a route change event but that is unnecessary - you should just configure GTM to trigger on a history change event as outlined in step 4 below. All you have to do is configure the code below.

_app.js
import Script from 'next/script'
import { ThemeProvider } from 'next-themes'
 
import { Layout } from '../components/Layout'
 
import '../styles/index.css'
 
export default function MyApp({ Component, pageProps }) {
  return (
    <>
      {/* Google Tag Manager */}
      <Script
        id="gtm"
        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', '${process.env.NEXT_PUBLIC_GTM_ACCOUNT}');
          `,
        }}
      />
      <ThemeProvider attribute="class">
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </ThemeProvider>
    </>
  )
}

That's it! Google Tag Manager is installed in your Nextjs app assuming you have set your envronment variable to your GTM Container ID.

4

Add and publish your tags

The rest of the work is done by configuring Google Tag Manager. That is the power of GTM - your coding is done - the rest is all configuration. Most Tag Manager implementations start with a Google Analytics page view tag deployment. Here are step by step instructions for how to deploy a Google Analytics tag.

There is a significant "gotcha" for Nextjs apps - actually all "Single Page Apps" (SPAs). That's because of how SPA's work, and not related to Nextjs per se - when you navigate pages in Nextjs the page view doesn't fire because the page didn't change! If you'd like to fire GTM correctly on each page navigation, be sure to enable the "History Change" trigger, as described here.

Your configuration in GTM should look like this as a bare minumum:

GTM Setup

That's it! Now if you want to get fancy and show your Google Analytics stats inside your site check this out!

Sharing is Caring

Edit this page