@syfra3/react-native-monitor
v2.1.8
Published
Comprehensive performance monitoring solution for React Native applications
Maintainers
Readme
Syfra React Native Performance Monitor
A comprehensive performance monitoring solution for React Native applications. The SDK automatically tracks network requests, crashes, errors, and native metrics (FPS, memory, CPU). Screen renders, navigation, and interactions can be tracked using hooks or providers.
Table of Contents
- Features
- Installation
- Manual Integration
- Quick Start
- Usage Examples
- API Reference
- Performance Report Structure
- Configuration
- Troubleshooting
- Requirements
- License
Features
Automatic Tracking
- Automatic Network Tracking: Intercepts all
fetch()andXMLHttpRequestcalls - Automatic Error Tracking: Global error handlers and unhandled promise rejection tracking
- Automatic Crash Reporting: Native and JavaScript crash detection
- Automatic Native Metrics: Frame rate, memory, CPU usage collected automatically
Manual Tracking (Hooks & Providers)
- Screen Performance: Track screen renders using
useScreenPerformancehook orNavigationTrackingProvider - Navigation Tracking: Track navigation transitions using
useNavigationTrackinghook orNavigationTrackingProvider - Interaction Tracking: Track user interactions using
useInteractionTrackinghook
Core Monitoring
- Screen Performance: Track render times, mount times, and render counts for all screens
- Component Tracking: Monitor component re-renders and performance
- Interaction Tracking: Track button presses, gestures, scrolls, and text inputs
- Navigation Tracking: Monitor navigation transitions and render times
Native Metrics
- Frame Rate: UI and JavaScript FPS tracking
- Memory Usage: Heap, native heap, and system memory monitoring
- CPU Usage: Real-time CPU utilization tracking
- Dropped Frames: Detection of slow and frozen frames
- Battery Level: Battery state monitoring
- Thermal State: Device thermal state tracking
Advanced Features
- Breadcrumb Events: Individual events sent during session (screen renders, interactions, network requests, crashes)
- Performance Reports: Aggregated summaries sent on session end with health scores and warnings
- User Context: Track user ID, session ID, geographic region, and network type
- Network Monitoring: Automatic network request tracking with latency and error rates
- Stability Metrics: Crash and ANR tracking with error rates
- Bundle Size Validation: Track and validate bundle size against thresholds
- Report Export: Export performance reports to JSON or CSV
Installation
Using npm/yarn
npm install @syfra3/react-native-monitor
# or
yarn add @syfra3/react-native-monitoriOS Setup
cd ios && pod install && cd ..The module will be automatically linked via CocoaPods.
Android Setup
The module should be automatically linked. If not, see Manual Integration below.
Manual Integration
If automatic linking doesn't work or you prefer manual integration, follow these steps:
iOS Manual Integration
- Add the pod to your
Podfile:
pod 'RNSyfraMonitor', :path => '../node_modules/@syfra3/react-native-monitor'- Install pods:
cd ios && pod install && cd ..- Import in your Swift/Objective-C code (if needed):
The module is automatically available through the bridge.
Android Manual Integration
- Add to
android/settings.gradle:
include ':@syfra3/react-native-monitor'
project(':@syfra3/react-native-monitor').projectDir = new File(rootProject.projectDir, '../node_modules/@syfra3/react-native-monitor/android')- Add dependency in
android/app/build.gradle:
dependencies {
implementation project(':@syfra3/react-native-monitor')
// ... other dependencies
}- Add package in
MainApplication.javaorMainApplication.kt:
Java:
import co.syfra.rnmonitor.RNSyfraMonitorPackage;
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNSyfraMonitorPackage() // Add this line
);
}Kotlin:
import co.syfra.rnmonitor.RNSyfraMonitorPackage
override fun getPackages(): List<ReactPackage> {
return listOf(
MainReactPackage(),
RNSyfraMonitorPackage() // Add this line
)
}- Sync Gradle:
cd android && ./gradlew clean && cd ..Quick Start
Initialization
Initialize the SDK once when your app starts (e.g., in index.js or App.tsx):
import { SyfraMonitor } from '@syfra3/react-native-monitor';
// Initialize once at app startup
await SyfraMonitor.init({
url: 'https://syfra.co/',
org: 'your-org',
project: 'your-project', // Optional: Auto-detected from app name if not provided
authToken: 'your-auth-token',
enableLogs: true, // Optional: Enable debug logs
});What Gets Tracked Automatically
After initialization, the SDK automatically tracks:
Network Requests:
- Intercepts all
fetch()calls - Intercepts all
XMLHttpRequestcalls - Captures URL, method, latency, status, headers, body
Crashes & Errors:
- Global error handlers
- Unhandled promise rejections
- Fatal error detection
- Native crash reporting (if enabled)
Performance Metrics:
- Frame rate (UI & JS FPS)
- Memory usage (heap, native heap, system)
- CPU usage
- Collected at configurable intervals
Manual Tracking Setup
To track screen renders, navigation, and interactions, use hooks or providers:
Screen Tracking
Option 1: Using NavigationTrackingProvider (Recommended for React Navigation)
import { NavigationTrackingProvider } from '@syfra3/react-native-monitor';
import { NavigationContainer } from '@react-navigation/native';
function App() {
return (
<NavigationTrackingProvider>
<NavigationContainer>
{/* Screens and navigation automatically tracked */}
</NavigationContainer>
</NavigationTrackingProvider>
);
}Option 2: Using useScreenPerformance Hook
import { useScreenPerformance } from '@syfra3/react-native-monitor';
function HomeScreen() {
useScreenPerformance({ screenName: 'HomeScreen' });
return <View>...</View>;
}Navigation Tracking
Option 1: Using NavigationTrackingProvider (Recommended for React Navigation)
The NavigationTrackingProvider automatically tracks navigation transitions when used with React Navigation.
Option 2: Using useNavigationTracking Hook
import { useNavigationTracking } from '@syfra3/react-native-monitor';
function MyScreen() {
useNavigationTracking({ screenName: 'MyScreen' });
return <View>...</View>;
}Interaction Tracking
import { useInteractionTracking } from '@syfra3/react-native-monitor';
function MyComponent() {
const { trackButtonPress } = useInteractionTracking();
return (
<Button
title="Submit"
onPress={() => {
trackButtonPress('SubmitButton');
// Your logic here
}}
/>
);
}Understanding Data Flow
The SDK sends two types of data to your backend:
Breadcrumbs (
type: 'event'):- Individual events sent during the session
- Screen renders, interactions, navigation, network requests, crashes
- Includes performance metrics snapshot (CPU, memory, FPS)
- Sent when batch conditions are met or session ends
Performance Reports (
type: 'report'):- Aggregated summary sent when session ends
- Contains health scores, warnings, aggregated metrics
- Linked to breadcrumbs via
sessionId
Get Performance Report
import { getPerformanceReport } from '@syfra3/react-native-monitor';
const report = await getPerformanceReport();
console.log(JSON.stringify(report, null, 2));End Session Manually
import { endSession } from '@syfra3/react-native-monitor';
// This sends:
// 1. All pending breadcrumb events (type: 'event')
// 2. Performance report (type: 'report')
await endSession();Usage Examples
Complete Setup with React Navigation
If you're using React Navigation, wrap your NavigationContainer with NavigationTrackingProvider:
import React from 'react';
import { SyfraMonitor, NavigationTrackingProvider } from '@syfra3/react-native-monitor';
import { NavigationContainer } from '@react-navigation/native';
// Initialize SDK (do this once at app startup)
await SyfraMonitor.init({
url: 'https://syfra.co/',
org: 'your-org',
project: 'your-project',
authToken: 'your-auth-token',
});
function App() {
return (
<NavigationTrackingProvider>
<NavigationContainer>
{/* All screens and navigation are tracked */}
</NavigationContainer>
</NavigationTrackingProvider>
);
}What Happens Automatically
After initialization, the SDK automatically:
Intercepts Network Requests:
- All
fetch()calls - All
XMLHttpRequestcalls - Captures URL, method, latency, status, headers, body
- All
Tracks Crashes & Errors:
- Global JavaScript errors
- Unhandled promise rejections
- Fatal errors (auto-detected)
- Native crashes (if enabled)
Collects Performance Metrics:
- Frame rate (UI & JS FPS)
- Memory usage (heap, native heap, system)
- CPU usage
- At configurable intervals (default: 1 second)
Data Flow: Breadcrumbs vs Reports
The SDK sends two types of data to your backend:
Breadcrumbs (type: 'event'):
- Individual events sent during the session
- Includes: screen renders, interactions, navigation, network requests, crashes
- Each breadcrumb includes a performance metrics snapshot (CPU, memory, FPS)
- Sent when batch conditions are met (size, time, volume) or session ends
- Stored in InfluxDB for time-series analysis
Performance Reports (type: 'report'):
- Aggregated summary sent when session ends
- Contains: health scores, warnings, aggregated metrics, static data
- Linked to breadcrumbs via
sessionId - Stored in InfluxDB for trend analysis and version comparisons
Session End Flow:
- All pending breadcrumb events are flushed (sent as
type: 'event') - Performance report is generated and sent (sent as
type: 'report') - Both are linked via
sessionIdfor correlation
### Screen Performance Tracking (Manual)
Track how long screens take to render:
```typescript
import { useScreenPerformance } from '@syfra3/react-native-monitor';
function ProfileScreen() {
useScreenPerformance({ screenName: 'ProfileScreen' });
return (
<View>
<Text>Profile Screen</Text>
</View>
);
}Or manually record screen renders:
import { recordScreenRender } from '@syfra3/react-native-monitor';
recordScreenRender('HomeScreen', 150); // screenName, renderTime in msInteraction Tracking
Track user interactions with different types:
import { useInteractionTracking, InteractionType } from '@syfra3/react-native-monitor';
function MyComponent() {
const {
trackButtonPress,
trackGesture,
trackScroll,
trackTextInput
} = useInteractionTracking();
return (
<ScrollView onScroll={() => trackScroll('MainScrollView')}>
<TextInput
onChangeText={() => trackTextInput('SearchInput')}
placeholder="Search..."
/>
<Button
title="Submit"
onPress={() => trackButtonPress('SubmitButton')}
/>
<TouchableOpacity
onPress={() => trackGesture('SwipeGesture', 200)}
>
<Text>Swipe Me</Text>
</TouchableOpacity>
</ScrollView>
);
}Or manually record interactions:
import { recordInteraction, InteractionType } from '@syfra3/react-native-monitor';
recordInteraction(InteractionType.BUTTON_PRESS, 'MyButton', undefined, 50);
recordInteraction(InteractionType.GESTURE, 'Swipe', 200, 150);
recordInteraction(InteractionType.SCROLL, 'ScrollView', undefined, 30);
recordInteraction(InteractionType.TEXT_INPUT, 'InputField', undefined, 20);Component Render Tracking
Track component re-renders:
import { useRenderTracking } from '@syfra3/react-native-monitor';
function ExpensiveComponent() {
useRenderTracking({ componentName: 'ExpensiveComponent' });
return <View>...</View>;
}Navigation Tracking
Track navigation performance:
import { useNavigationTracking } from '@syfra3/react-native-monitor';
function MyScreen() {
useNavigationTracking({ screenName: 'MyScreen' });
return <View>...</View>;
}Or manually record navigation:
import performanceMonitor from '@syfra3/react-native-monitor';
performanceMonitor.recordNavigation('HomeScreen', 'ProfileScreen', 200, 150);User Context
Set user context for better debugging and prioritization:
import { setUserContext, NetworkType } from '@syfra3/react-native-monitor';
setUserContext({
userId: 'user123',
sessionId: 'session456',
geographicRegion: 'US-West',
networkType: NetworkType.WIFI, // or let it auto-detect
});The library automatically detects network type if @react-native-community/netinfo is installed (optional dependency).
Error Tracking
Errors are automatically tracked, but you can also manually record them:
import { recordError } from '@syfra3/react-native-monitor';
try {
// Your code
} catch (error) {
await recordError({
error: error.message,
errorMessage: error.message,
errorType: error.name,
stackTrace: error.stack,
isUnhandled: false,
});
}Getting Performance Reports
Get a comprehensive performance report:
import { getPerformanceReport } from '@syfra3/react-native-monitor';
const report = await getPerformanceReport();
console.log('Screens:', report.screens);
console.log('Interactions:', report.interactions);
console.log('Errors:', report.errors);
console.log('User Context:', report.userContext);
console.log('Stability:', report.metrics.stability);Exporting Reports
Export reports to JSON:
import { exportPerformanceReport } from '@syfra3/react-native-monitor';
const jsonReport = await exportPerformanceReport();
console.log(jsonReport); // JSON string
// Save to file
import { saveReportToFile } from '@syfra3/react-native-monitor';
const result = await saveReportToFile({
format: 'json',
filename: 'performance-report',
});
console.log('Saved to:', result.filePath);Custom Configuration
Configure the SDK during initialization with specific settings:
import { SyfraMonitor } from '@syfra3/react-native-monitor';
SyfraMonitor.init({
// Required infrastructure configuration
url: 'https://syfra.co/',
org: 'your-org',
project: 'your-project',
authToken: 'your-auth-token',
// Optional: Enable logs (defaults to false)
enableLogs: true,
// Optional: Customize thresholds and limits
sampleInterval: 2000, // Collect metrics every 2 seconds (default: 1000ms)
maxInteractions: 2000, // Store up to 2000 interactions (default: 1000)
maxNavigationEvents: 1000, // Store up to 1000 navigation events (default: 500)
warningThresholds: {
slowScreenRenderTime: 500,
slowInteractionResponseTime: 100,
lowUIFPS: 60,
lowJSFPS: 60,
highMemoryUsage: 200 * 1024 * 1024, // 200MB
highCPUUsage: 30, // 30%
networkLatency: 1000, // 1 second
networkErrorRate: 0.01, // 1%
crashRate: 0.01, // 1%
bundleSize: {
warning: 5 * 1024 * 1024, // 5MB
error: 10 * 1024 * 1024, // 10MB
},
},
});Note: For advanced use cases, you can also create custom monitor instances using createPerformanceMonitor(), but you must still provide infrastructure configuration.
Note: Screen tracking, navigation tracking, and interaction tracking require manual setup using hooks or NavigationTrackingProvider. Network requests, errors, crashes, and native metrics are tracked automatically.
Bundle Size Checking
Check and validate bundle size:
import { checkBundleSize } from '@syfra3/react-native-monitor';
const result = await checkBundleSize();
if (result.status === 'error') {
console.error('Bundle too large!', result.message);
} else if (result.status === 'warning') {
console.warn('Bundle size warning:', result.message);
} else {
console.log('Bundle size OK:', result.message);
}Using HOC (Higher-Order Component)
Wrap components to automatically track performance:
import { withPerformanceTracking } from '@syfra3/react-native-monitor';
function MyScreen() {
return <View>...</View>;
}
export default withPerformanceTracking(MyScreen, {
screenName: 'MyScreen',
componentName: 'MyScreen',
});Note: This HOC provides an alternative way to track component performance. You can also use hooks for more granular control.
Reset Metrics
Reset all collected metrics:
import { resetPerformanceMetrics } from '@syfra3/react-native-monitor';
resetPerformanceMetrics();Syfra Backend Integration
The SDK automatically sends performance data to your Syfra backend infrastructure. The integration handles batching, sampling, and secure transmission according to the Data Flow Architecture.
Automatic Data Transmission
Once initialized, the SDK automatically:
- Collects performance events and metrics
- Batches events locally for efficient transmission
- Sends data to your infrastructure endpoint
- Applies intelligent sampling (100% for critical events, configurable for normal sessions)
Manual Data Sending
You can also manually send reports or session traces:
import {
getSyfraBackendIntegration,
getPerformanceReport,
getSessionTrace
} from '@syfra3/react-native-monitor';
const integration = getSyfraBackendIntegration();
// Send a performance report
const report = await getPerformanceReport();
const result = await integration.sendReport(report);
if (result.success) {
console.log(`Sent ${result.eventsProcessed} events to backend`);
}
// Send a session trace
const trace = getSessionTrace();
if (trace) {
const traceResult = await integration.sendSessionTrace(trace);
console.log(`Sent session trace with ${trace.events.length} events`);
}
// Flush buffered events immediately
await integration.flush();
// Check buffer status
const status = integration.getBufferStatus();
console.log(`Buffer: ${status.eventCount} events, ${status.bufferSize} bytes`);Custom Integration Configuration
Create a custom integration with specific batching and sampling settings:
import {
createSyfraBackendIntegration,
getSyfraBackendIntegration
} from '@syfra3/react-native-monitor';
// Get infrastructure config from initialized SDK
const defaultIntegration = getSyfraBackendIntegration();
// Or create a custom one
const customIntegration = createSyfraBackendIntegration({
infrastructure: {
url: 'https://syfra.co/',
org: 'your-org',
project: 'your-project',
authToken: 'your-auth-token',
},
batchSizeLimit: 100, // Upload when buffer reaches 100 events
batchTimeLimit: 300000, // Upload every 5 minutes
batchVolumeLimit: 5242880, // Upload when buffer reaches 5MB
samplingRate: 0.1, // Sample 10% of normal sessions
enableBatching: true, // Enable automatic batching
});Endpoint Configuration
The integration automatically determines the correct endpoint based on your infrastructure URL:
- Production:
https://syfra.co/api/v1/ingest/mobile - Localhost/Testing:
http://localhost:3000/v1/ingest/mobile
The SDK detects localhost URLs and uses the testing endpoint format automatically.
Event Types
The integration converts performance data into standardized event types:
session_summary- Overall session metrics and healthscreen_render- Screen render performanceuser_interaction- User interactions (button presses, gestures, etc.)navigation_event- Navigation transitionsnetwork_request- Network API callserror- JavaScript errorsfatal_error- Unhandled errorscrash- Application crashes
Testing Connection
Test the connection to your backend:
const integration = getSyfraBackendIntegration();
const isConnected = await integration.testConnection();
if (isConnected) {
console.log('Backend connection successful');
} else {
console.error('Failed to connect to backend');
}API Reference
Hooks
useScreenPerformance({ screenName, enabled? })
Tracks screen render performance. Use this hook in each screen component, or use NavigationTrackingProvider for automatic tracking with React Navigation.
Parameters:
screenName(string, required): Name of the screenenabled(boolean, optional): Enable/disable tracking (default:true)
Example:
useScreenPerformance({ screenName: 'HomeScreen' });useRenderTracking({ componentName, enabled? })
Tracks component re-render performance.
Parameters:
componentName(string, required): Name of the componentenabled(boolean, optional): Enable/disable tracking (default:true)
useInteractionTracking({ enabled? })
Returns interaction tracking functions.
Returns:
trackButtonPress(target: string): Track button presstrackGesture(target: string, duration?: number): Track gesturetrackScroll(target: string): Track scrolltrackTextInput(target: string): Track text input
useNavigationTracking({ screenName, enabled? })
Tracks navigation performance.
Functions
SyfraMonitor.init(config: InitConfig): void
Required: Initialize the SDK with infrastructure configuration. Must be called before using any other SDK features.
Parameters:
config(InitConfig, required): Configuration object with required infrastructure fields and optional monitoring settings
Example:
SyfraMonitor.init({
url: 'https://syfra.co/',
org: 'your-org',
project: 'your-project', // Optional: Auto-detected from app name if not provided
authToken: 'your-auth-token',
});Throws: Error if required fields (url, org, authToken) are missing or if SDK methods are called before initialization.
getPerformanceReport(): Promise<PerformanceReport>
Returns the current performance metrics report.
Throws: Error if SDK is not initialized.
exportPerformanceReport(): Promise<string>
Exports the performance report as JSON string.
Throws: Error if SDK is not initialized.
setUserContext(context: UserContext): void
Set user context (userId, sessionId, region, networkType).
Throws: Error if SDK is not initialized.
getUserContext(): UserContext | undefined
Get current user context.
Throws: Error if SDK is not initialized.
recordError(error: ErrorInfo): Promise<void>
Manually record an error.
Throws: Error if SDK is not initialized.
recordScreenRender(screenName: string, renderTime?: number): void
Manually record a screen render.
Throws: Error if SDK is not initialized.
recordInteraction(type: InteractionType, target: string, duration?: number, responseTime?: number): void
Manually record an interaction.
Throws: Error if SDK is not initialized.
resetPerformanceMetrics(): void
Reset all collected metrics.
Throws: Error if SDK is not initialized.
checkBundleSize(): Promise<BundleSizeCheckResult>
Check bundle size against thresholds.
Throws: Error if SDK is not initialized.
Types
InteractionType (Enum)
BUTTON_PRESSGESTURESCROLLTEXT_INPUT
NetworkType (Enum)
WIFICELLULAR_5GCELLULAR_4GCELLULAR_3GCELLULAR_2GCELLULAR_UNKNOWNOFFLINEUNKNOWN
Performance Report Structure
The performance report includes:
interface PerformanceReport {
timestamp: number;
duration: number;
platform: string;
systemInfo: SystemInfo;
appInfo?: AppInfo;
userContext?: UserContext;
units: ReportUnits;
metrics: {
frameRate: FrameRateMetrics;
memory: MemoryUsage;
cpu: number;
startup?: StartupMetrics;
network?: NetworkMetrics;
stability?: StabilityMetrics;
};
screens: Record<string, ScreenMetrics>;
navigation: NavigationMetrics[];
interactions: InteractionMetrics[];
crashes?: CrashInfo[];
errors?: ErrorInfo[];
networkRequests?: NetworkRequest[];
summary: PerformanceSummary;
health: PerformanceHealth;
warnings: PerformanceWarnings;
}Key Metrics
- Screens: Render times, mount times, render counts per screen
- Interactions: All user interactions with timestamps and response times
- Navigation: Navigation transitions with durations and render times
- Errors: JavaScript errors with stack traces and context
- Stability: Crash count, error count, ANR count, and rates
- Network: Request count, average latency, error rate
- Frame Rate: UI FPS, JS FPS, slow frames, frozen frames
- Memory: Heap usage, native heap, system memory
- CPU: CPU usage percentage
Configuration
Initialization Configuration
The SyfraMonitor.init() function accepts the following configuration:
Required Fields:
url(string): Your infrastructure URL (e.g., 'https://syfra.co/')org(string): Your organization identifierauthToken(string): Authentication token for your infrastructure
Optional Fields:
project(string): Your project identifier. If not provided, will be automatically detected from your app name.
Optional Fields:
Most monitoring features are enabled by default. You only need to specify these if you want to change the defaults:
enableLogs(boolean, default:false): Enable console logging (disabled by default to reduce noise)enableNativeMetrics(boolean, default:true): Enable native metrics collection (FPS, memory, CPU)enableScreenTracking(boolean, default:true): Enable screen tracking (requires manual setup with hooks or NavigationTrackingProvider)enableComponentTracking(boolean, default:true): Enable component render trackingenableInteractionTracking(boolean, default:true): Enable interaction trackingenableNavigationTracking(boolean, default:true): Enable navigation trackingreportFormat('full' | 'simple', default:'full'): Report formatsampleInterval(number, default:1000): Metrics collection interval in millisecondsmaxInteractions(number, default:1000): Maximum number of interactions to storemaxNavigationEvents(number, default:500): Maximum number of navigation events to storewarningThresholds(object): Custom warning thresholds (see below)
Default Configuration
If you don't specify optional fields, these defaults are used:
{
enableNativeMetrics: true,
enableScreenTracking: true,
enableComponentTracking: true,
enableInteractionTracking: true,
enableNavigationTracking: true,
enableLogs: false, // Logs are disabled by default
reportFormat: 'full',
sampleInterval: 1000,
maxInteractions: 1000,
maxNavigationEvents: 500,
}Note: Most monitoring features are enabled by default. Only enableLogs defaults to false to reduce console noise in production.
Warning Thresholds
Default warning thresholds:
{
slowScreenRenderTime: 500, // ms
slowInteractionResponseTime: 100, // ms
lowUIFPS: 60, // fps
lowJSFPS: 60, // fps
highMemoryUsage: 200 * 1024 * 1024, // 200MB
highCPUUsage: 30, // %
networkLatency: 1000, // ms
networkErrorRate: 0.01, // 1%
crashRate: 0.01, // 1%
bundleSize: {
warning: 5 * 1024 * 1024, // 5MB
error: 10 * 1024 * 1024, // 10MB
},
}Troubleshooting
SDK Not Initialized Error
If you see an error like "SyfraMonitor.init() must be called before using the SDK", make sure you've called SyfraMonitor.init() before using any SDK features.
Solution:
// ✅ Correct: Initialize first
import { SyfraMonitor } from '@syfra3/react-native-monitor';
await SyfraMonitor.init({
url: 'https://syfra.co/',
org: 'your-org',
project: 'your-project', // Optional: Auto-detected if not provided
authToken: 'your-auth-token',
});
// Now you can use SDK features
import { getPerformanceReport } from '@syfra3/react-native-monitor';
const report = await getPerformanceReport();Common mistakes:
- ❌ Forgetting to call
init()before using SDK methods - ❌ Missing required fields (url, org, authToken)
- ❌ Calling SDK methods in module-level code before initialization
Initialization Validation Error
If you see "SyfraMonitor.init() requires url, org, and authToken", make sure all required fields are provided:
// ✅ Correct: All required fields provided
await SyfraMonitor.init({
url: 'https://syfra.co/', // Required
org: 'your-org', // Required
project: 'your-project', // Optional: Auto-detected if not provided
authToken: 'your-auth-token', // Required
});
// ❌ Incorrect: Missing required fields
await SyfraMonitor.init({
url: 'https://syfra.co/',
// Missing org, authToken
});Requirements
- React Native >= 0.73.0
- React >= 18.0.0
- iOS >= 11.0
- Android API Level >= 21
Optional Dependencies
Install these packages only if you plan to use the corresponding integrations:
Network Type Detection
npm install @react-native-community/netinfoInfluxDB Integration
npm install @influxdata/influxdb-clientS3 Integration
# Option 1: AWS SDK v2
npm install aws-sdk
# Option 2: AWS SDK v3 (recommended)
npm install @aws-sdk/client-s3The library will work without these dependencies, but the corresponding integrations will not be available.
License
MIT
