Maximize Website Traffic Analysis with GA4 Property API and Node.js

Maximize Website Traffic Analysis with GA4 Property API and Node.js

In today's digital age, understanding the performance of your website is crucial for success.

Google Analytics has been a go-to tool for webmasters and marketers to gain insights into user behavior, With the introduction of the new Google Analytics GA4 Property, you can now take advantage of advanced features and analytics capabilities.

In this article, we will explore how to leverage the @google-analytics/data package and provide an example code snippet to retrieve views count using the GA4 Property.

What is GA4?

Google Analytics 4 (GA4) is the latest version of Google's analytics platform. It offers a number of new features and capabilities, including the ability to collect data from a wider range of sources, such as mobile apps and offline events.

Benefits of Using GA4

There are a number of benefits to using GA4, including:

  • Cross-platform tracking: GA4 can track users across multiple devices and platforms, giving you a more complete view of their behavior.
  • Enhanced predictive analytics: GA4 uses machine learning to provide more accurate and predictive analytics, helping you to make better decisions about your marketing campaigns.
  • Flexible data model: GA4 uses a flexible data model that makes it easier to integrate with other data sources, such as your CRM system.

How to use GA4 property with NodeJS?

The @google-analytics/data package is a powerful tool that enables developers to interact with the Google Analytics Data API.

It provides a streamlined way to access and retrieve data from your GA4 Property programmatically.

To get started, make sure you have the package installed in your project.

Example code snippet: 

Retrieving Last Day Views:

propertyId = 'YOUR_PROPERTY_ID';

// Imports the Google Analytics Data API client library.
const { BetaAnalyticsDataClient } = require('@google-analytics/data');

const analyticsDataClient = new BetaAnalyticsDataClient();

exports.getLastDayViews = async (req, res, next) => {
  try {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dateRanges: [
        { startDate: 'yesterday', endDate: 'yesterday' },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });

    const visitorsCount = response.rows[0].metricValues[0];

    res.json({
      status: "success",
      result: visitorsCount.value,
    });
  } catch (err) {
    res.status(500).json(err);
  }
};

Retrieving 7-Day Views:

exports.get7DayViews = async (req, res, next) => {
  try {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${process.env.GOOGLE_G4_PROPERTY}`,
      dateRanges: [
        { startDate: '7daysAgo', endDate: 'yesterday' },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });

    const visitorsCount = response.rows[0].metricValues[0];

    res.json({
      status: "success",
      result: visitorsCount.value,
    });
  } catch (err) {
    res.status(500).json(err);
  }
};

Retrieving Monthly Views:

exports.getMonthlyViews = async (req, res, next) => {
  try {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${process.env.GOOGLE_G4_PROPERTY}`,
      dateRanges: [
        { startDate: '30daysAgo', endDate: 'today' },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });

    const visitorsCount = response.rows[0].metricValues[0];

    res.json({
      status: "success",
      result: visitorsCount.value,
    });
  } catch (err) {
    res.status(500).json(err);
  }
};

Retrieving Top-Performing Posts:

exports.getTopPosts = async (req, res, next) => {
  try {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${process.env.GOOGLE_G4_PROPERTY}`,
      dateRanges: [
        { startDate: '30daysAgo', endDate: 'today' },
      ],
      dimensions: [
        {
          name: 'pageTitle',
        },
        {
          name: 'pagePath',
        },
      ],
      metrics: [
        {
          name: 'screenPageViews',
        },
      ],
      limit: 30,
    });

    const modifiedArray = response.rows.map(item => {
      const pageTitle = item.dimensionValues[0].value;
      const slug = item.dimensionValues[1].value;
      const views = item.metricValues[0].value;

      return { pageTitle, slug, views };
    });

    res.json({
      status: "success",
      result: modifiedArray,
    });
  } catch (err) {
    res.status(500).json(err);
  }
};
Conclusion:

The new Google Analytics GA4 Property and the @google-analytics/data package empower website owners and marketers to harness the power of advanced analytics. By implementing the example code snippets provided in this article, you can easily retrieve last day views, 7-day views, monthly views, and top-performing posts.

Utilize these insights to optimize your website's performance, make informed decisions, and achieve your business goals.

Stay ahead of the competition by leveraging the power of data-driven decision making with the Google Analytics GA4 Property and the @google-analytics/data package.

Other Resources:

https://www.npmjs.com/package/@google-analytics/data

https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries

https://googleapis.dev/nodejs/analytics-data/latest/index.html

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment