Set up Google Analytics with Vitepress

October 31, 2024 ยท blogging, vitepress, vue

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.