Skip to content

fix(docs): Google Analytics not tracking SPA navigation in VitePress #220

@polaz

Description

@polaz

Problem

The vitepress-plugin-google-analytics plugin only sends a page_view event once on initial page load. When users navigate between pages via VitePress SPA routing, no additional page_view events are sent to Google Analytics.

Result: GA only tracks the first page a user lands on, not subsequent navigation. In GA logs, you always see the "previous" page.

Root Cause

The plugin does this on initialization:

gtag('js', new Date())
gtag('config', id)  // Single page_view - that's it

It doesn't use VitePress router hooks to track SPA navigation.

Solution

  1. Remove vitepress-plugin-google-analytics dependency
  2. Implement proper GA4 integration using VitePress router.route.path watch:
// Disable automatic page_view
gtag('config', GA_ID, { send_page_view: false });

// Track initial page
trackPageView(window.location.pathname);

// Track SPA navigations
watch(() => router.route.path, (path) => {
  trackPageView(path);
});

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions