Adding Google Analytics to your site

Frontastic doesn't currently fully integrate with TagManagers but you still have the ability to do this so you can track user actions, like newsletter registrations and clicks.

Within your project.yml in the config folder of your project, you can add the below:

data:
    googleTagManager:
        prod: #your tracking ID

Then you'll need to add a TagManager.js to your domain folder, for example, your\_project/src/js/domain. It should define the events that your TagManager is looking for, an example of what you could include is below:

class TagManager {
    constructor (dataLayerIdentifier = 'dataLayer') {
        this.dataLayerIdentifier = dataLayerIdentifier
    }

    /**
     * @param {object[]} productList
     */
    productImpressions = (productList) => {
        this.push({
            event: 'productList',
            ecommerce: {
                impressions: productList,
            },
        })
    }

    push = (data) => {
        const dataLayer = this.getDataLayer()
        if (!dataLayer) {
            return
        }

        dataLayer.push(data)
    }

    getDataLayer = () => {
        if (!window || !window[this.dataLayerIdentifier]) {
            // console.warn('Data layer with identifier "' + this.dataLayerIdentifier + '" could not be accessed')
            return null
        }

        return window[this.dataLayerIdentifier]
    }
}

export default TagManager

Then you'll need to use a Component Injector, see the injecting custom components and reducers article for how to do this.

Once it's all set up in your project, then you can import it in each of the relevant Frontastic componentsFrontastic components - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. by using something like:

import tagManager from '../../../helper/myTagManager'

[...]
        tagManager.productImpressions(
            products.map((product) => {
                let variant = product.variants[0] || {}
                return {
                    name: product.name,
                    id: variant.sku,
                    price: variant.price / 100,
                }
            }),
        )
[...]

You can track most things by using this method. From addtoCart to checkoutStep and purchase.


Did this page help you?