Google Analytics Integration Overview

Sooner or later you’ll probably want to measure and analyze the traffic on your website. For users of the well-known Google Analytics service, the Scrivito Example App already integrates it. To use it, all you need to do after setting up your site in GA is to copy your tracking ID and paste it to the “Site settings” section of the homepage.

Google Analytics tracking ID

Example App “Site settings” tab: GA Tracking ID

How GA tracking works in the Example App

The Scrivito Example App comes with a React component, GoogleAnalytics, which is called in the application JS code, so that it is rendered for every page:

The GoogleAnalytics component can be found in the “src/Components” directory of the Example App. It uses the ga() command queue, which is set up in the component’s componentDidMount() lifecycle method. As you can see below, the tracking ID is taken from the googleAnalyticsTrackingId attribute of the root page. It is this attribute that is set when entering the ID via the properties dialog of the homepage.

Tracking only takes place if a tracking ID has been provided, meaning that Google Analytics is not loaded if the tracking ID attribute and hence the trackingId state variable is empty.

With a single page application, we need to ensure that the tracking code is executed each time the visitor navigates to a different page. This is what the urlChangeTrackerGoogle Analytics plugin is registered for as the component is set up. The plugin is loaded at rendering time (via “/google_analytics.js”), just before Google’s “analytics.js” script is run.