I am wondering what is the best way to connect to my google analytics API using Node.js. I have tried the method below but I get trivial errors and struggle to find documentation to help me out. Just wondering if this method is the best way. Thank you for reading!
I am trying to visualize google analytics data on a web application. So, the first step I figured would be to request certain data from the google analytics API. I am working in Node.js and Express. I am getting a no file found error after the googleAuth.getClient call. Here is my current code:
const Router = require('express').Router;
const {google} = require('googleapis');
const {auth: googleAuth} = require('google-auth-library');
const responses = require('../lib/responses');
const auth = require('../lib/auth');
const router = Router({ mergeParams: true });
// Use the auth middleware to require a token
// for each non whitelisted request
router.use(auth.authMiddleware);
const viewId = '*********';
router.get('/data', async (req, res) => {
try {
const client = await googleAuth.getClient({
scopes: [
'https://www.googleapis.com/auth/analytics.readonly'
]
});
}catch(err){
console.log(err);
}
console.log("client ", client)
const url = `https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A${viewId}&start-date=30daysAgo&end-date=2018-08-28&metrics=ga%3Apageviews&dimensions=ga%3ApagePath&sort=-ga%3Apageviews`;
try {
const outcome = await client.request({ url });
}catch(err){
console.log(err);
}
return responses
.success ( res, outcome.data )
.error ( );
});
module.exports = router;
https://flaviocopes.com/google-analytics-api-nodejs/
const { google } = require('googleapis')
const scopes = 'https://www.googleapis.com/auth/analytics.readonly'
const jwt = new google.auth.JWT(process.env.CLIENT_EMAIL, null,
process.env.PRIVATE_KEY, scopes)
const view_id = 'XXXXX'
async function getData() {
const response = await jwt.authorize()
const result = await google.analytics('v3').data.ga.get({
'auth': jwt,
'ids': 'ga:' + view_id,
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:pageviews'
})
console.dir(result)
}
getData()