Google Analytics integration not working in NextJS app

I am working on a NextJS app and want to integrate Google Analytics to track ecommerce data. I have set up a Google Analytics account (Universal Analytics) and followed the steps in this article. Ecommerce tracking is enabled in both Snipcart and GA. However, I still get:

snipcart.js:1 e-commerce tracking is enabled but no service found

and GA is not tracking any ecommerce data. Any ideas?

The code I’m using:

_app.js:

import { useEffect } from 'react';
import Head from 'next/head';
import Script from 'next/script';

const MyApp = ({ Component, pageProps }) => {
  useEffect(() => {
    window.dataLayer = window.dataLayer || [];
    function gtag() {
      dataLayer.push(arguments);
    }
    gtag('js', new Date());

    gtag('config', 'UA-65759895-2');
  }, []);

  return (
    <>
      <Head>
        <link rel="preconnect" href="https://app.snipcart.com" />
        <link rel="preconnect" href="https://cdn.snipcart.com" />
        <link
          rel="stylesheet"
          href="https://cdn.snipcart.com/themes/v3.3.0/default/snipcart.css"
        />
      </Head>

      <Component {...pageProps} />

      {/* Google Analytics gtag */}
      <Script
        async
        src="https://www.googletagmanager.com/gtag/js?id=UA-65759895-2"
      />

      {/* Snipcart code */}
      <Script src="https://cdn.snipcart.com/themes/v3.3.0/default/snipcart.js" />
      <div
        id="snipcart"
        data-api-key={process.env.NEXT_PUBLIC_DEVELOPMENT_SNIPCART_API_KEY}
        data-config-modal-style="side"
        data-currency="eur"
        data-config-add-product-behavior="none"
        hidden
      ></div>
    </>
  );
};

export default MyApp;

Hi @PPlytas,

This warning is logged when the Google Site Tag is not present on the website. You can test this yourself by going to your website and typing window.gtag or gtag in the console. If the returned value is undefined then the script is not correctly installed.

Could you double-check your setup?

1 Like

Thanks @dominic

Turns out the gtag function wasn’t defined in the window level as you mentioned.

Made the following change in my code and it works now:

useEffect(() => {
    window.dataLayer = window.dataLayer || [];
    window.gtag = function () {
      dataLayer.push(arguments);
    };
    window.gtag('js', new Date());
    window.gtag('config', '<GA-id>');
  }, []);