Last updated Jun 14, 2023

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

Unlock GA4 insights using Node.js. Build automated reports, track user behavior, and optimize your website traffic with real-world examples.

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

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

Tags

Available for projectsLet’s build together

Need this built properly,
not just explained?

I take on Angular and NestJS work directly — auth systems, multi-tenant SaaS, API rewrites and the deploy pipeline underneath them. You talk to the person writing the code.

Projects delivered
20+ Projects delivered
Angular • NestJS
7+ years Angular • NestJS
Average reply time
1 day Average reply time

What I can help with

  • Auth and permissions systems
  • Multi-tenant SaaS foundations
  • API design and rewrites
  • Deploy pipelines and VPS setup
  • Bug fixing and performance optimization
Send me a message

Tell me about your project and I’ll get back with a realistic scope and price.

Turn
Your Ideas
Into Reality

Stay in the loop

Get the finished tutorials, projects and resources in your inbox.

Join 5,000+ developers and get new tutorials, source code, product updates and exclusive content — straight to your inbox.

  • No spam
  • Useful content only
  • Unsubscribe anytime

Subscribe to TutsCoder

Be the first to get new tutorials, projects and tips.

Join 5,000+ developers already learning with us.

Learn
Build
Grow

Discussion

Comments

Share your thoughts, ask questions or suggest improvements. Let’s learn and grow together!

Loading comments…

Join the discussion

Sign in to join the discussion. Your account also keeps your saved tutorials and path progress.