Seamless Integration of Google Tag Manager (GTM) and Facebook Pixel in Next.js Applications

  • 11 March 2024

  • Wendy Parkes

  • 7 minutes read

  • 1379 words

Laptop, phone and coffee

Integrating Google Tag Manager (GTM) and Facebook Pixel into your Next.js application is crucial for tracking user interactions and optimizing marketing efforts. This guide will walk you through the process of setting up these tools, ensuring they work flawlessly without duplications or performance issues.

Integrating tracking tools like Google Tag Manager and Facebook Pixel is essential for monitoring user behavior and optimizing your marketing strategies. Next.js, a popular React framework, allows for efficient integration of these tools. In this blog, we'll cover how to incorporate GTM and Facebook Pixel into your Next.js application, addressing common pitfalls and best practices.

Why Use Google Tag Manager and Facebook Pixel?

Google Tag Manager (GTM):

Simplifies the management of marketing and analytics tags without needing to modify the codebase each time.

Facebook Pixel:

Tracks user interactions and conversions from Facebook ads, helping optimize ad performance and audience targeting.

Setting Up Google Tag Manager in Next.js

Step 1: Install GTM Script Using useEffect

To ensure that the GTM script is included properly and only once, use the useEffect hook in _app.js. Here’s how you can do it:

import { useEffect } from 'react';

export default function App({ Component, pageProps }) {
  useEffect(() => {
    // Google Tag Manager (GTM) initialization
    (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-N8Q82BCF');
  }, []);

  return <Component {...pageProps} />;
}

Step 2: Add GTM Noscript Tag

Include the noscript tag in your _app.js to handle cases where JavaScript is disabled:

import Head from 'next/head';
export default function App({ Component, pageProps }) {
  return (
    <>
      <Head>
        <noscript>
          <iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-N8Q82BCF"
            height="0"
            width="0"
            style={{ display: 'none', visibility: 'hidden' }}
          ></iframe>
        </noscript>
      </Head>
      <Component {...pageProps} />
    </>
  );
}

Integrating Facebook Pixel in Next.js

Step 1: Initialize Facebook Pixel Using useEffect

Add the Facebook Pixel initialization in the useEffect hook to ensure it runs once:

import { useEffect } from 'react';

export default function App({ Component, pageProps }) {
  useEffect(() => {
    // Facebook Pixel initialization
    (function (f, b, e, v, n, t, s) {
      if (f.fbq) return;
      n = f.fbq = function () {
        n.callMethod
          ? n.callMethod.apply(n, arguments)
          : n.queue.push(arguments);
      };
      if (!f._fbq) f._fbq = n;
      n.push = n;
      n.loaded = !0;
      n.version = '2.0';
      n.queue = [];
      t = b.createElement(e);
      t.async = !0;
      t.src = v;
      s = b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t, s);
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '527596403291726');
    fbq('track', 'PageView');
  }, []);

  return <Component {...pageProps} />;
}

Step 2: Add Facebook Pixel Noscript Tag

Include the noscript tag in _app.js for scenarios where JavaScript is disabled:

import Head from 'next/head';

export default function App({ Component, pageProps }) {
  return (
    <>
      <Head>
        <noscript>
          <iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-N8Q82BCF"
            height="0"
            width="0"
            style={{ display: 'none', visibility: 'hidden' }}
          ></iframe>
        </noscript>
      </Head>
      <Component {...pageProps} />
    </>
  );
}

Integrating Facebook Pixel in Next.js

Step 1: Initialize Facebook Pixel Using useEffect

Add the Facebook Pixel initialization in the useEffect hook to ensure it runs once:

import { useEffect } from 'react';

export default function App({ Component, pageProps }) {
  useEffect(() => {
    // Facebook Pixel initialization
    (function (f, b, e, v, n, t, s) {
      if (f.fbq) return;
      n = f.fbq = function () {
        n.callMethod
          ? n.callMethod.apply(n, arguments)
          : n.queue.push(arguments);
      };
      if (!f._fbq) f._fbq = n;
      n.push = n;
      n.loaded = !0;
      n.version = '2.0';
      n.queue = [];
      t = b.createElement(e);
      t.async = !0;
      t.src = v;
      s = b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t, s);
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '527596403291726');
    fbq('track', 'PageView');
  }, []);

  return <Component {...pageProps} />;
}

Step 2: Add Facebook Pixel Noscript Tag

Include the noscript tag in _app.js for scenarios where JavaScript is disabled:

import Head from 'next/head';

export default function App({ Component, pageProps }) {
  return (
    <>
      <Head>
        <noscript>
          <img
            height="1"
            width="1"
            style={{ display: 'none', visibility: 'hidden' }}
            src="https://www.facebook.com/tr?id=527596403291726&ev=PageView&noscript=1"
            alt="facebook"
          />
        </noscript>
      </Head>
      <Component {...pageProps} />
    </>
  );
}

Common Pitfalls and Troubleshooting

Issue: Duplicate Script Tags

If you observe duplicate script tags for GTM or Facebook Pixel, it’s often due to the following:

Multiple useEffect Executions: Ensure useEffect is not running multiple times. Place initialization code in _app.js to avoid unnecessary re-renders.

Component Re-Mounting: Avoid unnecessary re-mounting of components that may trigger useEffect multiple times.

Fix for Duplicate GTM Scripts

If GTM scripts are duplicated, ensure that you are not initializing GTM more than once and check for any other parts of your application that might also be including the GTM script

Conclusion

Integrating GTM and Facebook Pixel into your Next.js application enhances your ability to track and optimize user interactions. By carefully managing script inclusion and ensuring proper placement of noscript tags, you can avoid common pitfalls and ensure accurate tracking.

Following these best practices will help you implement a robust tracking setup in your Next.js application, providing valuable insights into user behavior and campaign effectiveness