Skip to content

Instantly share code, notes, and snippets.

@benjaminparnell
Created October 15, 2015 15:03
Show Gist options
  • Select an option

  • Save benjaminparnell/c31e817fa4442efb04f2 to your computer and use it in GitHub Desktop.

Select an option

Save benjaminparnell/c31e817fa4442efb04f2 to your computer and use it in GitHub Desktop.

Integrating with the Google Analytics API with Node.js

Modules you will need:

Getting an API token to use with node-gapitoken

  1. Go to the "Google API console", and under "APIs & auth" go to credentials.
  2. Create a service account for your project.
  3. Go to the settings for that account, and click "Generate new P12 Key" to download a new key.
  4. Convert the .p12 file to .pem:
openssl pkcs12 -in key.p12 -out key.pem -nocerts
  1. Remove the passphrase from the .pem file:
openssl rsa -in key.pem -out key.pem

You can now make a request to the analytics api like so:

var ga = require('googleanalytics')
  , GAPI = require('gapitoken')

var gapi = new GAPI(
  { iss: 'xxxxxxxxx@developer.gserviceaccount.com'
  , scope: 'https://www.googleapis.com/auth/analytics'
  , keyFile: __dirname + '/ga-cert.pem'
  }
, function (error) {
    if (error) return callback(error)

    gapi.getToken(function (error, token) {
      var GA = new ga.GA({ token: token })
        , options = {}

      GA.get(options, callback)
    })
  }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment