Google Analytics v4 API + Node.js Starter Example

Posted — Feb 15, 2018

Google has lots of good documentation on starting out with Google APIs (which is used for Google Analytics) for certain languages like Python, Java, and C#, but completely sketchy for Node.js. Googling there are many examples but most are for v3. And the implementations get confusing if you aren’t familiar with oAuth or JSON Web Tokens.

Here is a really simplified chunk of starter code for pulling the number of Goal 2 completions by source/medium, ordered in descending order. The assumption is that you have already set up the service account and downloaded the JSON file with the private key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var prettyjson = require('prettyjson'); // Un-uglify JSON output
var {google} = require('googleapis');
var key = require('<SERVICE\_ACCOUNT\_JSON\_FILE>'); // Downloaded JSON file

var viewID = '<VIEW\_ID>'; // Google Analytics view ID
var analytics = google.analyticsreporting('v4'); // Used for pulling report
var jwtClient = new google.auth.JWT(key.client\_email, // For authenticating and permissions
                                    null,
                                    key.private\_key,
                                    \['https://www.googleapis.com/auth/analytics.readonly'\],
                                    null);

jwtClient.authorize(function (err, tokens) {
  if (err) {
    console.log('Reeeeejected');
    console.log(err);
    return;
  } else {
    console.log('Yup, we got authorized!');
  }
});

// Set up what we data we want to pull from Google Analytics
metrics\_columns = \[{
  expression: 'ga:goal2Completions'
}\];

dimensions\_rows = \[{
  name: 'ga:sourceMedium'
}\];

date\_filters = \[{
  startDate: 'today',
  endDate: 'today',
}\];

sort = \[{
  fieldName: 'ga:goal2Completions',
  sortOrder: "DESCENDING"
}\];

var req = {
  reportRequests: \[{
    viewId: viewID,
    dateRanges: date\_filters,
    metrics: metrics\_columns,
    dimensions: dimensions\_rows,
    orderBys: sort
  }\],
};

// Options for prettifying JSON output
var pretty\_json\_options = {
  noColor: false
};

// Pull report and output the data
analytics.reports.batchGet({
    auth: jwtClient,
    resource: req
  },
  function (err, response) {
    if (err) {
      console.log('Failed to get Report');
      console.log(err);
      return;
    }
    // response.data is where the good stuff is located
    console.log('Success - got something back from the Googlez');
    console.log(prettyjson.render(response.data, pretty\_json\_options));
  }
);