DEV Community

Abdur Rakib Rony
Abdur Rakib Rony

Posted on

Elevate Your Next.js E-commerce App with Google Tag Manager

Google Tag Manager simplifies the process of adding and updating tags (snippets of code) on your website without modifying the source code. It's a game-changer for marketers and analysts who need agility in tracking various events.

Integrating GTM with Next.js:

Next.js, a React framework, has gained popularity for its simplicity and performance optimizations. Let's see how we can seamlessly integrate GTM:

import { GoogleTagManager } from '@next/third-parties/google'
import { Suspense } from "react";

// In your layout component
<Suspense fallback={null}>
  <GoogleTagManager gtmId="GTM-******" />
</Suspense>
Enter fullscreen mode Exit fullscreen mode

Here, we're using @next/third-parties/google, an official package that simplifies third-party script integration in Next.js. The GoogleTagManager component takes your GTM container ID (gtmId). We wrap it in a Suspense component with a null fallback to avoid any layout shifts during loading.

Tracking Product Views:

"use client";
import { useEffect } from "react";

// In your product detail component
useEffect(() => {
  if (product) {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ ecommerce: null });
    window.dataLayer.push({
      event: "view_item",
      ecommerce: {
        currency: "BDT",
        value: product?.price,
        items: [
          {
            item_id: product?._id,
            item_name: product?.title,
            item_category: product?.category,
            item_variant: product?.category || "",
            price: product?.price,
            quantity: product?.quantity,
          },
        ],
      },
    });
  }
}, [product]);
Enter fullscreen mode Exit fullscreen mode

Breaking down the code:

"use client:" This is a Next.js directive indicating that the following code should run on the client-side.
useEffect: A React hook that runs after the component renders. Here, it runs when the product changes.
window.dataLayer: This is how GTM receives data. We initialize it if it doesn't exist.
dataLayer.push({ ecommerce: null }): This clears any previous ecommerce data to avoid conflicts.
dataLayer.push({ ... }): We push the view_item event data.

event: "view_item" is a standard GA4 ecommerce event.
ecommerce.currency: The currency code (BDT for Bangladeshi Taka).
ecommerce.value: The discounted price of the product.
ecommerce.items: An array of items viewed. In this case, just one product. item_id, item_name, item_category, item_variant, price, and quantity are standard GA4 product properties.

Top comments (0)