Manually setup Google analytics on GridSome sites

Bibhuti Poudyal
2 min readAug 24, 2021
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

Go to 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 instead of TRACKING_ID .

export default function (Vue, { router, head, isClient }) {	
//----
head.script.push({
src: '<https://www.googletagmanager.com/gtag/jsid=TRACKING_ID>',
async: true
})
if (process.isClient) { window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'TRACKING_ID');
window.gtag = gtag; // expose gtag function to global scope
}
//------
}

Note: check for window.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 sufficient, for more events visit Google analytics documentation.

--

--