Using Google Analytics API with Node.JS

I recently hosted a session on how to build a dashboard site using Node.JS, Express, MongoDB and Google Analytics.

One thing i noticed is that there many tutorials around on how to communicate between Node and Google Analytics (GA from now on) but none is a complete step by step guide using the latest Google APIs NPM package.

When accessing Google APIs from a backend, we need our server to authenticate against Google in order to access its APIs (Analytics in our case). To do that, we first have to create a special account called Service Account.

Creating a service account

Creating a service account is quite an easy process: 
 Head over to Google’s Developers Console site and create a new project. Once created, refresh the page and click on your newly created project. Click on Credentials under the APIs & Auth section, and then on the Create new Client ID button. 
 Under Application Type select Service account and click on the Create Client ID button. 
 After a few seconds your newly created private key will be downloaded to your computer and a popup message telling you that the secret password to your file is, well, notasecret will be shown. Remember this password as we will need it later on in this tutorial. 
 Congratulations — you now have a Google APIs service account!

Converting the key, a.k.a hello .pem!

Now that we have our service account setup and its private key ready — let’s convert it to a format Node.js can understand. While it may sound like a daunting task, the entire process can be summarized into a single OpenSSL command: 
 openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem

Once executed, you will be prompted for the secret key. Remember that popup message from the earlier step? That’s your secret password right there! 
 Once completed you should have a new key.pem file ready to be used.

Using the Google APIs package

Now that we have both the key and the account all setup and ready to go, we can move on and actually start using Google Analytics! 
 First, copy the converted .pem file we created in the previous step to a folder of your choice. In my sample solution i copied it to the root folder for ease of access. 
 Next, I created a module called analytics. This module will be incharge of the communication with Google Analytics API. 
 First, I imported Q and GoogleAPIs modules as follows:

Next, head back to the Google’s Developers Console site and under the APIs & auth section click on Credentials. Copy the Service account’s email address as we will need to store it in our module.

With the email address in your possession head back to the analytics module and add two new variables: one for the service account email address, and one for the location of the key file:

With the administration part out of the way, it’s time to create our GetNumberOfSessions method, which will return the number of sessions our site had for the last 7 days:

First, we create a deferred object which returns a promise to the caller of the method, which in time will resolve itself with the response to the called. We need to create such an object as we are going to communicate with Google Analytics asynchronously. If you need to shape up on deferreds/promises make sure to read HowToNode’s great article on the subject — Asynchronous Control Flow with Promises.

Other than the deferred object, we create a service client to interact with the Google Analytics API. In the code above, that’s the gAnalytics object. For every API google has its own service client. For example: google.drive(‘v2’) for Google Drive or google.urlshortener(‘v1’) for Google URL shortening services.

Before we can go wild and query the Google Analytics API, we have to authenticate against it. Server authentication is done using JWT. In order to authenticate using JWT we need a .pem key file (which we previously exported) and a service account email. Add the following snippet below the gAnalytics object declaration:

To perform the actual authentication we call the authorize method of the authClient object as follows:

If everything works as expected we should have no err object in our function callback, so it’s advisable you add such check before moving on).

Next, we define an object which tells the Google Analytics API who we are and what do we want to get from it:

Let’s go over these properties real fast:

  • authClient is the object we created earlier which contains our key file and the permission we are seeking. We pass this object to the ‘auth’ property.
  • The ids property requires our Analytics View ID prefixed with ga:. You can find your view id under the View Settings option in the Admin section of Google Analytics.
  • The metrics and dimensions properties, bundled together, dictates which type of data we like to get from Google Analytics. In this example we specify sessions for metric and date for dimension, meaning we wish to get the number of sessions our web site had over the dimension of dates (i.e.: how many hits my web site had over the course of X days). You can find a full list of possible metrics over at Google’s Dimensions & Metrics Explorer.
  • The start-date and end-date properties specifies the range of time for the queries data.

In short, in this example object we are requesting the number of sessions our website had per day over the course of 7 days.

Now that our object is in order, it’s time to get some data:

To make things easier to follow, here is the complete method:

The outcome of the api call will be an array of objects, each contains a date string (i.e:20150101) and the number of sessions on that particular day.


Originally published at www.fsjohnny.com on June 29, 2015.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.