DEV Community

Cover image for Integrating Firebase Analytics and Crashlytics in React Native
Sergiu
Sergiu

Posted on

1 1

Integrating Firebase Analytics and Crashlytics in React Native

I decided to write this tutorial after Client ask me to integrate Crashlytics and Analytics from Firebase, and I din't find something decent and clear on how to integrate and https://rnfirebase.io/analytics/ dosen't provide the totaly right and updated, clear code. And migration to v22 also dosn't help a lot.

Integrating Firebase Analytics and Crashlytics in React Native (v0.72+)

This tutorial walks you through how to integrate Firebase Analytics and Crashlytics into a React Native app using Expo SDK 52+ and React Native Firebase packages. The focus is Android, with no native code changes required.

Prerequisites

  • React Native app using Expo SDK 52+
  • Create a Firebase project at https://console.firebase.google.com
  • Download google-services.json from Firebase console and place it in your project root

Install Packages

yarn add @react-native-firebase/app @react-native-firebase/analytics @react-native-firebase/crashlytics
Enter fullscreen mode Exit fullscreen mode

Firebase Configuration File

Create a firebase.json file in the root of your project with the following config:

{
  "react-native": {
    "crashlytics_debug_enabled": true,
    "crashlytics_disable_auto_disabler": true,
    "crashlytics_auto_collection_enabled": true,
    "crashlytics_is_error_generation_on_js_crash_enabled": true,
    "crashlytics_javascript_exception_handler_chaining_enabled": true,
    "analytics_auto_collection_enabled": true,
    "analytics_collection_deactivated": false
  }
}
Enter fullscreen mode Exit fullscreen mode

This enables automatic crash logging, JS error chaining, and analytics collection.

Create a TrackingService Class

// tracking/TrackingService.ts

import {
  getAnalytics,
  logEvent,
  logScreenView,
} from '@react-native-firebase/analytics';

import {
  getCrashlytics,
  setAttributes,
  setCrashlyticsCollectionEnabled,
  setUserId,
} from '@react-native-firebase/crashlytics';

interface EventParams {
  [key: string]: string | number | boolean;
}

class TrackingService {
  // Logs crash or error events (e.g., exceptions)
  static async recordError(error: Error, context: Record<string, string> = {}) {
    const crashlytics = getCrashlytics();

    if (context && Object.keys(context).length > 0) {
      await crashlytics.setAttributes(context); // Add custom error context
    }

    await crashlytics.recordError(error); // Report the error to Firebase

    if (__DEV__) {
      console.error('Tracked error:', error, context);
    }
  }

  // Log any custom event (e.g., "checkout", "screen_loaded")
  static async logEvent(eventName: string, params: EventParams = {}) {
    const analytics = getAnalytics();
    await logEvent(analytics, eventName, params);

    if (__DEV__) {
      console.log('Tracked event:', eventName, params);
    }
  }

  // Tracks screen transitions
  static async logScreenView(screenName: string) {
    const analytics = getAnalytics();
    await logScreenView(analytics, {
      screen_name: screenName,
    });

    if (__DEV__) {
      console.log('Tracked screen view:', screenName);
    }
  }

  // Add device/user context to crash reports (e.g., ID, session, role)
  static async setDeviceContext(context: Record<string, string>) {
    const crashlytics = getCrashlytics();

    await setCrashlyticsCollectionEnabled(crashlytics, true);
    await setAttributes(crashlytics, context); // Add custom context data
    await setUserId(crashlytics, context.deviceId); // Optional: set user ID
  }
}

export default TrackingService;
Enter fullscreen mode Exit fullscreen mode

Usage Examples

import TrackingService from './tracking/TrackingService';

// Record a handled error
TrackingService.recordError(new Error('Something went wrong'), {
  screen: 'Home',
  deviceId: 'T12345',
});

// Log a custom event
TrackingService.logEvent('voucher_redeemed', {
  id: 'abc123',
  discount: 20,
});

// Log screen view
TrackingService.logScreenView('PaymentSuccess');

// Set context on app start or login
TrackingService.setDeviceContext({
  deviceId: 'T12345',
  role: 'admin',
});
Enter fullscreen mode Exit fullscreen mode

P.S. And YES this tutorial is written using AI, but it use my code after a lot of changes and fixes.

Warp.dev image

Warp is the #1 coding agent.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

DevCycle image

Fast, Flexible Releases with OpenFeature Built-in

Ship faster on the first feature management platform with OpenFeature built-in to all of our open source SDKs.

Start shipping

👋 Kindness is contagious

Explore this insightful piece, celebrated by the caring DEV Community. Programmers from all walks of life are invited to contribute and expand our shared wisdom.

A simple "thank you" can make someone’s day—leave your kudos in the comments below!

On DEV, spreading knowledge paves the way and fortifies our camaraderie. Found this helpful? A brief note of appreciation to the author truly matters.

Let’s Go!