Set up Google Analytics with Vitepress
October 31, 2024
Code Snippet 
Change all G-XXXXXXXXXX with the Tracking ID provided by Google Analytics (GA4).
ts
// src/.vitepress
module.exports = {
  head: [
    [
      'script',
      {
        async: true,
        src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX',
      },
    ],
    [
      'script',
      {},
      "window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'G-XXXXXXXXXX');",
    ],
  ],
}Resources 
Inspiration 
If you're coming from Vuepress, you may be used to the plugin system that provides features such as Google Analytics. Vitepress is (arguably) simpler in this regard. Just add the script provided by Google to your HTML head, and it should work.
Stay Updated
Get notified about new posts and updates. No spam, unsubscribe anytime.
Comments
Share your thoughts and feedback using GitHub comments.