This blog post shows how to setup and query data with Node.js from Googles Analytics Core Reporting API.

1. Install Googles Analytics Core Reporting API

Install the Googles Analytics Core Reporting API for Node.js in your project folder using npm:

npm install --save googleapis

2. Get the credentials from Google

2.1 Create a Service Account Googles Developer console

  • First create a new project on Googles Developer console like “mywebsiteGAapi”.
  • Under the section “Credentials”, execute “Create credentials” and choose “Service account key
  • Create a new service account and choose a Service account name

    • Role: Project -> Viewer
    • Key type: JSON
    • Copy the email address under Service account ID
  • Click “Create” and copy the new .json file in the “node_modules” folder of your project, like /node_modules/mywebsiteGAapi-6116b1dg49a1.json

2.2 Create a User and get your View ID from your Google Analytics Account

  • open the Admin panel in your Google Analytics Account and enter the User Management section
  • Create a new user
    • Email address:  The one you copied previously (It’s also in the JSON-file you already saved)
    • Property Permissions: Read & Analyse
  • Back in the Admin panel under View enter the View Settings

  • Copy the View ID

3. Run the script

  • Now copy the script below in your Project file and give it a nice name like getmydata.js.
  • Change your individual ApiKeyFile and View ID
  • Run the script with nodegetmydata.js

'use strict';
var googleapi = require('googleapis');
var ApiKeyFile = require('mywebsiteGAapi-6116b1dg49a1.json');
var viewID = 'ga:123456700';

var google = getdefaultObj(googleapi);
var Key = getdefaultObj(ApiKeyFile);

function getdefaultObj(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var jwtClient = new google.default.auth.JWT(Key.default.client_email, null, Key.default.private_key, ['https://www.googleapis.com/auth/analytics.readonly'], null);
jwtClient.authorize(function (err, tokens) {
  if (err) {
    console.log(err);
    return;
  }
  var analytics = google.default.analytics('v3');
  queryData(analytics);
});

function queryData(analytics) {
  analytics.data.ga.get({
    'auth': jwtClient,
    'ids': viewID,
    'metrics': 'ga:users,ga:pageviews',
    'start-date': 'yesterday',
    'end-date': 'today',
  }, function (err, response) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(JSON.stringify(response, null, 4));
  });
}

You retrieve the users and page views since yesterday.

I guess you looking for other queries? Check out the common queries in the API Reference.
The Query Explorer lets you play with the API by building queries.

One Reply to “Query Google Analytics via Node.js”

Leave a Reply

Your email address will not be published. Required fields are marked *