How to Access Google Analytics API in Node.js: Complete Guide with Express Setup

Google Analytics API
Google Analytics API in Node.js enables developers to fetch key metrics, automate reports, and integrate analytics into Express-based apps.

Introduction

Through Node.js, developers can access Google Analytics API that enables them to create programmatic statistical analysis of user activity, web performance and traffic origins. Assuming that you create the modern web applications, in particular, using the stacks such as MERN, it is vital to ensure that you incorporate analytics data to make decisions efficiently. This blog post will take you through these steps to build a node.js app with express, install the module of the Google Analytics API, and perform authenticated API requests to receive the analytics data.

Introduction to Google Analytics API in Node.js

Node.js Google Analytics API is quite an elucidative integration that can be utilized by developers to fetch meaningful statistics such as page views, bounce rates, sessions, as well as the all-important demographics of the users. Regardless of the application you are working on top of, such as creating an administrator dashboard or performance reporting, automation and flexibility benefits provided by using this API in the Node.js programming language cannot be accomplished using the Google Analytics web user interface.

Why Use Google Analytics API?

  • Automate report generation.
  • Integrate data into custom dashboards.
  • Analyze user behavior programmatically.
  • Fetch real-time and historical data.
  • Save time over manual report pulling.

Setting Up a New Node.js Project with Express

We are going to begin with the simplest Node.js+express project:

1. Create Project Directory

				
					mkdir analytics-node
cd analytics-node
				
			

2. Initialize the Node.js project

				
					npm init -y
				
			

3. Install Express

				
					npm install express
				
			

4. Create the app file:

				
					touch app.js
				
			

5. Basic Express Setup:

				
					const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Google Analytics API with Node.js');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

				
			

Since we currently have Express up and running, it is time to install the module of Google Analytics.

Installing the Required NPM Modules

Install Google’s API client module:

				
					npm install googleapis
				
			

To handle the environment variables we will also need the dotenv package:

				
					npm install dotenv
				
			

Enabling Google Analytics API and Obtaining Credentials

To access the Google Analytics API:

  • Go to the Google Cloud Console.
  • Create a new project or select an existing one.
  • Enable Google Analytics Data API v1.
  • Go to Credentials:
    • Click on Create Credentials > OAuth 2.0 Client IDs.
    • Configure the consent screen.
    • Download the JSON file after creation.

After renaming the file and saving it to your root directory as credentials.json, you are able to use it.

Authenticating with Google APIs

				
					require('dotenv').config();
const fs = require('fs');
const { google } = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];
const TOKEN_PATH = 'token.json';

function authorize() {
    const credentials = JSON.parse(fs.readFileSync('credentials.json'));
    const { client_secret, client_id, redirect_uris } = credentials.installed;
    const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

    if (fs.existsSync(TOKEN_PATH)) {
        const token = fs.readFileSync(TOKEN_PATH);
        oAuth2Client.setCredentials(JSON.parse(token));
        return oAuth2Client;
    } else {
        throw new Error('Token not found. Please run the authentication flow.');
    }
}

				
			

Accessing Analytics Data with the API

Using the authorized client:

				
					async function getAnalyticsData(auth) {
    const analytics = google.analyticsdata({ version: 'v1beta', auth });

    const response = await analytics.properties.runReport({
        property: 'properties/YOUR_PROPERTY_ID',
        requestBody: {
            dateRanges: [{ startDate: '2024-01-01', endDate: '2024-12-31' }],
            metrics: [{ name: 'activeUsers' }],
            dimensions: [{ name: 'country' }]
        }
    });

    console.log('Report result:', JSON.stringify(response.data, null, 2));
}

const authClient = authorize();
getAnalyticsData(authClient);

				
			

Instead of properties/YOUR_PROPERTY_ID insert your own GA4 property ID.

Practical Example: Fetching User Metrics

Let’s integrate everything:

				
					app.get('/report', async (req, res) => {
    try {
        const authClient = authorize();
        const analytics = google.analyticsdata({ version: 'v1beta', auth: authClient });

        const result = await analytics.properties.runReport({
            property: 'properties/YOUR_PROPERTY_ID',
            requestBody: {
                dateRanges: [{ startDate: '2024-01-01', endDate: '2024-12-31' }],
                metrics: [{ name: 'activeUsers' }],
                dimensions: [{ name: 'browser' }]
            }
        });

        res.json(result.data);
    } catch (error) {
        res.status(500).send(error.message);
    }
});

				
			

Error Handling and Best Practices

  • Put try-catch on exceptions.
  • Secure store credentials (save with dotenv and .gitignore).
  • Rotate refresh tokens.
  • Large datasets should be responded to using pagination.

Common Pitfalls and Debugging Tips

  • Invalid Grant Error: Check whether the token has expired.
  • 403 Forbidden: Make sure that property ID and permissions are correct.
  • Invalid Scope: Ensure that the OAuth permission screen is properly set.

Securing API Keys and OAuth Tokens

  • API keys and paths to secrets are to be placed in .env.
  • Never commit any sensitive data to version control.
  • Secure transmission should be done using https during production.

Conclusion

There is great potential of learning about your website performance with API integration of Google Analytics into Node.js with the help of Express. Using this guide, you have not only figured out a way to install a Node.js project and install necessary modules but also how to authenticate in Google Analytics and access the data.

If you find yourself working with the full-stack projects, then take a moment and browse our comprehensive article What is MERN Stack to observe how backend services, such as the one presented here, can be a part of the bigger development picture.

Happy coding.

FAQs

Can I use Google Analytics API with frontend JavaScript?

No, this is not safe. Always utilize it out the server side such as in Node.js.

Yep, the newest v1beta API is compatible with GA4 properties.

Yes, but within the limit of quotas.

Yes, Google too offers real-time reporting options through an alternate endpoint.

You can implement cron jobs into Node.js and call APIs at specific times and send emails.

Be sure to save this blog to your resources, and see additional developer tutorials on analytics, authentication, and full-stack development.

Author

Category on EverSoft

Table of Contents

Read Some Blogs