Created
November 21, 2018 19:26
-
-
Save karlwilbur/35be3803a20a2fb615806a0175518e42 to your computer and use it in GitHub Desktop.
Example Google Analytics API Request Using JavaScript/Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
I am afraid the link for viewId
is not working.
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
This code uses the
googleapis
JavaScript module. Theconfig
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
andprivateKey
Here is a walk-through on a11n and a12n (for the
clientEmail
andprivateKey
; 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/