2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

nuxtjs/google-gtag でユーザー毎の計測をするときは注意してね

Posted at

nuxtjs/google-gtag を使って Google Analytics の計測をしているのですが、計測できずにハマったので記事にしておきます。
なお、今回の問題は Google Analytics の UserID 機能 を使った時に発生します。

起こった問題

どのユーザーがどのページに遷移したかを、Google Analytics で確認したいとの要望がありました。
nuxtjs/google-tag のドキュメント通りにやると計測はできたのですが、計測できるのはログイン直後のページのみで、 router.push などで遷移した先のページは計測できていませんでした。

元々のコード

nuxt.config.js での goole-gtag の設定は以下です。

nuxt.config.js
export default {
  // 省略
  'google-gtag': {
    id: `${process.env.GA_ID}`,
    debug: process.env.NODE_ENV !== 'production',
  },
};

Nuxt の plugins に追加した gtag.js は以下です。

gtag.js
let gtag;

export default ({ app }) => {
  if (!app.$gtag) {
    console.error('GA settings load to failed');
    return;
  }
  gtag = app.$gtag;

  // エラー時のイベント計測など
};

/**
 * この関数はログイン直後に呼ばれる
 */
export function setUserId(userId) {
  gtag('config', process.env.ga_id, {
    user_id: userId,
  });
}

原因

nuxtjs/google-gtag を導入すると生成される .nuxt/google-gtag.js を確認すると以下のようになっています。

google-gtag.js
export default function ({app: {router}}, inject) {
  if(false){
    // inject empty gtag function for disabled mode
    inject('gtag', () => {})
    return
  }

  window.dataLayer = window.dataLayer || []
  function gtag () {
    dataLayer.push(arguments)
    if(true){
      console.debug('gtag tracking called with following arguments:', arguments)
    }
  }
  inject('gtag', gtag)
  gtag('js', new Date())
  gtag('config','UA-XXXX-1',)

  if(!false){
    router.afterEach((to) => {
      gtag('config', 'UA-XXXX-1', {'page_path': to.fullPath}) // !!!!!!
    })
  }

  // additional accounts
}

上記の !!!!!! がついている行で user_id が指定されていないので、 route を変更した時にユーザーの追跡が止まっていたようです。

解決策

router.afterEach の処理は自前で書くようにし、 user_id を指定します。

gtag.js
export default ({ app, store }): void => {
  // 以下を追記
  (app.router).afterEach((to) => {
    const userId = 'store から取ってくる';
    gtag('config', process.env.ga_id, {
      user_id: userId,
      page_path: to.fullPath,
    });
  });
};

これで解決できました。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?