Skip to content

Instantly share code, notes, and snippets.

@karlwilbur
Created November 21, 2018 19:26
Show Gist options
  • Save karlwilbur/35be3803a20a2fb615806a0175518e42 to your computer and use it in GitHub Desktop.
Save karlwilbur/35be3803a20a2fb615806a0175518e42 to your computer and use it in GitHub Desktop.
Example Google Analytics API Request Using JavaScript/Node.js
import config from './config.js'
import { google } from 'googleapis'
const scopes = ['https://www.googleapis.com/auth/analytics.readonly']
const jwtClient = new google.auth.JWT(config.clientEmail, null, config.privateKey, scopes)
async function doTheThings() {
await jwtClient.authorize()
let response = await google.analytics('v3').data.realtime.get({
'auth': jwtClient,
'ids': 'ga:' + config.viewId,
'metrics': 'rt:activeUsers'
})
console.log(response)
}
doTheThings().catch(console.error)
@karlwilbur
Copy link
Author

This code uses the googleapis JavaScript module. The config object contains a few properties and rather than get into a lot of detail about them here, I'll reference other articles that provide that detail.

clientEmail and privateKey

Here is a walk-through on a11n and a12n (for the clientEmail and privateKey; look under "Service to Service API"): https://flaviocopes.com/google-api-authentication/

viewId

Here is another on accessing analytics (where to get the viewId): https://flaviocopes.com/google-analytics-api-nodejs/

@phaistonian
Copy link

I am afraid the link for viewId is not working.

@phaistonian
Copy link

Also, I am getting Error: User does not have any Google Analytics account. though I do.

I am sure I am missing something related to briding my dev account to analytics one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment