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

Found this article helpful?

TutsCoder tutorials are free and ad-light — supported by readers like you. Buy me a coffee (or two ☕☕) as a token of appreciation and help keep Angular & Node.js content coming!

One-time. No subscription. 100% optional. 🙏 Every coffee counts!

Leave a Comment

Your email will not be published. Spam-free zone. ✌️

Available for Projects

Need Help With Your
Angular or Node.js Project?

7+ years of MEAN Stack experience. I build scalable Angular 21 apps, Node.js APIs, and SaaS products — delivered on time, every time.

7+ Years MEAN Stack Angular 21 + Nx Expert 20+ Projects Delivered Remote / Freelance