28/10/2024

Nuxt for multi domain multi app building : integrating analytics

It's easy to integrate google analytics (GA) or Google Tag Manager in Nuxt applications, as there a plugins for that, and many tuts, like this one that describes how to include a script from nuxt config file. What's not covered though, is the possibility to use GTM , for instance, in a single layout using useHead script integration.

This article is part of many tips on how to work with nuxt on multi domain multi language with one single codebase. I've already talked about language issues, which, similarly, I solved using my own code base instead on relying on third party plugins, which are very powerful but sometimes too much.

Here, we find it's very simple to integrate GTM via usehead, this time in your vue file (layout or page depending on your scope requirements for GTM)

useHead({
  script: [{ children: "  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':" +
        "new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0]," +
        "j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=" +
        "'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);" +
        "})(window,document,'script','dataLayer','GTM-XXXXXX');console.log('GTM-XXXXXXX')"+
" " }],
});

then in your template, just include the iframe as described buy GTM docs

 <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXX"
                    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>

Leave a Comment

Your email address will not be published. Required fields are marked *

To top