6 min read

How to Set Up Alerts for Active Users in Google Analytics 4

Your active users are dropping and you need to know immediately—not when you check your dashboard tomorrow. Google Analytics 4 doesn't have native real-time alerts for individual metrics, but you can build them using the Reporting API and a simple script. Here's how.

Method 1: Set Up Alerts Using GA4 Admin Notifications

GA4's built-in notification system works for basic threshold monitoring.

Step 1: Navigate to Notifications in GA4 Admin

Sign into Google Analytics 4 and go to Admin > Notifications. Click Create notification. You'll see options for anomaly detection, which uses machine learning to flag unusual drops, or threshold-based alerts where you specify an exact number.

javascript
// GA4 notifications are configured in the Admin UI
// Store your Property ID for API reference later
const propertyId = '123456789';
const metricsToMonitor = ['activeUsers', 'engagedSessions'];
console.log(`Monitoring property: ${propertyId}`);
Save your Property ID—you'll need it for API calls later

Step 2: Choose Your Alert Type and Threshold

Select Threshold-based if you want to alert when active users drop below a specific number (e.g., 500 daily). Select Anomaly detection to let Google's ML algorithm spot unusual dips automatically. For threshold-based, enter your target number and GA4 will check it daily.

javascript
// Threshold logic example
const dailyActiveUserThreshold = 500;
const anomalyDetection = true;

const shouldAlert = (currentValue, threshold) => {
  return currentValue < threshold;
};

if (shouldAlert(450, dailyActiveUserThreshold)) {
  console.log('ALERT: Active users below threshold');
}
GA4 checks thresholds once per day, typically around midnight UTC

Step 3: Add Recipients and Save

Under Notification settings, add email addresses for your team. You can add multiple recipients. Make sure they have at least Viewer access to the GA4 property to view alerts. Save the notification and GA4 will begin monitoring.

javascript
// Recipients are managed in GA4 Admin UI
// They need Editor or Viewer access to the property
const alertRecipients = ['[email protected]', '[email protected]'];

// Add recipients via Admin > Access management
console.log(`Notifying ${alertRecipients.length} recipients on threshold breach`);
Recipients must have verified Google accounts with GA4 access
Watch out: GA4's daily check means you could miss a traffic drop for 24 hours. If you need hourly or minute-level alerts, use the Reporting API instead.

Method 2: Build Real-Time Alerts with the Google Analytics Data API

For immediate notifications, query GA4's Reporting API and set your own monitoring logic.

Step 1: Create a Service Account and Grant Access

Go to Google Cloud Console > Service Accounts and create a new account. Download the JSON key file. Then in GA4 Admin > Access management, add this service account as an Editor so it can query your property data.

javascript
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
const path = require('path');

const analyticsDataClient = new BetaAnalyticsDataClient({
  keyFilename: path.join(__dirname, 'service-account-key.json')
});

console.log('Service account authenticated to GA4 Reporting API');
Install @google-analytics/data via npm: npm install @google-analytics/data

Step 2: Query Active Users for Today

Use the runReport() method to fetch today's active user count. Specify your property ID and request the activeUsers metric. The API returns data within seconds—much faster than GA4's dashboard UI.

javascript
async function getActiveUsers(propertyId, startDate, endDate) {
  const response = await analyticsDataClient.runReport({
    property: `properties/${propertyId}`,
    dateRanges: [
      {
        startDate: startDate,
        endDate: endDate
      }
    ],
    metrics: [
      { name: 'activeUsers' },
      { name: 'sessions' },
      { name: 'screenPageViews' }
    ]
  });

  const activeUsers = parseInt(response[0].rows[0].metricValues[0].value, 10);
  return activeUsers;
}

const today = await getActiveUsers('123456789', 'today', 'today');
console.log(`Today's active users: ${today}`);
Dates use YYYY-MM-DD format or 'today', 'yesterday', 'NdaysAgo'

Step 3: Compare to Threshold and Send Alert

Check if today's active users fall below your threshold. Optionally, compare to yesterday to detect percentage drops. If the threshold is breached, send an alert via Slack, email, or SMS.

javascript
async function checkAndAlert(propertyId, threshold) {
  const today = await getActiveUsers(propertyId, 'today', 'today');
  const yesterday = await getActiveUsers(propertyId, '1daysAgo', '1daysAgo');
  
  const percentDrop = ((yesterday - today) / yesterday * 100).toFixed(1);
  
  if (today < threshold) {
    const message = `ALERT: Active users = ${today} (${percentDrop}% drop from yesterday)`;
    
    // Send to Slack webhook
    await fetch(process.env.SLACK_WEBHOOK_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text: message })
    });
    
    console.log(message);
  }
}

await checkAndAlert('123456789', 500);
Store webhook URLs in environment variables, not hardcoded

Step 4: Schedule the Script to Run Hourly

