(bug) plausible not counting initial page view

This commit is contained in:
Andrea Vos 2025-01-28 08:24:18 +01:00
parent a0b8959749
commit 9bc7ba399a

View File

@ -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);
});
});