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

7

13

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?

Violation answered 8/5, 2012 at 8:15 Comment(0)
A
2

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


Aerostation answered 3/4, 2013 at 10:29 Comment(6)
This is really amusing... I was just putting the touches on a module that does the exact same thing this weekend! I've been using a version of it in production, but figured I would clean up the code a bit before throwing it out there.Swagsman
@Brad: The more modules, the merrier the user :)Aerostation
Ha, maybe. For now though, I think yours fills the need just fine. Nice work!Swagsman
@JoshLeaves nice library, can you also track events with this somewhere in a route (not as middleware)? I tried something like ga(...)(req, res, function() {}); which fires a request indeed, but it doesn't appear in GAMagaretmagas
@forste: You can call it from within a single route, here is an example: gist.github.com/joshleaves/5669653Aerostation
That library uses Google Analytics for Mobile Websites, which has been deprecated in 2014Bala
M
11

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.

Maryalice answered 9/4, 2015 at 13:0 Comment(3)
upvoted! how do you prevent from double tracking meaning if the event runs on the browser, how will you prevent from sending the same event on server sideAnther
@Anther Not quite sure what you mean; I'd only run it either on the browser OR on the server and not bothMaryalice
what I was saying is that i pasted the browser side script and i have the server side page() method on as well, when i open the website, i see 2 users under real time which is understandable as it sends the event once from the client and once from my server also, my question or doubt was how do I prevent this duplication, would post another question if needed , cannot find any tag for universal-analytics though, stackoverflow has the wrong tag currentlyAnther
U
4

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.

Unipod answered 29/9, 2016 at 3:42 Comment(0)
S
2

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"]);
Swagsman answered 16/6, 2012 at 14:35 Comment(0)
A
2

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


Aerostation answered 3/4, 2013 at 10:29 Comment(6)
This is really amusing... I was just putting the touches on a module that does the exact same thing this weekend! I've been using a version of it in production, but figured I would clean up the code a bit before throwing it out there.Swagsman
@Brad: The more modules, the merrier the user :)Aerostation
Ha, maybe. For now though, I think yours fills the need just fine. Nice work!Swagsman
@JoshLeaves nice library, can you also track events with this somewhere in a route (not as middleware)? I tried something like ga(...)(req, res, function() {}); which fires a request indeed, but it doesn't appear in GAMagaretmagas
@forste: You can call it from within a single route, here is an example: gist.github.com/joshleaves/5669653Aerostation
That library uses Google Analytics for Mobile Websites, which has been deprecated in 2014Bala
M
1

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

Magaretmagas answered 29/5, 2013 at 8:58 Comment(0)
H
1

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

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

Hyperemia answered 30/1, 2014 at 12:1 Comment(0)
R
0

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));
  });
}
Rosewood answered 16/7, 2017 at 22:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.