Cody Bontecou

Set up Google Analytics with Vitepress

February 5, 2023 · 1 minute read · blogging,vitepress,vue

Code Snippet

Change all G-XXXXXXXXXX with the Tracking ID provided by Google Analytics (GA4).

// 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.

Newsletter

Subscribe to get my latest content. No spam.