Home » Nodejs » How to track usage on a node.js RESTful service with Google Analytics?

How to track usage on a node.js RESTful service with Google Analytics?

Posted by: admin December 5, 2017 Leave a comment

Questions:

I’ve written a RESTful node.js service as a backend for http://www.cross-copy.net and would like to not only track usage of the web-client but also other clients (like commandline or Apps) which use the service for inter-device copy/paste. Is it possible to embed the Google Analytics JavaScript API into a node.js application and do server-side tracking?

Answers:

As Brad rightfully sad, there was nothing for Node… So I wrote a nodejs module tailored for this these last few days and just published it on NPM: node-ga

The module is still really new (barely trying it in production on a pet project), so don’t hesitate to give your input 🙂


Questions:
Answers:

Since all of the answers are really old, I will mention a new npm package:
https://www.npmjs.com/package/universal-analytics

It’s really great and incredible easy to use.

Questions:
Answers:

You won’t be able to just drop ga.js into your Node project. It has to be loaded in a browser to function correctly.

I don’t believe there is anything out there for Node yet (correct me if I’m wrong!), but you should be able to easily adapt the existing PHP classes for doing logging server-side:

https://developers.google.com/analytics/devguides/collection/other/mobileWebsites

You can see how the URL to request the tracking GIF is constructed within ga.php. Translate ga.php to JS and you’re set.

$utmGifLocation = "http://www.google-analytics.com/__utm.gif";

// Construct the gif hit url.
$utmUrl = $utmGifLocation . "?" .
    "utmwv=" . VERSION .
    "&utmn=" . getRandomNumber() .
    "&utmhn=" . urlencode($domainName) .
    "&utmr=" . urlencode($documentReferer) .
    "&utmp=" . urlencode($documentPath) .
    "&utmac=" . $account .
    "&utmcc=__utma%3D999.999.999.999.999.1%3B" .
    "&utmvid=" . $visitorId .
    "&utmip=" . getIP($_SERVER["REMOTE_ADDR"]);

Questions:
Answers:

Install universal analytics

npm install universal-analytics --save

In your routes file, require the module. (Replace process.env.GA_ACCOUNT with string like ‘UA-12345678-1’)

// Init GA client
var ua = require('universal-analytics');
var visitor = ua(process.env.GA_ACCOUNT);

Now inside your endpoint functions, you can track a pageview. (Replace request.url with the current url string like '/api/users/1')

// Track pageview
visitor.pageview(request.url).send();

Read the documentation on UA for more info on this module.

Questions:
Answers:

I tried out node-ga, but didn’t get event tracking to work. nodealytics did the job.

Questions:
Answers:

See Core Reporting API Client Libraries & Sample Code (v3).

There is also the following version: Google APIs Client Library for Node.js (alpha).

Questions:
Answers:

I wrote a script to query data with Node.js from Googles Analytics Core Reporting API (v3). The script and a detailed setup description is available here.

Here is the script part:

'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));
  });
}

Leave a Reply

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