diff --git a/plugins/track.client.ts b/plugins/track.client.ts index b4d6d4818..405a3341c 100644 --- a/plugins/track.client.ts +++ b/plugins/track.client.ts @@ -1,5 +1,6 @@ import * as Sentry from '@sentry/vue'; import { defineNuxtPlugin, useRouter } from 'nuxt/app'; +import type { RouteLocationNormalized } from 'vue-router'; const USER_AT = /^\/@.+/; const USER_SUBPAGE = /^\/(u|card)\/.*/; @@ -16,16 +17,12 @@ export const normalizeUrl = (page: URL): URL => { return page; }; -export default defineNuxtPlugin(() => { +export default defineNuxtPlugin((nuxtApp) => { const router = useRouter(); - router.afterEach((to, from) => { + + const trackPageview = (route: RouteLocationNormalized): void => { try { - const toUrl = normalizeUrl(new URL(to.fullPath, window.location.href)); - const fromUrl = normalizeUrl(new URL(from.fullPath, window.location.href)); - if (toUrl.toString() === fromUrl.toString()) { - // same page, but different search param - return; - } + const toUrl = normalizeUrl(new URL(route.fullPath, window.location.href)); console.debug('[analytics] tracking page view:', toUrl.toString()); useTrackPageview({ data: { @@ -35,5 +32,22 @@ export default defineNuxtPlugin(() => { } catch (error) { Sentry.captureException(error); } + }; + + // Track the initial page load + nuxtApp.hook('app:mounted', () => { + trackPageview(router.currentRoute.value); + }); + + // Track client-side navigation + router.afterEach((to: RouteLocationNormalized, from: RouteLocationNormalized) => { + const toUrl = normalizeUrl(new URL(to.fullPath, window.location.href)); + const fromUrl = normalizeUrl(new URL(from.fullPath, window.location.href)); + if (toUrl.toString() === fromUrl.toString()) { + // Same page, but different search param + return; + } + trackPageview(to); }); }); +