You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将Firebase Analytics数据嵌入网页并通过API自动化展示?

Answer

Great questions! Yes, you can absolutely both embed Firebase Analytics app data into a webpage and automate displaying key metrics like installs and audience data in your backend UI. Here's a practical, step-by-step breakdown of how to pull this off:

1. Embedding Firebase Analytics App Data into a Webpage

Firebase Analytics for mobile apps is tied to a GA4 property, so you won’t find a pre-built "embed widget" for app analytics—but you can easily build a custom display using the Google Analytics Data API (GA4). The key is to fetch data securely server-side and render it on your frontend:

Step 1: Set Up API Access

  • Head to the Google Cloud Console, select your Firebase project, and enable the Google Analytics Data API.
  • Create a service account, generate a JSON key file, and store it securely (never expose this client-side!).
  • Grant the service account the Analytics Viewer or Analytics Editor role in your GA4 property (you can find this in Firebase Console > Analytics > Settings).

Step 2: Fetch Data Server-Side (Critical!)

Never call the API directly from your frontend—this would expose your service account key. Instead, build a backend endpoint to handle the API request. Here’s a quick Node.js example using the official client library:

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

// Initialize the client with your service account key
const analyticsClient = new BetaAnalyticsDataClient({
  keyFilename: './path/to/your-service-account-key.json'
});

// Fetch weekly app installs
async function getWeeklyInstalls() {
  const [response] = await analyticsClient.runReport({
    property: 'properties/YOUR_GA4_PROPERTY_ID',
    dateRanges: [{ startDate: '7daysAgo', endDate: 'today' }],
    metrics: [{ name: 'appInstalls' }],
  });

  return response.rows[0]?.metricValues[0].value || '0';
}

Step 3: Render Data on Your Webpage

Call your backend endpoint from your frontend and display the data however you like—for example, in a dashboard card:

<div class="dashboard-card">
  <h3>Weekly App Installs</h3>
  <span id="installs-count">Loading...</span>
</div>

<script>
  // Fetch data from your backend API
  fetch('/api/get-weekly-installs')
    .then(res => res.json())
    .then(data => {
      document.getElementById('installs-count').textContent = data.installs;
    })
    .catch(err => console.error('Failed to load installs:', err));
</script>

2. Automating Metrics in Your Backend UI

The same API approach works seamlessly for your backend admin UI. You can build automated dashboards that pull real-time or scheduled data, and even segment metrics to fit your needs:

Key Metrics You Can Fetch

  • Installs: Use the appInstalls metric
  • Audience Data: Segment by country, deviceCategory, or operatingSystem with dimensions, paired with metrics like activeUsers or newUsers
  • Engagement: Track sessionDuration, screenPageViews, or eventCount

Example: Fetch Top 5 Countries by Active Users

async function getTopCountries() {
  const [response] = await analyticsClient.runReport({
    property: 'properties/YOUR_GA4_PROPERTY_ID',
    dateRanges: [{ startDate: '30daysAgo', endDate: 'today' }],
    dimensions: [{ name: 'country' }],
    metrics: [{ name: 'activeUsers' }],
    orderBys: [{ metric: { metricName: 'activeUsers' }, desc: true }],
    limit: 5
  });

  return response.rows.map(row => ({
    country: row.dimensionValues[0].value,
    users: row.metricValues[0].value
  }));
}

Scheduled Updates (Optional)

If real-time data isn’t critical, set up a cron job to fetch metrics hourly/daily and store them in your database. This reduces API calls and makes your UI load faster.

Quick Tips

  • Rate Limits: The GA4 Data API has rate limits—check the official docs to avoid hitting them.
  • Security: Always keep your service account key encrypted and restrict API access to your backend IPs.
  • Customization: Mix and match dimensions/metrics to build exactly the dashboard you need.

内容的提问来源于stack exchange,提问作者Leonardo Pinheiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:16:15