Back to journal
·1 min readVue.jsVueGridsomeGoogle AnalyticsTrackingAnalytics

Google Analytics on Gridsome Applications

Gridsome + gtag without a plugin that fought me. Manual setup in main.js, pageviews, and a share event example.

ShareCopy failed

Analytics still matters on static sites. Gridsome plugins for Google Analytics didn't behave how I wanted, so I wired gtag by hand. More control, same tracking ID.

Create the property

Open Google Analytics, Admin (gear bottom left), Create Property. Enable Universal Analytics property if you're following this older UA flow from the original post.

Google Analytics Dashboard

Create property

Copy the setup snippet and tracking ID from the finish screen.

Tracking ID

Wire Gridsome

In main.js, push the script and init gtag only on the client (window doesn't exist at build time):

export default function (Vue, { router, head, isClient }) {
  head.script.push({
    src: "https://www.googletagmanager.com/gtag/js?id=UA-********-*",
    async: true,
  });

  if (isClient) {
    window.dataLayer = window.dataLayer || [];
    function gtag() {
      dataLayer.push(arguments);
    }
    if (typeof window.gtag === "undefined") window.gtag = gtag;
    gtag("js", new Date());
    gtag("config", "UA-********-*");
  }

  // rest code...
}

Deploy and you should see active users tick up.

Custom events

Track a share button:

async share() {
    const key = this.to;
    const params = {
        method: key,
        content_type: "article",
        item_id: location.href,
    };
    gtag("event", "share", params);
}

Default config still sends pageviews. More event types: Google docs.

ShareCopy failed