← Back to DevBytes

Monitoring Firebase Auth: Metrics, Alarms, and Dashboards

What Is Firebase Auth Monitoring and Why It Matters

Firebase Authentication handles everything from email/password sign-in to social providers and phone-based auth. When your app scales, the auth layer becomes a critical piece of infrastructure. Monitoring its metrics, setting up alarms, and building dashboards lets you detect anomalies, prevent security incidents, and maintain a smooth user experience. Without proper observability, a spike in failed sign-ins could go unnoticed until users complain or an attacker quietly brute-forces accounts.

Auth monitoring is not just about uptime. It's about understanding user behavior patterns, tracking new registrations, measuring token refresh rates, and catching quota limits before they impact production. By combining Firebase’s built-in metrics with Google Cloud Monitoring and custom logging, you gain a complete picture of your authentication service's health.

Understanding the Available Metrics

Firebase Authentication automatically exports a rich set of metrics to the Firebase console and Google Cloud Monitoring. These metrics are grouped into categories that cover sign-in activity, token operations, user lifecycle events, and provider-specific breakdowns.

Core Authentication Metrics

Log-based Metrics

Beyond the standard metrics, Firebase Auth events are written to Cloud Logging. You can create log-based metrics to track anything that appears in the logs, such as specific error messages, patterns in IP addresses, or custom user attributes. This gives you unlimited flexibility to define your own signals.

How to Access and Export Metrics

Via the Firebase Console

The quickest way to see auth metrics is the Firebase Console under Authentication β†’ Usage. There you'll find charts for sign-in success/failure, new registrations, and top providers over a rolling time window. It’s perfect for ad-hoc checks but not for persistent dashboards or programmatic alerting.

Via Google Cloud Monitoring API

All Firebase Auth metrics are exported as time-series data in Cloud Monitoring under the metric prefix firebaseauth.googleapis.com/auth/. You can query them using the Cloud Monitoring API or the Metrics Explorer. Below is a Node.js example that retrieves the sign-in success count over the last hour.


const { MetricServiceClient } = require('@google-cloud/monitoring').v3;

async function querySignInSuccessCount(projectId) {
  const client = new MetricServiceClient();
  const projectPath = client.projectPath(projectId);

  const filter = `metric.type="firebaseauth.googleapis.com/auth/sign_in_success_count"`;
  const now = new Date();
  const startTime = new Date(now.getTime() - 60 * 60 * 1000); // 1 hour ago

  const request = {
    name: projectPath,
    filter: filter,
    interval: {
      startTime: { seconds: Math.floor(startTime.getTime() / 1000) },
      endTime: { seconds: Math.floor(now.getTime() / 1000) },
    },
    aggregation: {
      alignmentPeriod: { seconds: 300 },
      perSeriesAligner: 'ALIGN_SUM',
    },
    view: 'FULL',
  };

  const [timeSeries] = await client.listTimeSeries(request);
  timeSeries.forEach(ts => {
    console.log('Metric:', ts.metric.labels);
    ts.points.forEach(p => {
      console.log(`Time: ${p.interval.startTime}, Value: ${p.value.int64Value}`);
    });
  });
  return timeSeries;
}

// Example call
querySignInSuccessCount('your-gcp-project-id').catch(console.error);

This code uses the @google-cloud/monitoring client library. It filters by the exact metric type, sets a time interval, and requests a sum alignment every 5 minutes. You can replace the metric type with any Firebase Auth metric, such as firebaseauth.googleapis.com/auth/sign_in_failure_count.

Exporting to External Tools

Cloud Monitoring metrics can be streamed to BigQuery, Grafana, Datadog, or Prometheus via the federated-metrics connector or using the Cloud Monitoring API. For Grafana, simply add the Google Cloud Monitoring data source and build dashboards directly on the same metrics. This centralizes auth observability alongside infrastructure and application metrics.

Building Dashboards for Firebase Auth

Dashboards turn raw metrics into actionable visualizations. You can create them in Google Cloud Monitoring, Grafana, or even build custom real-time dashboards using Firebase services.

Google Cloud Monitoring Dashboards

In the Cloud Console, navigate to Monitoring β†’ Dashboards and create a new dashboard. Add a chart widget, select the Firebase Auth metric, and choose a breakdown by provider. To automate this, you can define the dashboard as JSON and use the gcloud CLI.


// dashboard.json – a minimal example showing sign-in success/failure by provider
{
  "displayName": "Firebase Auth Overview",
  "dashboardFilters": [],
  "widgets": [
    {
      "title": "Sign-in Success by Provider",
      "xyChart": {
        "dataSets": [
          {
            "timeSeriesQuery": {
              "timeSeriesFilter": {
                "filter": "metric.type=\"firebaseauth.googleapis.com/auth/sign_in_success_count\"",
                "aggregation": {
                  "alignmentPeriod": "300s",
                  "perSeriesAligner": "ALIGN_SUM",
                  "crossSeriesReducer": "REDUCE_SUM",
                  "groupByFields": ["metric.labels.provider"]
                }
              }
            },
            "plotType": "LINE"
          }
        ],
        "chartOptions": { "mode": "COLOR" }
      }
    },
    {
      "title": "Sign-in Failures (last hour)",
      "timeSeriesTable": {
        "dataSets": [
          {
            "timeSeriesQuery": {
              "timeSeriesFilter": {
                "filter": "metric.type=\"firebaseauth.googleapis.com/auth/sign_in_failure_count\"",
                "aggregation": {
                  "alignmentPeriod": "3600s",
                  "perSeriesAligner": "ALIGN_SUM"
                }
              }
            },
            "tableDisplayOptions": { "showFullTimeRange": false }
          }
        ]
      }
    }
  ]
}

