search

Home  >  Q&A  >  body text

Send user_id to Google Analytics 4 using vue-gtag and nuxtjs

I have a Nuxtjs project. I'm using https://github.com/MatteoGabriele/vue-gtag. I am trying to send the user_id to Google Analytics 4 when the user id exists but the code fails but doesn't work. I checked in GA4 but there is no data "Login with user ID includes yes":

import Vue from "vue";
import VueGtag from "vue-gtag";

export default ({ $config, $auth }) => {
  const obj = {
    config: {
      id: 'G-XXXXXXXXXX'
    }
  }
  if ($auth?.loggedIn) {
    obj.config.params = {user_id: $auth.user.sub}
  }
  Vue.use(VueGtag, obj, app.router)
}

The following code is running:

import Vue from "vue";
import VueGtag from "vue-gtag";

export default ({ $config, $auth }) => {
  Vue.use(VueGtag, {
    config: {
      id: 'G-XXXXXXXXXX',
      params: {
        user_id: '122xzczxc'
      }
    }
  }, app.router)
}

can I help you? I want to send user_id to GA4 when user_id exists.

P粉615886660P粉615886660352 days ago575

reply all(1)I'll reply

  • P粉135799949

    P粉1357999492023-12-20 00:30:07

    Reply correctly after commenting and what I think I have understood.

    If you change the condition to the default value, for example:

    if ($auth?.loggedIn) {
      obj.config.params = {user_id: '123-update-id'}
    }
    

    This doesn't work.

    But if you initialize your object like this:

    const obj = {
      config: {
        {
          id: 'G-XXXXXXXXXX',
          params: {
          user_id: '123-default-id'
        }
      }
    }
    
    The condition on

    $auth?.loggedIn will take effect and assign a value.

    In this case, the problem is just that you need to have a default structure for your object. In this case the object does not create new properties which could cause async or structural issues, it just updates the properties.

    Just do this:

    const obj = {
      config: {
        {
          id: 'G-XXXXXXXXXX',
          params: {
          user_id: ''
        }
      }
    }
    

    reply
    0
  • Cancelreply