Skip to content
Learni
View all tutorials
Firebase

How to Implement Firebase Analytics in 2026

Lire en français

Introduction

Firebase Analytics, Google's free solution, lets you collect precise behavioral data from your web and mobile apps without any infrastructure hassle. In 2026, with the rise of PWAs and hybrid apps, it integrates natively via the Firebase SDK v10+, delivering real-time reports, audience segmentation, and funnel analysis. Unlike tools like Google Analytics 4 (GA4), Firebase shines with custom events and crash reports at minimal latency (<1s). This intermediate tutorial guides you step-by-step through a vanilla JS implementation: from console setup to advanced analysis. You'll end up with robust, GDPR-compliant tracking via consent mode, boosting your SEO and monetization. At the end, analyze 100% of your sessions in 5 minutes.

Prerequisites

  • Free Google account with access to the Firebase Console
  • Intermediate HTML/JavaScript knowledge
  • Code editor (VS Code recommended)
  • Local server (VS Code Live Server extension or npx serve)
  • Browser with DevTools (Chrome for Firebase Debugger)

Set up the project structure

terminal
mkdir firebase-analytics-demo
cd firebase-analytics-demo
npm init -y
npm install --save-dev vite
mkdir src
touch src/index.html src/firebase-config.js src/analytics.js
npm run dev

These commands initialize a minimal Vite project to serve the app locally at http://localhost:5173. Vite provides fast hot reload, perfect for real-time Analytics event testing. Avoid simple static servers that block Firebase scripts due to CORS.

Configure your Firebase project in the console

  1. Go to console.firebase.google.com and create a new project (e.g., 'analytics-demo').
  2. Enable Analytics in Project Settings > Integrations (free, no credit card needed).
  3. Click Web () to add a web app, name it 'demo-web', and enable Firebase Hosting if needed.
  4. Copy the generated firebaseConfig object (apiKey, authDomain, etc.). It looks like this: { apiKey: "AIza...", ... }.
Tip: Use DebugView mode by adding 'firebase-analytics-debug' as a query string (?debug_mode=1) for instant validation.

Add Firebase configuration

src/firebase-config.js
import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.13.0/firebase-app.js';
import { getAnalytics, logEvent } from 'https://www.gstatic.com/firebasejs/10.13.0/firebase-analytics.js';

const firebaseConfig = {
  apiKey: "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "analytics-demo.firebaseapp.com",
  projectId: "analytics-demo",
  storageBucket: "analytics-demo.firebasestorage.app",
  messagingSenderId: "123456789",
  appId: "1:123456789:web:abcdef123456",
  measurementId: "G-XXXXXXXXXX"
};

const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);

export { logEvent };

This file imports Firebase SDK v10.13 via CDN (no npm install for vanilla simplicity). Replace firebaseConfig with your console values. measurementId enables Analytics; without it, no events are tracked. Pitfall: Double-check the auth domain to avoid 403 errors.

Initialize the app and track page views

src/index.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Firebase Analytics Demo</title>
  <script type="module" src="/src/firebase-config.js"></script>
  <script type="module" src="/src/analytics.js"></script>
</head>
<body>
  <h1>Demo Firebase Analytics</h1>
  <button id="purchase-btn">Acheter (Événement custom)</button>
  <button id="login-btn">Se connecter</button>
  <p id="status">Analytics prêt</p>
</body>
</html>

Basic HTML page with ES modules to load config and analytics. Buttons trigger standard/custom events. Add ?debug_mode=1 to the URL to see real-time logs in Firebase DebugView. Avoid inline scripts for better maintainability.

Implement event tracking

src/analytics.js
import { analytics, logEvent } from './firebase-config.js';

const statusEl = document.getElementById('status');
const purchaseBtn = document.getElementById('purchase-btn');
const loginBtn = document.getElementById('login-btn');

// Auto-track page view à l'init
logEvent(analytics, 'page_view', {
  page_title: document.title,
  page_location: window.location.href
});
statusEl.textContent = 'Page view tracké !';

purchaseBtn.addEventListener('click', () => {
  logEvent(analytics, 'purchase', {
    currency: 'EUR',
    value: 29.99,
    items: [{ item_id: 'prod_123', item_name: 'Super Gadget' }]
  });
  statusEl.textContent = 'Achat tracké !';
});

loginBtn.addEventListener('click', () => {
  logEvent(analytics, 'login');
  statusEl.textContent = 'Connexion trackée !';
});

This script sets up automatic page view tracking and attaches events to buttons (purchase with e-commerce params, standard login). Params follow the standard event schema. Pitfall: Always include currency for monetary values; otherwise, revenue is ignored.

Verify and analyze data

Open your app at localhost:5173?debug_mode=1. In Firebase Console > Analytics > DebugView, watch events live (2-5s latency). For production:

  • Realtime: Live sessions.
  • Events: Count purchase/login.
  • Audiences: Create 'Buyers' (purchase >0).

Disable debug in production. Full reports propagate in 24h.

Set user properties

src/user-properties.js
import { getAnalytics, setUserId, setUserProperties } from 'https://www.gstatic.com/firebasejs/10.13.0/firebase-analytics.js';
import { analytics } from './firebase-config.js';

// ID utilisateur anonyme ou authentifié
setUserId(analytics, 'user_12345');

// Propriétés custom (max 25)
setUserProperties(analytics, {
  userType: 'premium',
  subscription_plan: 'pro_monthly',
  country: 'FR'
});

console.log('Propriétés utilisateur définies');

Add this script after init to segment users (e.g., premium vs free). setUserId persists across sessions; custom properties enhance audiences. Limits: 25 props/user, strings <100 chars. Integrate after Firebase Auth login for realism.

Handle GDPR consent mode

src/consent.js
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('consent', 'default', {
  'analytics_storage': 'denied'
});

// Fonction pour accepter (appelée par bouton consent)
function acceptAnalytics() {
  gtag('consent', 'update', {
    'analytics_storage': 'granted'
  });
  // Ré-logger événements bloqués si besoin
}

export { acceptAnalytics };

Integrate Google Consent Mode for GDPR: Analytics blocked by default until consent. Call acceptAnalytics() on CMP button click. Compatible with Firebase v10+. Pitfall: Without it, 0% opt-in in EU; test with chrome://settings/content/cookies.

Best practices

  • Event names: Use kebab-case (e.g., 'add_to_cart'), max 40 chars, prefix custom ('app_open').
  • Param limits: 25/event, always include value/currency for e-commerce.
  • Sampling: Beyond 500k users/month, enable BigQuery export (free 1GB/day).
  • Consent: Implement CMP as above + Google Tag Manager for multi-tools.
  • Performance: Load SDK async; test with Lighthouse (Analytics doesn't impact score).

Common errors to avoid

  • Incomplete config: Forgetting measurementId → zero data. Check Firebase console.
  • Forgotten debug: Events visible only 24h in DebugView; use for dev only.
  • Non-standard events: 'click_button' instead of 'select_item' loses predefined reports.
  • No userId: Can't track cross-device without it.

Next steps