Skip to main content
Version: next

Google Tag Manager

Learn how to configure Google Tag Manager with Front-Commerce.

Prerequisites

Before configuring Google Tag Manager in Front-Commerce, ensure that you have:

  • A GTM container ID.

Resources

Installation

pnpm add @analytics/google-tag-manager

Configuration

app/config/analytics.ts
import { type AnalyticsConfig } from "@front-commerce/core/react";

export default {
analytics: {
enable: true,
debug: process.env.NODE_ENV !== "production",
plugins: [
{
name: "google-tag-manager",
needConsent: true,
settings: (authorization, otherAuthorizations) => {
// This ensure an event is pushed with current authorizations
// right after the plugin's initialization.
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: "initConsents",
userConsents: otherAuthorizations,
});
return {
containerId: "GTM-XXXXXX",
};
},
script: () => import("@analytics/google-tag-manager"),
},
],
} satisfies AnalyticsConfig,
};

Setup CSP

You will need to update your CSP to allow your Front-Commerce application to communicate with the GTM servers.

app/config/cspProvider.ts
const appCSPProvider = () => {
return {
name: "cspConfiguration",
values: {
contentSecurityPolicy: {
__dangerouslyDisable: false,
directives: {
scriptSrc: ["www.googletagmanager.com"],
...[],
},
},
},
};
};
export default appCSPProvider;

In GTM, you will then be able to leverage several specific things configured in your plugins.

First, pushing the initConsents event will push the current customer's authorization to your dataLayer as userConsents value. You can reference it from a Variable in GTM. Here is an example:

Screenshot of a GTM Variable configured to expose the user consents

Then, you can leverage the UserConsentUpdated event tracked whenever users update their consent preferences. You could create triggers to enable scripts to load / remove (depending on the userConsents value). Here is an example:

Screenshot of a GTM Trigger configured to detect when users gave their consent to a specific integration

Please note that to retrieve the authorized cookies services in GTM's datalayer, services must be declared in your analytics.js.