Search code examples
node.jsgoogle-apigoogle-oauthgoogle-analytics-apigoogle-api-nodejs-client

Can we get Google anallytics report at server end , without redirecting to google page and ask for login


I need to show Google analytics report to my end user .

I need to request data from NodeJs and show them for end user .

Is it possible please help .

I have tried many packages but they redirect to google login page .

Thanks


Solution

  • The redirect to login page is because you are authenticating with Oauth2. This will display data owned by the person logging in.

    Assuming you are trying to show your own Google Analytics data to someone else. Then you should use a service account. Service accounts are pre authorized. You will simply need to create a service account credentials on Google developer console then add the service account email address at the account level in the Google analytics admin section.

    async function runSample () {
      // Create a new JWT client using the key file downloaded from the Google Developer Console
      const client = await google.auth.getClient({
        keyFile: path.join(__dirname, 'jwt.keys.json'),
        scopes: 'https://www.googleapis.com/auth/analytics.readonly'
      });
    
      // Obtain a new drive client, making sure you pass along the auth client
      const analyticsreporting = google.analyticsreporting({
        version: 'v4',
        auth: client
      });
    

    There is an example of service account authencation with the Google Apis node.js client here samples/jwt.js This can be pluged into the sample for Google Analaytics reporting api here analyticsReporting/batchGet.js

    Tecincally i gave you the same code on your previous question Google Analytics - invalid_grant: Invalid JWT Signature