Deploy it with:


gcloud monitoring dashboards create --config-from-file=dashboard.json

Grafana Dashboards

When using Grafana, add the Google Cloud Monitoring data source. Create a new dashboard, add a panel, and enter the same metric filter in the query editor. Grafana’s templating allows you to switch between projects and environments seamlessly. Combine auth metrics with server-side logs or custom backend metrics for a full picture.

Real-Time Custom Dashboard with Cloud Functions

Sometimes you need real-time counters that update instantly (e.g., a live sign-in activity feed). You can use Firebase Authentication triggers in Cloud Functions to push events to Firestore and build a lightweight dashboard from that data.


const admin = require('firebase-admin');
const functions = require('firebase-functions');

admin.initializeApp();
const db = admin.firestore();

// Increment a daily counter whenever a new user is created
exports.trackNewUser = functions.auth.user().onCreate(async (user) => {
  const date = new Date().toISOString().split('T')[0];
  const ref = db.collection('auth_metrics').doc(date);
  await db.runTransaction(async (t) => {
    const doc = await t.get(ref);
    const data = doc.data() || { newUsers: 0 };
    t.set(ref, { newUsers: data.newUsers + 1 }, { merge: true });
  });
  console.log(`New user ${user.uid} created on ${date}`);
});

// Log sign-in failure events from Cloud Logging via a sink and a Pub/Sub function
// (Alternative: Use Auth triggers are limited to create/delete; for sign-in events you need log-based sinks)

The functions.auth.user().onCreate trigger gives you user creation events in real time. For sign-in success/failure events, you can stream Cloud Logging entries to Pub/Sub and process them in a Cloud Function to update Firestore or push metrics to external systems. This approach enables completely customized dashboards with minimal latency.

Setting Up Alarms and Alerts

Why You Need Auth Alarms

Alarms turn monitoring from a passive observation into an active defense. A sudden 10x spike in sign-in failures might indicate a credential stuffing attack. A drop in new registrations could mean a broken onboarding flow. Quota exhaustion can silently block users. Alarms let you respond before users notice a problem.

Creating Alert Policies in Cloud Monitoring

Alert policies define a condition on a metric, a notification channel, and an optional duration. The Node.js example below creates an alert that fires when the sign-in failure rate exceeds a threshold for 5 minutes.


const { AlertPolicyServiceClient } = require('@google-cloud/monitoring').v3;

async function createHighFailureAlert(projectId, notificationChannelId) {
  const client = new AlertPolicyServiceClient();
  const projectPath = client.projectPath(projectId);

  const alertPolicy = {
    displayName: 'High sign-in failure rate',
    combiner: 'AND',
    conditions: [
      {
        displayName: 'Failure rate exceeds threshold',
        conditionThreshold: {
          filter: `metric.type="firebaseauth.googleapis.com/auth/sign_in_failure_count"`,
          aggregations: [
            {
              alignmentPeriod: { seconds: 300 },
              perSeriesAligner: 'ALIGN_SUM',
              crossSeriesReducer: 'REDUCE_SUM',
            },
          ],
          comparison: 'COMPARISON_GT',
          thresholdValue: 50, // more than 50 failures in 5 minutes
          duration: { seconds: 300 },
          trigger: { count: 1 },
        },
      },
    ],
    notificationChannels: [
      `projects/${projectId}/notificationChannels/${notificationChannelId}`,
    ],
    enabled: true,
  };

  const [newPolicy] = await client.createAlertPolicy({
    name: projectPath,
    alertPolicy,
  });
  console.log(`Created alert policy: ${newPolicy.name}`);
  return newPolicy;
}

// Usage – replace with your notification channel ID (e.g., email, Slack, PagerDuty)
createHighFailureAlert('your-project-id', '123456789').catch(console.error);

You can adjust the thresholdValue and duration to match your baseline. For a lower-traffic app, a threshold of 20 failures might be significant. The notificationChannels array can include multiple channels so that the alert reaches on-call engineers via email, SMS, Slack, or PagerDuty.

Common Notification Channels

Example: Detecting Brute Force Attempts

A brute force attack often shows a high number of sign-in failures from a single IP or for a single email. While Firebase Auth includes built-in rate limiting, you can create a log-based metric that counts failures grouped by the ip field from Cloud Logging. Then set an alert condition:


// Example MQL for a log-based metric counting failures per IP
fetch auth_log_metric
| metric 'logging.googleapis.com/user/my_failure_per_ip'
| group_by(ip)
| window 5m
| condition gt(val(), 30)

This approach gives you early warning and the ability to trigger automated IP blocking via Cloud Functions.

Best Practices for Firebase Auth Monitoring

Conclusion

Monitoring Firebase Auth is not a one-time setup β€” it's an evolving practice that grows with your user base and threat landscape. By tapping into Google Cloud Monitoring's metrics, building dashboards that surface key signals, and configuring alarms that catch anomalies early, you turn your authentication layer from a black box into a transparent, manageable service. Whether you rely on the Firebase console for quick checks, Cloud Monitoring API for automation, or custom real-time functions for live feeds, the goal remains the same: protect your users and your application with proactive observability.

Start today by connecting your Firebase project to Cloud Monitoring, creating a dashboard for the top three auth metrics, and setting an alert for abnormal failure rates. From there, expand gradually, incorporating provider-specific views and log-based custom metrics as your operational maturity grows.

πŸš€ Need a reliable AI agent for your project?

Deploy Hermes Agent in 10 minutes. Managed hosting, zero DevOps.

Get Started β€” $23.99/mo
← Back to all articles