Skip to content

Instantly share code, notes, and snippets.

@missinglink
Created December 5, 2013 18:24
Show Gist options
  • Save missinglink/7810596 to your computer and use it in GitHub Desktop.
Save missinglink/7810596 to your computer and use it in GitHub Desktop.
An example of how to generate Google Analytics reports from node.js (with custom dimensions).
var GA = require('googleanalytics'),
Table = require('cli-table'),
util = require('util');
// API client.
// You may need to enable API access to analytics for your account
// here: https://code.google.com/apis/console
var ga = new GA.GA({
"user": "[email protected]",
"password": "mysupersecretpassword"
});
// What we call the custom dimension.
var cvdimensions = {
'ga:dimension1': 'installation',
'ga:dimension2': 'creative',
'ga:dimension3': 'variant',
'ga:dimension4': 'merchant',
'ga:dimension5': 'product'
};
// Which metrics & dimensions we want.
var metrics = [ 'ga:pageviews' ];
var dimensions = [
'ga:pagePath',
'ga:dimension1',
'ga:dimension2',
'ga:dimension3',
'ga:dimension4',
'ga:dimension5',
];
// Options (make sure you set the 'view id' and start & end dates)
// You can find the id you need in the analytics web console under:
// 'Admin' (top right) -> 'VIEW (PROFILE)' (far right column) ->
// 'View Settings' (first option) -> 'View ID'.
// NOTE: IT IS NOT THE 'UA-xxx' ONE!
var options = {
'ids': 'ga:79670027',
'start-date': '2013-01-01',
'end-date': '2014-01-01',
'dimensions': dimensions.join(','),
'metrics': metrics.join(','),
'sort': '-ga:pagePath'
};
ga.login(function(err, token) {
ga.get(options, function(err, entries) {
if( err ) throw new Error(err);
// headings
var headers = [""].concat( metrics );
dimensions.forEach( function( dim ){
headers.push( ( dim in cvdimensions ) ? cvdimensions[dim] : dim );
});
var table = new Table({ head: headers });
entries.map( function( entry ){
// console.log( entry );
var row = {}, cols = [];
// metrics
for( var metric in entry.metrics[0] ){
cols.push( entry.metrics[0][metric] );
}
// dimensions
for( var dimension in entry.dimensions[0] ){
cols.push( entry.dimensions[0][dimension] );
}
row[entry.dimensions[0]['ga:pagePath']] = cols;
table.push( row );
});
console.log( table.toString() );
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment