Skip to main content
RapidDev - Software Development Agency
firebase-tutorial

How to Use Firebase Analytics in a Web App

To use Firebase Analytics in a web app, add your Firebase config with the measurementId, call getAnalytics() to initialize, and Analytics automatically starts tracking page views, sessions, and user engagement. Use logEvent() for custom events, setUserProperties() for audience segmentation, and enable consent mode for GDPR compliance. Analytics is completely free on all Firebase plans with no usage limits.

What you'll learn

  • How to initialize Firebase Analytics with the modular SDK in a web app
  • What events Firebase Analytics tracks automatically without any code
  • How to enable debug mode and consent mode for GDPR compliance
  • How to view Analytics data in the Firebase Console
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Beginner8 min read10-15 minFirebase JS SDK v9+, all Firebase plans (Analytics is free)March 2026RapidDev Engineering Team
TL;DR

To use Firebase Analytics in a web app, add your Firebase config with the measurementId, call getAnalytics() to initialize, and Analytics automatically starts tracking page views, sessions, and user engagement. Use logEvent() for custom events, setUserProperties() for audience segmentation, and enable consent mode for GDPR compliance. Analytics is completely free on all Firebase plans with no usage limits.

Setting Up Firebase Analytics in a Web Application

Firebase Analytics (also known as Google Analytics for Firebase) is a free, unlimited analytics solution that tracks user behavior in your web app automatically. Once initialized, it collects events like page_view, session_start, and first_visit without any additional code. This tutorial walks you through setup, automatic events, consent mode configuration for privacy compliance, debug mode for development, and navigating the Analytics dashboard to understand your users.

Prerequisites

  • A Firebase project created in the Firebase Console
  • A web app registered in the Firebase project (with a measurementId)
  • Firebase JS SDK v9+ installed via npm
  • A basic HTML or React/Next.js web application

Step-by-step guide

1

Install the Firebase SDK and initialize Analytics

Install the Firebase package and create a configuration file that initializes both the Firebase app and Analytics. The measurementId (starting with G-) is required for Analytics to function. You can find all config values in the Firebase Console under Project Settings > General > Your Apps.

typescript
1// Install: npm install firebase
2
3import { initializeApp } from 'firebase/app';
4import { getAnalytics, isSupported } from 'firebase/analytics';
5
6const firebaseConfig = {
7 apiKey: 'YOUR_API_KEY',
8 authDomain: 'YOUR_PROJECT.firebaseapp.com',
9 projectId: 'YOUR_PROJECT',
10 storageBucket: 'YOUR_PROJECT.appspot.com',
11 messagingSenderId: '123456789',
12 appId: '1:123456789:web:abc123',
13 measurementId: 'G-XXXXXXXXXX',
14};
15
16const app = initializeApp(firebaseConfig);
17
18// Check if analytics is supported (fails in SSR/Node.js)
19const analytics = await isSupported().then((yes) =>
20 yes ? getAnalytics(app) : null
21);

Expected result: Firebase Analytics is initialized and immediately begins collecting automatic events like page_view and session_start.

2

Understand automatically collected events

Once Analytics is initialized, Firebase automatically tracks several events without any additional code. These events provide baseline engagement data. Key automatic events include page_view (every page load), session_start (new session begins), first_visit (user visits for the first time), user_engagement (user has the app in the foreground), and scroll (user scrolls to 90% of the page).

typescript
1// These events are collected AUTOMATICALLY — no code needed:
2// page_view — fires on every page load
3// session_start — fires when a new session begins
4// first_visit — fires the first time a user visits
5// user_engagement — fires when the app is in the foreground
6// scroll — fires when user scrolls past 90% of page
7// click — fires on outbound link clicks
8// file_download — fires when user clicks a download link
9// video_start — fires when an embedded video starts playing
10
11// Enhanced measurement (enabled by default) handles most of these.
12// You can toggle specific enhanced events in the Firebase Console:
13// Analytics > Admin > Data Streams > Web > Enhanced measurement

Expected result: Basic user engagement metrics appear in the Firebase Console within 24-48 hours after the first user visits.

3

Configure consent mode for GDPR compliance

