Set GA in Nuxt3 with Nuxt Scripts

Nuxt

Language :

Hi I’m Lovefield.

I finded about the "Nuxt Script"(link) module when I updated my blog. "Nuxt scripts" is a module created to use third-party scripts in the Nuxt application. You can easily import third-party scripts that were previously called using useHead into settings, providing compatibility between client and server-side environments.

Nuxt Scripts Home Page

Before I knew "Nuxt Scripts", I used Google Analytics And Google Adsense as next:

Google Analytics

TypeScript

useHead({
    script: [
        {
            src: `https://www.googletagmanager.com/gtag/js?id=${config.public.googleAnalyticsId}`
        }
    ]
});

onMounted(()=>{
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }
    gtag("js", new Date());
    gtag("config", config.public.googleAnalyticsId, {
        page_title: document.title,
        page_herf: window.location.href.split(window.location.hostname)[1],
        page_url: window.location.pathname,
    });
});

Google Adsense

HTML, XML

<template>
    <ins class=”adsbygoogle” style=”display:block” :data-da-client=”config.public.adclient” :data-ad-slot=”config.public.adslot” data-ad-format=”auto” data-full-width-responsve=”true”></ins>
</template>

<script setup lang=”ts>
const config = useRuntimeConfig();

onMounted(()=>{
    (adsbygoogle = window.adsbygoogle || []).push({});
});
</script>

The biggest problem with the above codes is that they do not recognize the type. So we use @ts-ignore or @ts-nocheck to hide an error. But now we know "Nuxt Scripts"!

Nuxt Scripts install

Shell Session

bun add @nuxt/scripts

First, add the "Nuxt Scripts” module.

nuxt.config.ts

TypeScript

export default defineNuxtConfig({
    …
    modules: [
        “@nuxt/scripts”
    ],
    scripts: {
        registry: {
            googleAnalytics: {
                id: process.env.GOOGLE_ANALYTICS_ID,
            },
        },
    },
});

Set "Nuxt Scripts" in the nuxt.config.ts file. And set Google Analytics too. In this case Google Analytics runs automatically on all pages.

layout/default.vue

HTML, XML

<script setup lang=”ts>
const { proxy } = useScriptGoogleAnalytics();

useScriptEventPage(({ title, path }) => {
   proxy.gtag("set", {
       is_login: userStore.isLogin,
       page_title: title,
       page_herf: path,
       page_url: path.split("?")[0],
   });
});
</script>

I set the default layout file to above code. Import useScriptGoogleAnalytics to proxy. The proxy has a gtag function. The useScriptEventPage function detects the route change inside Nuxt. page_view is already scheduled to be called, so use set to specify the global value. This way, the GA setting is over.

ads.vue

HTML, XML

<template>
    <ScriptGoogleAdsense data-ad-client="your-client-code" data-ad-slot="your-slot-code" data-ad-format="auto" />
</template>

Google Adsense case is easier to set than Google Analytics. Just using components!

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.