React Google Tag Manager with Server-Side Tagging
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
-
ReferenceError: TagManager is not defined
cause The `TagManager` object was not correctly imported or the library was not installed.fixEnsure you have `npm install react-server-side-gtm` and use `import TagManager from 'react-server-side-gtm';` at the top of your file. -
GTM events are not appearing in Google Analytics, Tag Manager Debugger, or your GTM server container.
cause Incorrect `gtmId`, missing `src` for server-side tagging, or events are not correctly pushed to the dataLayer.fixDouble-check your `gtmId` for typos. If using server-side tagging, ensure the `src` parameter in `TagManager.initialize` points to your active GTM server container URL. Verify that `TagManager.dataLayer` calls include an `event` key and necessary parameters. -
Custom dataLayer values (e.g., `userId`, `userProject`) are not present or are overwritten in GTM.
cause The initial `TagManager.initialize` call didn't include the custom dataLayer, or a subsequent `TagManager.initialize` call overwrote it instead of pushing new data.fixEnsure all initial `dataLayer` variables are passed in the `dataLayer` object during the initial `TagManager.initialize` call. For subsequent updates, use `TagManager.dataLayer({ dataLayer: { /* new data */ } })` to merge new data without overwriting.
Warnings
- breaking This library is a fork of `react-gtm-module`. While the API is largely compatible, users migrating from the original package should review documentation for potential behavioral changes, new features, or slight API discrepancies introduced in `v3.0.0` and later.
- gotcha For server-side tagging to function correctly, your Google Tag Manager container and Google Cloud Platform setup must be configured specifically for server-side GTM. Simply installing this library is not sufficient.
- gotcha Calling `TagManager.initialize` multiple times with different dataLayer configurations can lead to unexpected behavior or data loss, as it re-initializes the GTM script and dataLayer.
Install
-
npm install react-server-side-gtm -
yarn add react-server-side-gtm -
pnpm add react-server-side-gtm
Imports
- TagManager
const TagManager = require('react-server-side-gtm');import TagManager from 'react-server-side-gtm';
- TagManager.initialize
TagManager.init({ gtmId: 'GTM-XXXXXX' });TagManager.initialize({ gtmId: 'GTM-XXXXXX' }); - TagManager.dataLayer
TagManager.initialize({ dataLayer: { event: 'my_event' } });TagManager.dataLayer({ dataLayer: { event: 'my_event' } });
Quickstart
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;