If your app serves users in regions with privacy regulations (GDPR, CCPA), configure consent mode before initializing Analytics. Consent mode lets Firebase know whether the user has granted or denied consent for analytics and advertising cookies. When consent is denied, Firebase uses cookieless pings that provide aggregate data without identifying individual users.

typescript
1import { getAnalytics, setConsent } from 'firebase/analytics';
2
3// Set default consent state BEFORE initializing Analytics
4setConsent({
5 analytics_storage: 'denied',
6 ad_storage: 'denied',
7 ad_user_data: 'denied',
8 ad_personalization: 'denied',
9});
10
11const analytics = getAnalytics(app);
12
13// When the user accepts cookies, update consent
14function onUserAcceptsCookies() {
15 setConsent({
16 analytics_storage: 'granted',
17 ad_storage: 'granted',
18 ad_user_data: 'granted',
19 ad_personalization: 'granted',
20 });
21}

Expected result: Analytics respects user consent preferences, collecting full data when granted and only aggregate cookieless data when denied.

4

Enable debug mode for real-time event verification

Analytics reports take 24-48 hours to process, which is too slow for development. Enable debug mode to see events in real time using the Firebase Console DebugView. You can enable debug mode by installing the Google Analytics Debugger Chrome extension or by setting a global flag before initialization.

typescript
1// Option 1: Set the global debug flag before Firebase init
2(window as any).self.FIREBASE_ANALYTICS_DEBUG_MODE = true;
3
4// Option 2: Use the Google Analytics Debugger Chrome extension
5// Install from Chrome Web Store and toggle it on
6
7// Option 3: Add a URL parameter to your app
8// Visit: http://localhost:3000?debug_mode=true
9
10// Then open Firebase Console > Analytics > DebugView
11// Events appear in real time as you interact with your app

Expected result: Events appear in the Firebase Console DebugView panel within seconds of being triggered.

5

Handle Analytics in server-side rendering (SSR) frameworks

Firebase Analytics requires a browser environment with window and document objects. In SSR frameworks like Next.js, analytics initialization must be deferred to the client side. Use isSupported() to check if the environment supports Analytics, and initialize only on the client.

typescript
1// For Next.js App Router — use a client component
2'use client';
3
4import { useEffect, useState } from 'react';
5import { getAnalytics, isSupported, Analytics } from 'firebase/analytics';
6import { app } from '@/lib/firebase';
7
8export function AnalyticsProvider({ children }: { children: React.ReactNode }) {
9 const [analytics, setAnalytics] = useState<Analytics | null>(null);
10
11 useEffect(() => {
12 isSupported().then((supported) => {
13 if (supported) {
14 setAnalytics(getAnalytics(app));
15 }
16 });
17 }, []);
18
19 return <>{children}</>;
20}

Expected result: Analytics initializes only in the browser and does not cause SSR errors in Next.js or other server-rendered frameworks.

6

Navigate the Analytics dashboard in the Firebase Console

Open the Firebase Console and click Analytics in the left sidebar. The dashboard shows an overview with active users, events, and revenue. Use the Events tab to see all tracked events with their counts. The User Properties tab shows custom attributes. The DebugView tab shows real-time events from debug-enabled devices. Note that data takes 24-48 hours to appear in standard reports.

Expected result: You can view automatic events, user engagement metrics, and custom events in the Firebase Analytics dashboard.

Complete working example

firebase-analytics.ts
1import { initializeApp } from 'firebase/app';
2import {
3 getAnalytics,
4 isSupported,
5 logEvent,
6 setConsent,
7 setUserProperties,
8 Analytics,
9} from 'firebase/analytics';
10
11const firebaseConfig = {
12 apiKey: 'YOUR_API_KEY',
13 authDomain: 'YOUR_PROJECT.firebaseapp.com',
14 projectId: 'YOUR_PROJECT',
15 storageBucket: 'YOUR_PROJECT.appspot.com',
16 messagingSenderId: '123456789',
17 appId: '1:123456789:web:abc123',
18 measurementId: 'G-XXXXXXXXXX',
19};
20
21const app = initializeApp(firebaseConfig);
22
23// Configure consent mode before init
24setConsent({
25 analytics_storage: 'denied',
26 ad_storage: 'denied',
27 ad_user_data: 'denied',
28 ad_personalization: 'denied',
29});
30
31let analytics: Analytics | null = null;
32
33export async function initAnalytics(): Promise<Analytics | null> {
34 if (analytics) return analytics;
35 const supported = await isSupported();
36 if (supported) {
37 analytics = getAnalytics(app);
38 }
39 return analytics;
40}
41
42export function grantConsent(): void {
43 setConsent({
44 analytics_storage: 'granted',
45 ad_storage: 'granted',
46 ad_user_data: 'granted',
47 ad_personalization: 'granted',
48 });
49}
50
51export function trackEvent(
52 name: string,
53 params?: Record<string, any>
54): void {
55 if (analytics) {
56 logEvent(analytics, name, params);
57 }
58}
59
60export function identifyUser(
61 properties: Record<string, string>
62): void {
63 if (analytics) {
64 setUserProperties(analytics, properties);
65 }
66}

Common mistakes when using Firebase Analytics in a Web App

Why it's a problem: Calling getAnalytics() in a server-side environment (Node.js, Next.js SSR), causing 'window is not defined' errors

How to avoid: Use isSupported() to check for browser support before calling getAnalytics(). In Next.js, initialize Analytics inside a useEffect hook or a 'use client' component.

Why it's a problem: Forgetting the measurementId in the Firebase config, causing Analytics to fail silently

How to avoid: Include the measurementId (starts with G-) in your firebaseConfig object. Find it in Firebase Console > Project Settings > General > Your Apps.

Why it's a problem: Expecting Analytics data to appear immediately in the Firebase Console

How to avoid: Standard reports take 24-48 hours to process. Use DebugView for real-time event verification during development.

Best practices

  • Always use isSupported() before getAnalytics() to handle SSR and environments where Analytics is not available
  • Configure consent mode before initializing Analytics to comply with GDPR and other privacy regulations
  • Use DebugView during development and testing to verify events fire correctly
  • Disable debug mode before deploying to production to keep DebugView clean
  • Leverage enhanced measurement for automatic tracking of scrolls, clicks, downloads, and video engagement
  • Create a centralized analytics module to manage initialization and event logging in one place
  • Set user properties after login to enable audience segmentation in reports
  • Check the Realtime card in the Analytics overview to quickly confirm Analytics is active

Still stuck?

Copy one of these prompts to get a personalized, step-by-step explanation.

ChatGPT Prompt

Set up Firebase Analytics in my Next.js web app using the v9 modular SDK. Show me initialization with isSupported for SSR safety, consent mode configuration for GDPR, debug mode setup, and a client component wrapper. Include TypeScript types.

Firebase Prompt

Initialize Firebase Analytics in a web app with the modular SDK. Handle SSR with isSupported(), configure consent mode with setConsent(), enable debug mode for development, and create a reusable analytics module with trackEvent and identifyUser functions.

Frequently asked questions

Is Firebase Analytics free?

Yes. Firebase Analytics is completely free with no usage limits on events, users, or data retention. You only pay if you export data to BigQuery and run queries there.

What is the difference between Firebase Analytics and Google Analytics 4?

They share the same backend. Firebase Analytics feeds into Google Analytics 4 automatically. You can view data in both the Firebase Console and the GA4 interface. The Firebase SDK handles the integration.

Why do I see no data in the Firebase Analytics dashboard?

Data takes 24-48 hours to appear in standard reports. Check that your measurementId is correct in the config, and use DebugView (Analytics > DebugView) to verify events are being sent in real time.

Can I use Firebase Analytics without other Firebase services?

Yes. You can initialize only Firebase Analytics without using Auth, Firestore, or any other Firebase service. Just include the app and analytics modules.

Does Firebase Analytics work with ad blockers?

Some ad blockers and privacy extensions block Firebase Analytics requests. Consent mode with cookieless pings provides partial data even when blocked. There is no way to guarantee 100% tracking accuracy.

How do I comply with GDPR when using Firebase Analytics?

Use consent mode (setConsent) to default all consent types to 'denied' until the user accepts cookies. Firebase collects only aggregate cookieless data when consent is denied.

Can RapidDev help set up analytics tracking for my web app?

Yes. RapidDev can implement Firebase Analytics with consent mode, custom event tracking, user properties, and BigQuery integration for advanced reporting and dashboards.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.