Advanced sleep tracking SDK for React Native applications, powered by Asleep's AI technology.
This is an experimental version of the SDK and is not recommended for production use. Please be aware that it may contain bugs and breaking changes.
The Asleep SDK for React Native provides comprehensive sleep tracking capabilities using advanced AI algorithms. It can detect sleep patterns, stages, and provide detailed analytics through audio analysis without requiring any wearable devices.
- Non-invasive Sleep Tracking: Uses device microphone for sleep analysis
- Real-time Monitoring: Live tracking status and progress updates
- Detailed Sleep Reports: Comprehensive sleep analysis and metrics
- Zustand State Management: Singleton pattern for consistent state across your app
- Cross-platform Support: Works on both iOS and Android
- Event-driven Architecture: Real-time callbacks for tracking events
expo install react-native-asleep
- Install the package:
npm install react-native-asleep zustand
- For iOS, run:
npx pod-install
- Ensure you have installed and configured the
expo
package.
- Visit Asleep Dashboard
- Create an account and generate your API key
- Note your API key for configuration
Add the following permissions to your app:
For Expo Managed Projects (app.json):
{
"expo": {
"ios": {
"infoPlist": {
"NSMicrophoneUsageDescription": "This app needs microphone access for sleep tracking",
"UIBackgroundModes": ["audio"]
}
}
}
}
For Bare React Native Projects (ios/YourApp/Info.plist):
<key>NSMicrophoneUsageDescription</key>
<string>This app needs microphone access for sleep tracking</string>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
import React, { useEffect } from "react";
import { useAsleep } from "react-native-asleep";
import { View, Text, Button } from "react-native";
const SleepTracker = () => {
const {
userId,
sessionId,
isTracking,
error,
initAsleepConfig,
startTracking,
stopTracking,
getReport,
enableLog,
} = useAsleep();
useEffect(() => {
const initSDK = async () => {
try {
// Enable debug logging (optional)
enableLog(true);
// Initialize SDK with your API key
await initAsleepConfig({
apiKey: "YOUR_API_KEY",
userId: "optional-user-id", // Optional: SDK generates one if not provided
});
console.log("SDK initialized successfully");
} catch (error) {
console.error("Failed to initialize SDK:", error);
}
};
initSDK();
}, []);
const handleStartTracking = async () => {
try {
await startTracking();
console.log("Sleep tracking started");
} catch (error) {
console.error("Failed to start tracking:", error);
}
};
const handleStopTracking = async () => {
try {
await stopTracking();
console.log("Sleep tracking stopped");
} catch (error) {
console.error("Failed to stop tracking:", error);
}
};
const handleGetReport = async () => {
if (!sessionId) return;
try {
const report = await getReport(sessionId);
console.log("Sleep report:", report);
} catch (error) {
console.error("Failed to get report:", error);
}
};
return (
<View>
<Text>User ID: {userId}</Text>
<Text>Session ID: {sessionId}</Text>
<Text>Status: {isTracking ? "Tracking" : "Not Tracking"}</Text>
<Button
title="Start Tracking"
onPress={handleStartTracking}
disabled={isTracking}
/>
<Button
title="Stop Tracking"
onPress={handleStopTracking}
disabled={!isTracking}
/>
<Button
title="Get Report"
onPress={handleGetReport}
disabled={!sessionId}
/>
</View>
);
};
For use outside React components or for singleton access:
import { AsleepSDK } from "react-native-asleep";
class SleepManager {
async initializeSDK() {
try {
await AsleepSDK.initAsleepConfig({
apiKey: "YOUR_API_KEY",
});
// Initialize event listeners
AsleepSDK.initialize();
console.log("SDK initialized");
} catch (error) {
console.error("SDK initialization failed:", error);
}
}
async startSleepTracking() {
await AsleepSDK.startTracking();
}
async stopSleepTracking() {
return await AsleepSDK.stopTracking();
}
getCurrentStatus() {
return {
isTracking: AsleepSDK.isTracking(),
userId: AsleepSDK.getUserId(),
sessionId: AsleepSDK.getSessionId(),
};
}
}
import { useAsleepStore } from "react-native-asleep";
// Get current state
const currentState = useAsleepStore.getState();
// Subscribe to specific state changes
const unsubscribe = useAsleepStore.subscribe(
(state) => state.isTracking,
(isTracking) => {
console.log("Tracking status changed:", isTracking);
}
);
Returns an object with the following properties and methods:
userId: string | null
- Current user IDsessionId: string | null
- Current session IDisTracking: boolean
- Whether tracking is activeerror: string | null
- Last error messagedidClose: boolean
- Whether the last session was closedlog: string
- Latest log message
initAsleepConfig(config: AsleepConfig): Promise<void>
- Initialize SDKstartTracking(): Promise<void>
- Start sleep trackingstopTracking(): Promise<void>
- Stop sleep trackinggetReport(sessionId: string): Promise<AsleepReport | null>
- Get sleep reportgetReportList(fromDate: string, toDate: string): Promise<AsleepSession[]>
- Get list of reportsenableLog(enabled: boolean): void
- Enable/disable debug loggingsetCustomNotification(title: string, text: string): Promise<void>
- Set custom notification (Android only)
Configuration object for SDK initialization:
interface AsleepConfig {
apiKey: string; // Required: Your API key
userId?: string; // Optional: User identifier
baseUrl?: string; // Optional: Custom API base URL
callbackUrl?: string; // Optional: Webhook callback URL
}
Sleep analysis report structure:
interface AsleepReport {
sessionId: string;
sleepEfficiency: number;
sleepLatency: number;
sleepTime: number;
wakeTime: number;
lightSleepTime: number;
deepSleepTime: number;
remSleepTime: number;
// ... additional metrics
}
Session information structure:
interface AsleepSession {
sessionId: string;
startTime: string;
endTime: string;
state: string;
// ... additional session data
}
The SDK automatically handles events through the zustand store. Events are processed internally and state is updated accordingly. You can monitor state changes using useEffect:
const { userId, sessionId, isTracking, error } = useAsleep();
useEffect(() => {
if (error) {
console.error("SDK Error:", error);
}
}, [error]);
useEffect(() => {
if (sessionId) {
console.log("New session created:", sessionId);
}
}, [sessionId]);
- Initialize the SDK early in your app lifecycle
- Handle initialization errors gracefully
- Store API key securely (use environment variables)
- Request microphone permission before starting tracking
- Provide clear explanation to users about why permission is needed
- Handle permission denial gracefully
- For Android, consider requesting battery optimization exemption
- Implement proper foreground service for long-running tracking
- Always wrap SDK calls in try-catch blocks
- Monitor the error state for real-time error updates
- Provide user-friendly error messages
- Use the built-in zustand store for consistent state
- Subscribe to specific state changes when needed
- Avoid unnecessary re-renders by selecting specific state slices
See the /example
directory for a complete implementation example.
- Permission Denied: Ensure microphone permission is granted
- SDK Not Initialized: Call
initAsleepConfig
before other methods - Network Errors: Check internet connection and API key validity
- Battery Optimization: On Android, exempt app from battery optimization
Enable debug logging to see detailed SDK operations:
const { enableLog } = useAsleep();
enableLog(true);
This project is licensed under the MIT License.
For issues and support: