Grab Google Analytics Data in remote account from Firebase Functions

Although Google analytics Login is isolated from other Google services, you can easily access the analytics data from another service.  I am going to demonstrate how to retrieve google analytics data from firebase functions.



You need to use googleAPI node package as an assistant.

In coding, you have to use  JWT authentication in order to avoid async await issue in Google Cloud functions. Currently stable version of cloud functions is Nodejs 6.

You have to download the service-account.json from Firebase or google cloud. In firebase, it is located at the following link. You have to generate a new private key.

https://console.firebase.google.com/u/0/project/<project-id>/settings/serviceaccounts/adminsdk

Make sure it contains the client email. That email need to be added in Analytics >>admin >> User Management Section as a user.

https://analytics.google.com/analytics/web/


The code block in the batchGet fuctions will execute in firebase functions nodejs V6.

const { Compute } = require('google-auth-library');
const  {google} = require('googleapis');
const prettyjson = require('prettyjson');
var scopes = [
  "https://www.googleapis.com/auth/userinfo.email",
  "https://www.googleapis.com/auth/firebase.database",
  "https://www.googleapis.com/auth/analytics.readonly"
];

const fs = require('fs');

var pretty_json_options = {
  noColor: false
};

// pass the service accout auth in firebase functions
const clientSecretJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'service-account.json')));

const jwtClient = new google.auth.JWT(clientSecretJson.client_email, null,clientSecretJson.private_key, scopes, null);

function batchGet() {
const authPromise = new Promise((resolve, reject) => {
  jwtClient.authorize((err, tokens) => {
    if (err) {
      return reject(err);
    }
    // This is the part that doesn't happen when using promisify.
    jwtClient.setCredentials(tokens);
    console.log('jwtClient ',jwtClient);
    var  agent = google.analyticsreporting({
       version: 'v4',
       auth:jwtClient
     })
   console.log('agent ');

     return new Promise((resolve, reject) => {
       const res = agent.reports.batchGet({
         resource: {
           reportRequests: [ .  // quary to get unique page views in last week
             {
               viewId: "<viewID>",
               dateRanges: [
                 {
                   startDate: '7daysAgo',
                   endDate: 'today'
                 }
               ],
               metrics: [
                 {
                   expression: 'ga:uniquePageviews'
                 }
               ],
               dimensions: [
                 {
                   name:"ga:pagePath"
                 }],
                 "orderBys":
                 [
                   {"fieldName": "ga:uniquePageviews", "sortOrder": "DESCENDING"}
                 ]
               }
             ],
           },
         }, (error, response) => {
           if(error){
              console.log('error ',error);
              reject(error);
           }else {

             var dataResopnse =response.data;
            var reports=  dataResopnse.reports;

                  var rowObject =reports[0]['data']['rows'];
                   console.log('rowObject ',rowObject);
             //console.log(prettyjson.render(response.data, pretty_json_options));
              //console.log('res ',res);
             resolve(response);
           }

          })
       })

    //resolve(jwtClient);
  });
});
}
batchGet();  


Following codings make my life easy.

https://github.com/ebidel/devwebfeed/blob/master/analytics.mjs
http://nali.org/google-analytics-v4-api-node-js-starter-example/


Above query is used to get the weekly views of the site. You can design your query JSON using the following link.

https://ga-dev-tools.appspot.com/query-explorer/



Comments

Popular posts from this blog

ENOENT: no such file or directory, rename : node_modules/async

react-quill Integrate quill-image-resize-module