Deploy this script to a server (Node.js on Google Cloud Run, AWS Lambda, or Heroku) or schedule it via Google Cloud Scheduler. Set the cron expression to run every hour. You'll receive alerts within minutes of a drop, not 24 hours later.

javascript
// Use node-cron for local scheduling
const cron = require('node-cron');

// Run every hour at minute 0
cron.schedule('0 * * * *', async () => {
  console.log('Running hourly active users check...');
  await checkAndAlert('123456789', 500);
});

// Or use Google Cloud Scheduler with a Cloud Run endpoint
// POST https://us-central1-project.cloudfunctions.net/checkActiveUsers
// Frequency: 0 * * * * (every hour)
console.log('Scheduler running. Ctrl+C to stop.');
Google Cloud Scheduler is free and integrates with Cloud Run
Tip: Combine threshold and percentage-based checks. Alert if users drop below 500 AND it's a 25% drop from the 7-day average—this reduces false positives from normal weekend fluctuations.

Method 3: Monitor with Google Sheets and Apps Script

No coding required. Pull GA4 data into Sheets and set up email alerts.

Step 1: Install the Google Analytics Connector

Open a Google Sheet and go to Extensions > Get add-ons. Search for and install Google Analytics 4. Authorize it to access your GA4 property. This connector pulls metrics directly into your sheet.

javascript
// In Google Apps Script (Tools > Script editor)
function runGA4Report() {
  const analyticsReportRequest = {
    'property': 'properties/YOUR_PROPERTY_ID',
    'dateRanges': [{'startDate': '2025-03-26', 'endDate': '2025-03-26'}],
    'metrics': [{'name': 'activeUsers'}, {'name': 'sessions'}]
  };
  
  const report = Analytics.Properties.runReport(analyticsReportRequest);
  const activeUsers = report.rows[0].metricValues[0].value;
  
  SpreadsheetApp.getActiveSheet().getRange('A1').setValue(activeUsers);
  console.log('GA4 data refreshed: ' + activeUsers);
}

// Run this function manually or via triggers
The connector uses Google Apps Script under the hood

Step 2: Set Up Conditional Formatting to Flag Alerts

Once data is in your sheet, select the cell with active users and go to Format > Conditional formatting. Add a custom formula: =A1<500. Choose a red background to highlight when the threshold is breached. The cell will turn red automatically when active users drop below your limit.

javascript
// Conditional formatting via Apps Script
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('A1:A100');

const rule = SpreadsheetApp.newConditionalFormatRule()
  .whenFormulaSatisfied('=A1<500')
  .setBackground('#FF0000') // Red
  .setRanges([range])
  .build();

sheet.conditionalFormats.push(rule);
console.log('Conditional formatting applied');
Red cells = visual alert. Your team sees status at a glance

Step 3: Send Email Alerts via Apps Script

Write a simple function to send emails when the threshold is breached. Use Tools > Triggers to run this function hourly. When active users drop, everyone on your team gets notified immediately.

javascript
function sendActiveUsersAlert() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const activeUsers = parseInt(sheet.getRange('A1').getValue(), 10);
  const threshold = 500;
  
  if (activeUsers < threshold) {
    const message = `ALERT: GA4 active users = ${activeUsers} (below threshold of ${threshold})`;
    
    GmailApp.sendEmail(
      '[email protected]',
      'Active Users Alert',
      message
    );
    
    console.log('Alert email sent');
  }
}

// Set up trigger: Tools > Triggers > Create new trigger
// Function: sendActiveUsersAlert
// Event source: Time-driven
// Type: Hour timer
Apps Script triggers run on Google's servers—no local server needed
Tip: Combine Sheets with Data Studio for dashboard visualization. Data Studio also connects to GA4 and can email team members when metrics cross thresholds.

Common Pitfalls

  • GA4's built-in alerts check only once daily, usually midnight UTC. A traffic drop at 2am won't trigger until the next day. Use the Reporting API for real-time monitoring.
  • Active user counts depend on consistent user ID and device ID tracking. If your gtag configuration or GTM setup is inconsistent, counts will be unreliable. Verify your tracking before relying on alerts.
  • Service account credentials grant broad access to your GA4 data. Never hardcode them in scripts or commit them to git. Use environment variables or Google Secret Manager instead.
  • GA4 has 24-72 hour latency for some dimensions and attribution data. Real-time alerts work best with basic metrics like activeUsers and sessions, not with custom events or attributed conversions.

Wrapping Up

You now have three approaches: GA4's native daily alerts for simple thresholds, the Reporting API for custom logic and hourly checks, or Google Sheets for a no-code dashboard your whole team can see. Most teams use Sheets for visibility and the API for automated alerts to Slack. If you want to track this automatically across tools, Product Analyst can help.

Track these metrics automatically

Product Analyst connects to your stack and surfaces the insights that matter.

Try Product Analyst — Free