Manually setup Google analytics on GridSome sites

2021 Aug 24 - 2 min read

Photo by Markus Winkler on Unsplash

As we all know analytics is an essential part of any website. Google analytics is the best free tool out there. This article illustrate how google analytics can be added to a GridSome site.

I was trying to use this plugin, but it doesn't work as expected. So, I had to add it manually. If you are stuck in same place or you want to customize the analytics on your website(beyond the plugin), follow along.

Create Universal tracking on Google analytics

Goto google Analytics

Navigate to Admin section (Click on small gear icon at bottom left) then "Create Property"

Fill up the form. Since we are collecting analytics for website, make sure you enable “Create a Universal Analytics property”

Finish the setup and you will be redirected to page containing setup scripts and your tracking ID.

Setup GridSome site to send analytics data

Go to main.js file and paste the following code. Make sure you include your tracking id.

export default function (Vue, { router, head, isClient }) {	
    src: '',
    async: true

  if (process.isClient) {
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', 'YOUR_TRACKING_ID');


Note: check for process.isClient is needed because window won't work during build.

Reload your site and you should see increase in "Active users" on google Analytics dashboard.

For counting page views of specific page or blog post, simply paste this code(filling necessary details) on respective component's lifecycle hook.

//eg: include this code on component's "created" hook
gtag('event', 'page_view', {
  page_title: '<Page Title>',
  page_location: '<Page Location>',
  page_path: '<Page Path>',
  send_to: '<TRACKING_ID>'

Counting only pageviews may not be suffecient, for more events visit Google analytics documentation.