LoginSignup
4
3

More than 3 years have passed since last update.

Nuxt.js のライフサイクルを踏まえてトラッキングタグ埋め込みを実装する

Posted at

Web サイトのエンハンスやマーケティングといった目的でユーザー分析や広告表示用のトラッキングタグを埋め込むことは開発の現場でよくあると思います。
Google Tag Manager などのツールを利用すれば比較的簡単に設定できますが、ユーザー ID など Web アプリケーション固有のデータをタグと併せて設定したい場合など、アプリケーション側にタグ埋め込み用のコードを書かなければならない場面もあります。

Nuxt.js のユニバーサルモードにおけるライフサイクル処理には幾つか種類があり、実行タイミングおよび SSR/CSR の実行有無がそれぞれ異なります。

これらを踏まえ、タグやカスタム変数を設定する際にどのライフサイクル処理を選択すれば良いのか整理します。

TL;DR

  • クライアントサイドで一度だけ実行したい処理(タグ埋め込みなど)は plugins を利用する。
  • ページ遷移ごとに実行したい処理(ページ遷移時の状態を表す変数の設定など)は Vue Router を利用する。

シチュエーション

以下のようなタグやカスタム変数に関する処理をまとめた composition を適宜 import して利用するようなシチュエーションを想定します。
コードは TypeScript で記述していますが、本記事の要点に関しては JavaScript の場合と特に大きな相違はありません。

compositions/sample-tag.ts
export function useSampleTag() {
  return {
    addTag() {
      // タグの埋め込み
    },
    addCustomValue() {
      // カスタム変数の設定
    }
  }
}

タグの埋め込み

タグの埋め込みは直アクセスされたタイミングで行い、 nuxt-link での遷移時には実行したくないケースが多いと思います。
このような用途では直アクセス時のみ実行される plugins が利用できます。

plugins/sample-tag.ts
import { useSampleTag } from '~/compositions/sample-tag'

export default () => {
  const st = useSampleTag()
  st.addTag()
}

カスタム変数の設定

ページ遷移ごとにログイン状態やユーザー ID などの値を設定したい場合は Vue Router の afterEach() が利用できます。

plugins/router.ts
import { useSampleTag } from '~/compositions/sample-tag'

export default () => {
  ctx.app.router!.afterEach((to, from) => {
    if (process.client) {
      const st = useSampleTag()
      st.addCustomValue()
    }
  })
}

middleware を利用する場合

middleware を用いても同様のコードで似たような処理は実現できます。
ただしユニバーサルモードでは直アクセス時に SSR でしか処理されないため、 window オブジェクトの利用といった CSR が前提となる処理が失敗する可能性があります。
特別な理由がない限りは Vue Router を利用するのが無難だと思います。

Vuex の Store を利用する場合

Vuex の Store から getter で値を取得したい場合、 addCustomValue() の引数に Store を取るようにして内部で getter を呼び出す作りにしても良いかもしれません。

compositions/sample-tag.ts
import { Store } from 'vuex/types'
import { AuthenticationState } from '~/store/authentication'

export function useSampleTag() {
  return {
    addTag() {
      // タグの埋め込み
    },
    addCustomValue(store: Store<AuthenticationState>) {
      // カスタム変数の設定
    }
  }
}
plugins/router.ts
import { Context } from '@nuxt/types'
import { useSampleTag } from '~/compositions/sample-tag'

export default (ctx: Context) => {
  ctx.app.router!.afterEach((to, from) => {
    if (process.client) {
      const st = useSampleTag()
      st.addCustomValue(ctx.store)
    }
  })
}
4
3
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
4
3