React Google Tag Manager with Server-Side Tagging

3.0.1 · active · verified Wed Apr 22

react-server-side-gtm is a React component library designed for integrating Google Tag Manager (GTM) into React applications, with a particular focus on robust server-side tagging capabilities. As an actively maintained fork of the `react-gtm-module` library, it addresses the original project's stagnation by providing more active development and support for newer GTM features. The current stable version is `3.0.1`, with recent `v3.0.0` releases indicating an active development cycle and a steady release cadence. Key differentiators include enhanced support for server-side tagging, offering greater control over data and improved privacy compliance. It also provides flexible options for custom and multiple `dataLayer` configurations, facilitates the integration of additional events, and allows for specific configurations for custom GTM server-side containers and different deployment environments. This library is well-suited for React projects requiring advanced GTM implementations beyond basic client-side tracking, especially those leveraging the performance, security, and data accuracy benefits of server-side Google Tag Manager.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes Google Tag Manager upon component mount, pushes initial page view data to the dataLayer, and demonstrates how to push custom events triggered by user actions or asynchronous operations, incorporating environment variables for GTM ID.

import React, { useEffect } from 'react';
import TagManager from 'react-server-side-gtm';

const GtmInitializer = () => {
  useEffect(() => {
    const gtmId = process.env.NEXT_PUBLIC_GTM_ID ?? 'GTM-XXXXXX'; // Use env var or default

    if (gtmId === 'GTM-XXXXXX') {
      console.warn('GTM ID is not configured. Using placeholder GTM-XXXXXX. Please set NEXT_PUBLIC_GTM_ID.');
    }

    // Initialize GTM when the component mounts
    TagManager.initialize({
      gtmId: gtmId,
      dataLayer: {
        event: 'page_view',
        pagePath: window.location.pathname,
        pageTitle: document.title,
        userId: 'USER_12345', // Example custom user ID
        userProject: 'web_application',
      },
      // Optional: Specify a custom dataLayer name if needed
      // dataLayerName: 'myCustomDataLayer',
      // Optional: Configure custom GTM server-side container endpoint
      // src: 'https://your-custom-gtm-server.com',
    });

    // Simulate a user action after some time
    const timer = setTimeout(() => {
      TagManager.dataLayer({
        dataLayer: {
          event: 'promo_view',
          promotionId: 'SUMMER_SALE',
          position: 'top_banner'
        },
      });
      console.log('Pushed a simulated promo_view event to dataLayer.');
    }, 3000);

    return () => clearTimeout(timer);
  }, []);

  const handleProductClick = (productId) => {
    TagManager.dataLayer({
      dataLayer: {
        event: 'product_click',
        productId: productId,
        category: 'Electronics',
        list: 'Search Results'
      },
    });
    alert(`Product ${productId} clicked! Event sent to GTM.`);
  };

  return (
    <div>
      <h1>Welcome to your Application!</h1>
      <p>This page integrates Google Tag Manager for analytics and server-side tagging.</p>
      <button onClick={() => handleProductClick('P1001')}>View Product P1001</button>
      <p>Open your browser's developer tools and check the Network tab or GTM Debugger for dataLayer events.</p>
    </div>
  );
};

export default GtmInitializer;

view raw JSON →