Send user_id to Google Analytics 4 using vue-gtag and nuxtjs
P粉615886660
P粉615886660 2023-12-19 08:50:16
0
1
571

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粉615886660
P粉615886660

reply all(1)
P粉135799949

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: ''
    }
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template