简体   繁体   中英

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

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?

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.

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.

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"]);

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 :)


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM