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
Install the Firebase SDK and initialize Analytics
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.
1// Install: npm install firebase23import { initializeApp } from 'firebase/app';4import { getAnalytics, isSupported } from 'firebase/analytics';56const 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};1516const app = initializeApp(firebaseConfig);1718// Check if analytics is supported (fails in SSR/Node.js)19const analytics = await isSupported().then((yes) =>20 yes ? getAnalytics(app) : null21);Expected result: Firebase Analytics is initialized and immediately begins collecting automatic events like page_view and session_start.
Understand automatically collected events
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).
1// These events are collected AUTOMATICALLY — no code needed:2// page_view — fires on every page load3// session_start — fires when a new session begins4// first_visit — fires the first time a user visits5// user_engagement — fires when the app is in the foreground6// scroll — fires when user scrolls past 90% of page7// click — fires on outbound link clicks8// file_download — fires when user clicks a download link9// video_start — fires when an embedded video starts playing1011// 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 measurementExpected result: Basic user engagement metrics appear in the Firebase Console within 24-48 hours after the first user visits.
Configure consent mode for GDPR compliance
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.
1import { getAnalytics, setConsent } from 'firebase/analytics';23// Set default consent state BEFORE initializing Analytics4setConsent({5 analytics_storage: 'denied',6 ad_storage: 'denied',7 ad_user_data: 'denied',8 ad_personalization: 'denied',9});1011const analytics = getAnalytics(app);1213// When the user accepts cookies, update consent14function 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.
Enable debug mode for real-time event verification
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.
1// Option 1: Set the global debug flag before Firebase init2(window as any).self.FIREBASE_ANALYTICS_DEBUG_MODE = true;34// Option 2: Use the Google Analytics Debugger Chrome extension5// Install from Chrome Web Store and toggle it on67// Option 3: Add a URL parameter to your app8// Visit: http://localhost:3000?debug_mode=true910// Then open Firebase Console > Analytics > DebugView11// Events appear in real time as you interact with your appExpected result: Events appear in the Firebase Console DebugView panel within seconds of being triggered.
Handle Analytics in server-side rendering (SSR) frameworks
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.
1// For Next.js App Router — use a client component2'use client';34import { useEffect, useState } from 'react';5import { getAnalytics, isSupported, Analytics } from 'firebase/analytics';6import { app } from '@/lib/firebase';78export function AnalyticsProvider({ children }: { children: React.ReactNode }) {9 const [analytics, setAnalytics] = useState<Analytics | null>(null);1011 useEffect(() => {12 isSupported().then((supported) => {13 if (supported) {14 setAnalytics(getAnalytics(app));15 }16 });17 }, []);1819 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.
Navigate the Analytics dashboard in the Firebase Console
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
1import { initializeApp } from 'firebase/app';2import {3 getAnalytics,4 isSupported,5 logEvent,6 setConsent,7 setUserProperties,8 Analytics,9} from 'firebase/analytics';1011const 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};2021const app = initializeApp(firebaseConfig);2223// Configure consent mode before init24setConsent({25 analytics_storage: 'denied',26 ad_storage: 'denied',27 ad_user_data: 'denied',28 ad_personalization: 'denied',29});3031let analytics: Analytics | null = null;3233export 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}4142export function grantConsent(): void {43 setConsent({44 analytics_storage: 'granted',45 ad_storage: 'granted',46 ad_user_data: 'granted',47 ad_personalization: 'granted',48 });49}5051export function trackEvent(52 name: string,53 params?: Record<string, any>54): void {55 if (analytics) {56 logEvent(analytics, name, params);57 }58}5960export 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.
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.
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.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation