johannschopplich / nuxt-gtag

🔸 Google Analytics & Ads integration made easy

Home Page:https://developers.google.com/tag-platform/gtagjs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Set Gtag ID dynamically in the client, instead of module options

ILLuMiNaTe7 opened this issue · comments

Describe the feature

We were wondering if its possible to set the GTAG ID Dynamically.

We basically have a white label website where every domain that points towards the server has different layout and content.

Really hope this is possible :)

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

We were wondering if its possible to set the GTAG ID Dynamically.

What do you mean by that? At runtime instead of build time? You can adapt the GTAG ID based on the NUXT_PUBLIC_GTAG_ID variable:

# Sets the `gtag.id` module option
NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX

Hey there, I've implemented an optional ID parameter for useGtagConsent: 7859fe6

Make sure to set initialConsent to false in the module options. Then, you can fetch your data and initialize a specific Gtag ID:

useGtagConsent(true, { id: "XXX" })

Since no Gtag instance has been initialized until that point, it will do so for the custom ID. Hope that helps!

Hi @johannschopplich ,

I've tested the implementation however I'm encountering a weird issue that may be related to #19 .

For some reason, the script doesn't get injected into the head with your instructions. The only time it gets injected is when I do set the ID in the Nuxt config. However, then it also injects it 2 times. One time with the Nuxt config and another time with the new implementation.

As a result, the first collection for analytics also uses injection originating from Nuxt config. (G-XXXXXXX)

<script type="text/javascript" async="" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX&amp;l=dataLayer&amp;cx=c"></script>
<script src="https://www.googletagmanager.com/gtag/js?id=G-4DJ1K7LHXI"></script>

This is my implementation:
Nuxt Config:

export default defineNuxtConfig({
  ...
  modules: [
    ...
    'nuxt-gtag'
  ],
  gtag: {
    initialConsent: false
    // id: 'G-XXXXXXXXXX' <<< If this is added it does work except for the first collection.
  }
  ...
})

Plugin:

export default defineNuxtPlugin(async () => {
   // Do some magic to get the GTAG ID:
   useGtagConsent(true, { id: 'G-4MJ1K7LSXM' })
})

You are right, there was a bug in my code, which I just fixed.

You won't have to add the Gtag ID to your Nuxt config, but can dynamically enable Gtag in the client.

Thanks for the quick handling. After testing the code it seems you have accidentally removed the import of defineNuxtPlugin.

This causes the following error:

Uncaught ReferenceError: defineNuxtPlugin is not defined
    at plugin.client.mjs?v=2faffd2d:1:1

Thanks for fixing this :)