--- url: /react-native-nitro-device-info/api/device-attestation.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Device Attestation API **Server-verifiable, hardware-backed** device attestation via the opt-in package `react-native-nitro-device-integrity`. Since v0.1.0 The version badges on this page refer to the integrity package. [v0.1.0 on npm](https://www.npmjs.com/package/react-native-nitro-device-integrity/v/0.1.0) corresponds to [this source](https://github.com/l2hyunwoo/react-native-nitro-device-info/tree/react-native-nitro-device-integrity%400.1.0/packages/react-native-nitro-device-integrity). Read the [availability badge definitions](/react-native-nitro-device-info/api/index.md#availability-badges). Its pod targets iOS 14+ and its Android module targets API 24+. Dependencies can require higher minimums. There is no web entry point. - **Android** → [Play Integrity API](https://developer.android.com/google/play/integrity) - **iOS** → [App Attest (`DCAppAttestService`)](https://developer.apple.com/documentation/devicecheck/dcappattestservice) + [DeviceCheck (`DCDevice`)](https://developer.apple.com/documentation/devicecheck/dcdevice) This is a **separate, opt-in package** from the core library. Install it only if you need real attestation; it pulls in Play Integrity / App Attest dependencies and requires Google Cloud / Apple console setup. :::tip Attestation vs. local detection This API **complements** the core [Device Integrity API](/react-native-nitro-device-info/api/device-integrity.md). - **Local detection** ([`isDeviceCompromised()`](/react-native-nitro-device-info/api/device-integrity.md)) — instant, offline, easily bypassed. A first-line pre-filter. - **Attestation** (this page) — platform-issued results that your **server verifies**. Apply your access policy using verified attestation results together with other risk signals for your service. ::: ## The responsibility boundary :::warning This library issues tokens. It does not verify them. Token, attestation, and assertion methods return **opaque** values. These values alone do not establish device trust. Send them to your backend for verification before deciding whether to accept a protected action. ::: | Responsibility | Owner | | -------------------------------------------------------- | ----------------------------------------------- | | Issue token / attestation / assertion on the device | **this library** | | Compute `clientDataHash` (SHA-256), assemble client data | your app | | Send the token to your backend | your app | | Decrypt / verify signature / interpret the verdict | **your server** | | Persist the App Attest `keyId` | your app (the library does not persist `keyId`) | | Google Cloud / Apple console setup | you (developer) | ## Installation ```bash yarn add react-native-nitro-device-integrity react-native-nitro-modules cd ios && pod install ``` The package sets iOS 14.0+ and Android API 24+ as native minimums. Its Nitro and React Native dependencies can raise these minimums. Play Integrity requires Google Play Services. DeviceCheck exists from iOS 11, but this package does not support installing on iOS 11. ## API Reference ```typescript import { createDeviceIntegrity } from 'react-native-nitro-device-integrity'; const integrity = createDeviceIntegrity(); ``` ### Availability #### `isSupported` Since v0.1.0 iOS 14+ Android API 24+ Web: unavailable ```typescript readonly isSupported: boolean ``` Best-effort check. On Android, `true` when Google Play Services is available (does **not** guarantee the Play Integrity API is onboarded for your app). On iOS, `DCAppAttestService.shared.isSupported` — always `false` on the Simulator. #### `providerType` Since v0.1.0 iOS 14+ Android API 24+ Web: unavailable ```typescript readonly providerType: 'playIntegrity' | 'appAttest' | 'unsupported' ``` Which provider backs this device. Branch your client logic on this before calling platform-specific methods. *** ### Android — Play Integrity #### `prepareStandardProvider()` Since v0.1.0 iOS: rejects Android API 24+ Web: unavailable ```typescript prepareStandardProvider(cloudProjectNumber: string): Promise ``` Warms up the Play Integrity **Standard** token provider. Call once per session; the provider is cached natively. `cloudProjectNumber` is passed as a string to avoid JS number-precision loss. Error messages start with `CLOUD_PROJECT_NUMBER_IS_INVALID` for invalid project numbers or `STANDARD_INTEGRITY_ERROR_` for SDK failures. For example, a network failure is `STANDARD_INTEGRITY_ERROR_-3`. On iOS: `UNSUPPORTED_PLATFORM`. #### `requestIntegrityToken()` Since v0.1.0 iOS: rejects Android API 24+ Web: unavailable ```typescript requestIntegrityToken(requestHash: string): Promise ``` Requests a Standard token. Requires a prior `prepareStandardProvider`. If the cached provider has expired (`INTEGRITY_TOKEN_PROVIDER_INVALID`), it is re-prepared once automatically and the request retried. `requestHash` is a base64 SHA-256 of your request's critical parameters (max 500 bytes) — **not** a server nonce; the caller computes it. Returns an opaque, encrypted token string. #### `requestClassicIntegrityToken()` Since v0.1.0 iOS: rejects Android API 24+ Web: unavailable ```typescript requestClassicIntegrityToken(nonce: string, cloudProjectNumber: string): Promise ``` Play Integrity **Classic** flow (one-off, server-nonce based). Prefer Standard for frequent checks. `nonce` must be a server-generated, single-use, URL-safe base64 value of 16–500 bytes. *** ### iOS — App Attest #### `generateKey()` Since v0.1.0 iOS 14+ Android: rejects Web: unavailable ```typescript generateKey(): Promise ``` Generates an App Attest key pair in the Secure Enclave and returns its `keyId`. :::warning Persist the keyId yourself The `keyId` is the only handle to this key — store it (e.g. Keychain). The library does not persist `keyId`. App Attest keys **do not survive app reinstall**; regenerate on `DCError.invalidKey`. ::: #### `attestKey()` Since v0.1.0 iOS 14+ Android: rejects Web: unavailable ```typescript attestKey(keyId: string, clientDataHash: string): Promise ``` Attests a key (**once** per key, per install). Makes a network call to Apple. `clientDataHash` is base64 of `SHA-256(server challenge)` and must decode to exactly **32 bytes**. The library does **not** hash for you. Malformed base64 rejects with `INVALID_BASE64`; any other decoded length rejects with `INVALID_INPUT`, before checking iOS device support. Returns base64 of the opaque CBOR attestation object. #### `generateAssertion()` Since v0.1.0 iOS 14+ Android: rejects Web: unavailable ```typescript generateAssertion(keyId: string, clientDataHash: string): Promise ``` Generates an assertion for a subsequent request (offline). Hash client data that contains a fresh one-time server challenge and the request payload. Pass its 32-byte SHA-256 digest as base64; the same validation as `attestKey` applies. Returns base64 of the opaque CBOR assertion object. Your server checks the issued challenge and monotonic counter to detect replays. *** ### iOS — DeviceCheck #### `getDeviceCheckToken()` Since v0.1.0 iOS 14+ Android: rejects Web: unavailable ```typescript getDeviceCheckToken(): Promise ``` Generates an Apple DeviceCheck token (device-level, lighter than App Attest). Your server queries/updates the device's 2 bits of state via Apple's DeviceCheck API. ## Errors Rejections include a code prefix in `Error.message`; there is no separate JavaScript `error.code` contract. | Message prefix | Meaning | | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `UNSUPPORTED_PLATFORM` | Platform-specific method called on the wrong platform, or unavailable iOS hardware. | | `CLOUD_PROJECT_NUMBER_IS_INVALID` | Project number is not a positive signed 64-bit integer string. | | `PROVIDER_NOT_PREPARED` | Call `prepareStandardProvider` before requesting a Standard token. | | `STANDARD_INTEGRITY_ERROR_` | Standard SDK failure. Provider invalidation (`-19`) is refreshed and retried once; other failures are returned directly. | | `CLASSIC_INTEGRITY_ERROR_` | Classic SDK failure; no automatic retry. | | `INVALID_BASE64` | iOS `clientDataHash` is not valid base64. | | `INVALID_INPUT` | iOS hash does not decode to 32 bytes, or Apple reports invalid input. | | `INVALID_KEY`, `SERVER_UNAVAILABLE`, `FEATURE_UNSUPPORTED`, `UNKNOWN_SYSTEM_FAILURE`, `UNKNOWN` | Mapped Apple DeviceCheck / App Attest failures. Other native errors retain their native message. | Numeric SDK codes are preserved, rather than translated to symbolic names such as `NETWORK_ERROR`. See the [Standard SDK error codes](https://developer.android.com/google/play/integrity/reference/com/google/android/play/core/integrity/model/StandardIntegrityErrorCode). Handle the rejection without treating it as a trusted verdict. ## Usage ```typescript import { createDeviceIntegrity } from 'react-native-nitro-device-integrity'; const integrity = createDeviceIntegrity(); if (integrity.providerType === 'playIntegrity') { // Android await integrity.prepareStandardProvider('123456789012'); // once const requestHash = base64Sha256('checkout:item-42'); // your request params const token = await integrity.requestIntegrityToken(requestHash); await postToYourServer({ token }); // server verifies } else if (integrity.providerType === 'appAttest') { // iOS const keyId = await integrity.generateKey(); // persist this const clientDataHash = base64Sha256(serverChallenge); const attestation = await integrity.attestKey(keyId, clientDataHash); // once await postToYourServer({ keyId, attestation }); // one-time validation // ...per request: const challenge = await fetchChallengeFromYourServer(); // fresh, one-time const clientData = JSON.stringify({ challenge, payload }); const assertion = await integrity.generateAssertion(keyId, base64Sha256(clientData)); await postToYourServer({ keyId, assertion, clientData }); } ``` The example assumes your app supplies the hashing and backend helpers. Send the exact `clientData` string you hashed so the server can verify the same bytes and compare its embedded challenge with the one it issued for that request. ## Server verification (your responsibility) This library stops at issuing the token. Your backend verifies it. ### Play Integrity (Android) Send the token to your server, then call Google's decode endpoint (recommended): ```http POST https://playintegrity.googleapis.com/v1/{packageName}:decodeIntegrityToken ``` Before checking verdicts, validate `requestDetails`: the expected `requestPackageName`, a recent `timestampMillis`, and the `requestHash` computed from the protected request (Standard) or the unused server-issued `nonce` (Classic). Reject mismatches and expired requests on your backend. Then apply your policy to the decoded verdict: - `deviceIntegrity.deviceRecognitionVerdict` containing `MEETS_DEVICE_INTEGRITY` - `appIntegrity.appRecognitionVerdict === 'PLAY_RECOGNIZED'` - An empty or absent `deviceRecognitionVerdict` means the device meets none of the verdict criteria. Possible causes include API hooking, system compromise, or an emulator that fails Google's integrity checks. See [Play Integrity verdicts](https://developer.android.com/google/play/integrity/verdicts). ### App Attest (iOS) 1. Validate the **attestation** once per key against Apple's App Attest Root CA (cert chain, nonce, app-ID hash, counter = 0). Store the public key + counter. 2. For each **assertion**, hash the exact client data received and verify the signature with the stored public key. Check that its challenge matches an unused server-issued value and that the counter strictly increased. See [Validating apps that connect to your server](https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server). ## Setup requirements ### Android (Play Integrity) 1. Create/select a **Google Cloud** project and enable the Play Integrity API. 2. Link it in **Play Console** → _Play Integrity API_. 3. Pass that **Cloud project number** to `prepareStandardProvider` / `requestClassicIntegrityToken`. 4. On your server, set up the Google service account (or response-encryption keys). ### iOS (App Attest / DeviceCheck) 1. Add the **App Attest** capability to your app target (Xcode → Signing & Capabilities), which adds the `com.apple.developer.devicecheck.appattest-environment` entitlement. 2. Use a **bundle identifier you own** and set your Development Team. 3. For DeviceCheck server queries, create a DeviceCheck `.p8` key in the Apple Developer portal. :::info The library configures none of this All of the above lives in your developer accounts and app target. The library cannot set it up — it only issues tokens once your app is configured. ::: ## Limitations :::warning Attestation limits - **App Attest is not a jailbreak detector.** It proves a genuine, unmodified app on genuine Apple hardware — use it as a _positive_ signal. - **Availability is separate from the verdict.** `isSupported` is `false` on the iOS Simulator. Google Play Services availability on Android does not guarantee token issuance or any integrity verdict. Check the [Play Integrity verdicts](https://developer.android.com/google/play/integrity/verdicts) on your server. - **Bypasses exist** (e.g. PlayIntegrityFix). Attestation is one signal in a broader anti-abuse strategy, not an absolute guarantee. - **Network + console configuration required.** Without them, token issuance rejects — handle the rejection; don't treat it as "safe". - **App Attest throttling**: Apple rate-limits `attestKey`. Control call frequency in your app; the library adds no automatic retries or timers for App Attest calls. ::: --- url: /react-native-nitro-device-info/api/device-info.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # DeviceInfo Module Complete API documentation for the DeviceInfo module. Read the [availability badge definitions](/react-native-nitro-device-info/api/index.md#availability-badges) before choosing an API. The native build minimums are iOS 15.1 and Android API 24. Dependencies can require higher minimums. Web entry points and fallbacks were added in v1.8.0. ## Import ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; ``` *** ## Core Device Information (9 APIs) Synchronous properties providing instant access to basic device identity. ### `deviceId: string` Since v0.1.0 iOS 15.1+ Android API 24+ Web: fallback Device model identifier. ```typescript const deviceId = DeviceInfoModule.deviceId; // iOS: "iPhone14,2" // Android: "SM-G998B" ``` ### `brand: string` Since v0.1.0 iOS 15.1+ Android API 24+ Web: limited Device brand/manufacturer name. ```typescript const brand = DeviceInfoModule.brand; // iOS: "Apple" // Android: "Samsung", "Google", "OnePlus", etc. ``` ### `model: string` Since v0.1.0 iOS 15.1+ Android API 24+ Web: fallback Device model marketing name. Maps the hardware identifier to a human-readable name, falling back to a generic name for unknown devices. ```typescript const model = DeviceInfoModule.model; // iOS: "iPhone 18 Pro", "iPhone Duo", "iPad Pro 11-inch (M5)" // Android: Device-specific model name (e.g., "Pixel 7 Pro", "Galaxy S24") ``` ### `systemName: string` Since v0.1.0 iOS 15.1+ Android API 24+ Web: limited Operating system name. ```typescript const systemName = DeviceInfoModule.systemName; // iOS: "iOS" or "iPadOS" // Android: "Android" ``` ### `systemVersion: string` Since v0.1.0 iOS 15.1+ Android API 24+ Web: fallback Operating system version string. ```typescript const systemVersion = DeviceInfoModule.systemVersion; // iOS: "15.0", "16.2.1" // Android: "12", "13", "14" ``` ### `deviceType: DeviceType` Since v0.1.0 iOS 15.1+ Android API 24+ Web: fallback Device type category. ```typescript const deviceType = DeviceInfoModule.deviceType; // "Handset" | "Tablet" | "Tv" | "Desktop" | "GamingConsole" | "unknown" ``` ### `uniqueId: string` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get unique device identifier. ```typescript const uniqueId = DeviceInfoModule.uniqueId; // iOS: IDFV (Identifier for Vendor) // Android: ANDROID_ID // Example: "FCDBD8EF-62FC-4ECB-B2F5-92C9E79AC7F9" ``` - **iOS**: Reads the current IDFV, or `""` when unavailable. Do not assume that it survives removal of all apps from the vendor. - **Android**: Reads ANDROID_ID, or `""` when unavailable. Its scope and reset behavior depend on Android. Do not use this value as a permanent device identity or account identifier. See [Apple IDFV](https://developer.apple.com/documentation/uikit/uidevice/identifierforvendor) and [Android ANDROID_ID](https://developer.android.com/reference/android/provider/Settings.Secure#ANDROID_ID). ### `manufacturer: string` Since v1.2.0 iOS 15.1+ Android API 24+ Web: limited Get device manufacturer name. ```typescript const manufacturer = DeviceInfoModule.manufacturer; // iOS: "Apple" // Android: "Samsung", "Google", "Xiaomi", etc. ``` ### `deviceName: string` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get user-assigned device name. ```typescript const deviceName = DeviceInfoModule.deviceName; // Example: "John's iPhone", "My Galaxy S21" ``` *** ## Device Capabilities (7 APIs) Boolean checks for device features and hardware availability. ### `isTablet: boolean` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Check if device is a tablet. ```typescript const isTablet = DeviceInfoModule.isTablet; // iPad → true // iPhone → false ``` - **iOS**: Based on UIDevice.userInterfaceIdiom - **Android**: Based on smallest screen width >= 600dp ### `isEmulator: boolean` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Check if running in simulator/emulator. ```typescript const isEmulator = DeviceInfoModule.isEmulator; ``` ### `deviceYearClass: number` Since v1.4.2 iOS 15.1+ Android API 24+ Web: fallback Get estimated device year class based on hardware specifications. ```typescript const yearClass = DeviceInfoModule.deviceYearClass; if (yearClass >= 2020) { enableHighEndFeatures(); } else if (yearClass >= 2015) { enableStandardFeatures(); } else { enableLowEndFeatures(); } ``` Returns an estimated "year class" representing when this device's hardware would have been considered flagship/high-end. Based on extended Facebook device-year-class algorithm updated for 2025. **RAM → Year Class mapping**: | RAM | Year Class | Example Devices | | ------ | ---------- | ------------------- | | ≤2 GB | 2013 | Budget devices | | ≤4 GB | 2015 | Mid-range 2015-2016 | | ≤6 GB | 2017 | Flagship 2017-2018 | | ≤8 GB | 2019 | Flagship 2019-2020 | | ≤12 GB | 2021 | Flagship 2021-2022 | | ≤16 GB | 2023 | Flagship 2023-2024 | | >16 GB | 2025 | Latest flagships | ### `isCameraPresent: boolean` Since v1.2.0 iOS 15.1+ (since v1.9.0) Android API 24+ Web: fallback The iOS implementation is available from v1.9.0. Published versions through v1.8.3 return `true` unconditionally. See the [implementation change](https://github.com/l2hyunwoo/react-native-nitro-device-info/commit/be976f0). Check if camera hardware is available. On iOS, returns `false` on the simulator or when no video capture device exists. This check does not request camera permission; a `true` result does not mean the app has permission to capture video. ```typescript const hasCamera = DeviceInfoModule.isCameraPresent; ``` ### `isPinOrFingerprintSet: boolean` Since v1.2.0 iOS 15.1+ (since v1.9.0) Android API 24+ Web: fallback The iOS implementation is available from v1.9.0. Published versions through v1.8.3 return `false` unconditionally. See the [implementation change](https://github.com/l2hyunwoo/react-native-nitro-device-info/commit/801903e). Check if PIN, fingerprint, or Face ID is configured. On iOS, checks whether device-owner authentication is available, including the device passcode fallback when biometrics are unavailable or locked out. Returns `false` when no passcode is set. This check does not authenticate the user or show a prompt; the result is checked again on each read. ```typescript const isSecure = DeviceInfoModule.isPinOrFingerprintSet; ``` ### `isHardwareKeyStoreAvailable: boolean` Since v1.2.1 iOS 15.1+ Android API 24+: limited Web: fallback Check platform key-storage availability. Android does not verify hardware backing. ```typescript const hasHardwareKeyStore = DeviceInfoModule.isHardwareKeyStoreAvailable; if (hasHardwareKeyStore) { console.log('Platform key-storage check passed'); // Apply your key-storage policy; this check alone is not a security guarantee. } else { console.log('Platform key storage unavailable'); // Use alternative security measures } ``` **Platform limits**: iOS checks Secure Enclave availability. Android only checks whether `AndroidKeyStore` can be opened; it does not prove that a key is hardware-backed. ### `isLowRamDevice: boolean` Since v1.2.0 iOS: fallback Android API 24+ Web: fallback Check if device is classified as low RAM device. ```typescript const isLowRam = DeviceInfoModule.isLowRamDevice; // Android API 19+: true/false // iOS: false ``` **Platform**: Android. The OS classification API exists from API 19, but this package requires API 24+. *** ## Display & Screen (7 APIs) Screen and display-related properties. ### `getHasNotch(): boolean` Since v1.3.0 iOS 15.1+ Android: fallback Web: fallback Check if device has a display notch. ```typescript const hasNotch = DeviceInfoModule.getHasNotch(); // iPhone X, 11, 12, 13 → true // iPhone SE, 8 → false ``` - **iOS only** - Detects iPhone X and later models - **Android**: Always returns `false` ### `getHasDynamicIsland(): boolean` Since v1.3.0 iOS 16+ Android: fallback Web: fallback Check if device has Dynamic Island. ```typescript const hasDynamicIsland = DeviceInfoModule.getHasDynamicIsland(); // iPhone 14 Pro, 15 Pro → true // iPhone 14, 13 → false ``` - **iOS 16+ only** - iPhone 14 Pro and later - **Android**: Always returns `false` ### `isDisplayZoomed: boolean` Since v1.2.0 iOS 15.1+ Android: fallback Web: fallback Check if iOS Display Zoom is enabled. ```typescript const isZoomed = DeviceInfoModule.isDisplayZoomed; // iOS: true/false based on display zoom setting // Android: false ``` **Platform**: iOS only ### `getIsLandscape(): boolean` Since v1.3.0 iOS 15.1+ Android API 24+ Web: limited Check if device is in landscape orientation. ```typescript const isLandscape = DeviceInfoModule.getIsLandscape(); ``` ### `getBrightness(): number` Since v1.1.0 iOS 15.1+ Android: fallback Web: fallback Get current screen brightness level (0.0 to 1.0). ```typescript const brightness = DeviceInfoModule.getBrightness(); console.log(`Brightness: ${(brightness * 100).toFixed(0)}%`); // iOS: 0.0 to 1.0 // Android: -1 ``` **Platform**: iOS only ### `getFontScale(): number` Since v1.1.0 iOS 15.1+ Android API 24+ Web: fallback Get current font scale multiplier. ```typescript const fontScale = DeviceInfoModule.getFontScale(); // Example: 1.0 (normal), 1.2 (large), 0.85 (small) ``` ### `isLiquidGlassAvailable: boolean` Since v1.2.1 iOS 26+ Android: fallback Web: fallback Check if the liquid glass effect is available on the device. ```typescript const hasLiquidGlass = DeviceInfoModule.isLiquidGlassAvailable; if (hasLiquidGlass) { console.log('Liquid glass effect available'); // Can use new iOS 26+ design features } else { console.log('Liquid glass not available'); // Fallback to standard UI } ``` **Platform**: iOS 26.0+ Requires a Swift 6.2+ compiler. Returns `false` on older compiler builds or when `UIDesignRequiresCompatibility` is enabled. *** ## System Resources (7 APIs) Memory, storage, and uptime information. ### `totalMemory: number` Since v1.2.0 iOS 15.1+ Android API 24+ Web: limited Get total device RAM in bytes. ```typescript const totalMemory = DeviceInfoModule.totalMemory; // Example: 6442450944 (6 GB) console.log(`Total RAM: ${(totalMemory / 1024 / 1024 / 1024).toFixed(1)}GB`); ``` ### `getUsedMemory(): number` Since v0.1.0 iOS 15.1+ Android API 24+ Web: fallback Get current app memory usage in bytes. On iOS this is `phys_footprint`, the value jetsam and Xcode's memory gauge use. ```typescript const usedMemory = DeviceInfoModule.getUsedMemory(); // Example: 134217728 (128 MB) console.log(`Used Memory: ${(usedMemory / 1024 / 1024).toFixed(0)}MB`); ``` ### `maxMemory: number` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get maximum memory available to app (in bytes). ```typescript const maxMemory = DeviceInfoModule.maxMemory; // Android: max Java heap size // iOS: memory limit before jetsam terminates the app // (getUsedMemory() + os_proc_available_memory()) ``` On iOS, `maxMemory` is `-1` when `os_proc_available_memory()` returns 0: no limit applies (e.g. the Simulator) or the app has already exceeded its limit. On Android, `maxMemory` and `getUsedMemory()` are not comparable: `maxMemory` is the Java heap limit, while `getUsedMemory()` is the PSS of the whole process, including native memory. `getUsedMemory() / maxMemory` is only meaningful on iOS. ### `totalDiskCapacity: number` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get total internal storage size in bytes. ```typescript const totalDisk = DeviceInfoModule.totalDiskCapacity; // Example: 128849018880 (120 GB) console.log(`Total Storage: ${(totalDisk / 1024 / 1024 / 1024).toFixed(0)}GB`); ``` ### `getFreeDiskStorage(): number` Since v0.1.0 iOS 15.1+ Android API 24+ Web: fallback Get available free storage space in bytes. ```typescript const freeDisk = DeviceInfoModule.getFreeDiskStorage(); // Example: 51539607552 (48 GB) console.log(`Free Storage: ${(freeDisk / 1024 / 1024 / 1024).toFixed(1)}GB`); ``` ### `getUptime(): number` Since v1.4.2 iOS 15.1+ Android API 24+ Web: fallback Get device uptime since boot in milliseconds, excluding deep sleep time. On iOS, use this clock only for app-event timing: elapsed time or timers (`35F9.1`), or app-event uptime converted into an absolute timestamp using `startupTime` (`8FFB.1`). Do not display or collect raw uptime as general device information, send it off-device, or use it for fingerprinting. Only elapsed time between app events or the resulting absolute app-event timestamps may be sent off-device. ```typescript const startedAt = DeviceInfoModule.getUptime(); const usedMemory = DeviceInfoModule.getUsedMemory(); const elapsedMs = DeviceInfoModule.getUptime() - startedAt; console.log({ usedMemory, elapsedMs }); ``` **Platform behavior**: - **iOS**: Uses `systemUptime` (excludes deep sleep) - **Android**: Uses `uptimeMillis()` (excludes deep sleep) Both platforms return consistent "active time" since boot, matching the behavior of `expo-device.getUptimeAsync()`. ### `startupTime: number` Since v1.1.0 iOS 15.1+ Android API 24+ Web: fallback Get device boot time (milliseconds since epoch). On iOS, use this value only as the time base for converting app-event uptime into an absolute timestamp (`8FFB.1`). Do not display or collect the raw boot timestamp as general device information, send it off-device, or use it for fingerprinting. Only the resulting absolute timestamps of events within the app may be sent off-device. ```typescript // iOS: capture an event occurring in the app using the same uptime clock. const eventUptime = DeviceInfoModule.getUptime(); const eventTimestamp = DeviceInfoModule.startupTime + eventUptime; console.log(`App event at: ${new Date(eventTimestamp).toISOString()}`); ``` This is the device boot time, not app startup time. See [iOS Privacy Manifest](/react-native-nitro-device-info/guide/getting-started.md#ios-privacy-manifest) for the supported purposes and Apple's usage limits. *** ## Battery & Power (4 APIs) Battery and power state information. ### `getBatteryLevel(): number` Since v0.1.0 iOS 15.1+ Android API 24+ Web: limited Get current battery level (0.0 to 1.0), or `-1` if unavailable. A known empty battery returns `0`. On web, battery getters read the live BatteryManager after the initial async request resolves. Before resolution, or if the API is unavailable or denied, level is `-1`, charging is `false`, battery state is `"unknown"`, and `isLowBatteryLevel()` returns `false`. ```typescript const batteryLevel = DeviceInfoModule.getBatteryLevel(); console.log(batteryLevel < 0 ? 'Battery: unavailable' : `Battery: ${(batteryLevel * 100).toFixed(0)}%`); // Output: "Battery: 75%" ``` ### `getPowerState(): PowerState` Since v0.1.0 iOS 15.1+ Android API 24+: limited Web: limited On Android, `lowPowerMode` is always `false`. Battery level and charging state are implemented. Get comprehensive power state information. ```typescript const powerState = DeviceInfoModule.getPowerState(); console.log(powerState.batteryLevel < 0 ? 'Battery: unavailable' : `Battery: ${(powerState.batteryLevel * 100).toFixed(0)}%`); console.log(`Status: ${powerState.batteryState}`); console.log(`Low Power Mode: ${powerState.lowPowerMode}`); // iOS only ``` **PowerState** interface: ```typescript interface PowerState { batteryLevel: number; // 0.0 to 1.0, or -1 if unavailable batteryState: BatteryState; // 'unknown' | 'unplugged' | 'charging' | 'full' lowPowerMode: boolean; // iOS only } ``` ### `getIsBatteryCharging(): boolean` Since v1.3.0 iOS 15.1+ Android API 24+ Web: limited Check if battery is currently charging. ```typescript const isCharging = DeviceInfoModule.getIsBatteryCharging(); ``` ### `isLowBatteryLevel(threshold: number): boolean` Since v1.1.0 iOS 15.1+ Android API 24+ Web: limited Check if a valid battery level is below threshold. Returns `false` for an unavailable reading; a known `0%` reading still counts as low. ```typescript const isLowBattery = DeviceInfoModule.isLowBatteryLevel(0.2); // 20% if (isLowBattery) { console.log('Battery is low, please charge'); } ``` *** ## Application Metadata (9 APIs) App bundle and version information. ### `version: string` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get application version string. ```typescript const version = DeviceInfoModule.version; // Example: "1.2.3" ``` ### `buildNumber: string` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get application build number. ```typescript const buildNumber = DeviceInfoModule.buildNumber; // Example: "42" or "20231025" ``` ### `bundleId: string` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get bundle ID (iOS) or package name (Android). ```typescript const bundleId = DeviceInfoModule.bundleId; // Example: "com.company.app" ``` ### `applicationName: string` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get application display name. ```typescript const appName = DeviceInfoModule.applicationName; // Example: "My Awesome App" ``` ### `readableVersion: string` Since v1.1.0 iOS 15.1+ Android API 24+ Web: fallback Get human-readable version string (version.buildNumber). ```typescript const readableVersion = DeviceInfoModule.readableVersion; // Example: "1.2.3.42" ``` ### `getFirstInstallTime(): Promise` Since v0.1.0 iOS 15.1+: limited Android API 24+ Web: fallback On iOS, this estimates installation time from the Documents directory creation time. It returns `0` when unavailable. Get timestamp when app was first installed (ms since epoch). ```typescript const installTime = await DeviceInfoModule.getFirstInstallTime(); const installDate = new Date(installTime); console.log(`Installed: ${installDate.toLocaleDateString()}`); ``` ### `getLastUpdateTime(): Promise` Since v0.1.0 iOS 15.1+: limited Android API 24+ Web: fallback Get timestamp of most recent app update (ms since epoch). ```typescript const updateTime = await DeviceInfoModule.getLastUpdateTime(); const updateDate = new Date(updateTime); console.log(`Last Updated: ${updateDate.toLocaleDateString()}`); ``` **iOS limitation**: Reads the Documents directory modification time, not an App Store update timestamp. Returns `0` if unavailable. ### `firstInstallTimeSync: number` Since v1.1.0 iOS 15.1+: limited Android API 24+ Web: fallback On iOS, this caches the Documents directory creation time on first access. It returns `0` when unavailable. Synchronous version of `getFirstInstallTime()`. ```typescript const firstInstallTimeSync = DeviceInfoModule.firstInstallTimeSync; ``` ### `lastUpdateTimeSync: number` Since v1.1.0 iOS: fallback Android API 24+ Web: fallback Synchronous variant (returns -1 on iOS). ```typescript const lastUpdateTimeSync = DeviceInfoModule.lastUpdateTimeSync; ``` *** ## Network (6 APIs) Network connectivity APIs (excluding carrier). ### `getIpAddress(): Promise` Since v0.1.0 iOS 15.1+ Android API 24+ Web: fallback Get device local IP address. ```typescript const ipAddress = await DeviceInfoModule.getIpAddress(); // Example: "192.168.1.100", "10.0.0.5" ``` ### `getIpAddressSync(): string` Since v1.3.0 iOS 15.1+ Android API 24+ Web: fallback Synchronous variant (with 5-second cache). ```typescript const ipAddressSync = DeviceInfoModule.getIpAddressSync(); ``` ### `getMacAddress(): Promise` Since v0.1.0 iOS: fallback Android API 24+ Web: fallback Get the Wi-Fi MAC address when Android allows access. Android uses the same 5-second cache as `getMacAddressSync()` and returns `"unknown"` when the address is unavailable. [Non-system apps generally cannot access hardware MAC addresses](https://developer.android.com/reference/java/net/NetworkInterface#getHardwareAddress\(\)) on modern Android; this API does not bypass those restrictions. ```typescript const macAddress = await DeviceInfoModule.getMacAddress(); // iOS: "02:00:00:00:00:00" (hardcoded since iOS 7 for privacy) // Android: "unknown" when restricted, otherwise the available wlan0 MAC ``` ### `getMacAddressSync(): string` Since v1.3.0 iOS: fallback Android API 24+ Web: fallback Synchronous variant, sharing the same Android lookup, 5-second cache, and `"unknown"` fallback. ```typescript const macAddressSync = DeviceInfoModule.getMacAddressSync(); ``` ### `getUserAgent(): Promise` Since v1.1.0 iOS 15.1+ Android API 24+ Web: limited Get HTTP User-Agent string. ```typescript const userAgent = await DeviceInfoModule.getUserAgent(); // Example: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) ..." ``` iOS initializes a WebView and caches the first successful result. Android queries `WebSettings` asynchronously. Both platforms return a `Promise`. ### `getIsAirplaneMode(): boolean` Since v1.3.0 iOS: fallback Android API 24+ Web: fallback Check if airplane mode is enabled. On web this always returns `false`: browsers cannot determine airplane mode. Being offline does not establish that airplane mode is enabled. ```typescript const isAirplaneMode = DeviceInfoModule.getIsAirplaneMode(); // Android: true/false // iOS and web: false (not available) ``` **Platform**: Android only *** ## Carrier Information (7 APIs) Cellular carrier data for telecom apps, analytics, and geo-detection. ### `getCarrier(): Promise` Since v0.1.0 iOS 15.1+ (since v1.8.0) Android API 24+ Web: fallback iOS has a functional implementation from v1.8.0. Earlier async versions return a fixed fallback, even when a synchronous counterpart is implemented. See the [iOS implementation change](https://github.com/l2hyunwoo/react-native-nitro-device-info/commit/cb6eb026). Get cellular carrier name. ```typescript const carrier = await DeviceInfoModule.getCarrier(); // Example: "Verizon", "AT&T", "T-Mobile" ``` ### `getCarrierSync(): string` Since v1.3.0 iOS 15.1+ Android API 24+ Web: fallback Synchronous variant (with 5-second cache). ```typescript const carrierSync = DeviceInfoModule.getCarrierSync(); ``` ### `carrierAllowsVOIP: boolean` Since v1.5.0 iOS 15.1+ Android: fallback Web: fallback Check if carrier allows VoIP calls on its network. ```typescript const allowsVOIP = DeviceInfoModule.carrierAllowsVOIP; // iOS: true/false based on carrier policy // Android: always true (no equivalent API) ``` **Platform**: iOS only (always returns `true` on Android) ### `carrierIsoCountryCode: string` Since v1.5.0 iOS 15.1+ Android API 24+ Web: fallback Get ISO 3166-1 alpha-2 country code for the carrier. ```typescript const countryCode = DeviceInfoModule.carrierIsoCountryCode; // Example: "US", "KR", "JP", "DE" // Returns "" if no SIM card ``` ### `mobileCountryCode: string` Since v1.5.0 iOS 15.1+ Android API 24+ Web: fallback Get Mobile Country Code (MCC) per ITU-T Recommendation E.212. ```typescript const mcc = DeviceInfoModule.mobileCountryCode; // Example: "310" (USA), "450" (Korea), "440" (Japan) // Returns "" if no carrier ``` **Common MCC values**: | Country | MCC | | ------- | ------- | | USA | 310-316 | | Korea | 450 | | Japan | 440-441 | | China | 460 | | Germany | 262 | ### `mobileNetworkCode: string` Since v1.5.0 iOS 15.1+ Android API 24+ Web: fallback Get Mobile Network Code (MNC) that identifies the carrier within a country. ```typescript const mnc = DeviceInfoModule.mobileNetworkCode; // Example: "260" (T-Mobile US), "05" (SKT Korea) // Returns "" if no carrier ``` ### `mobileNetworkOperator: string` Since v1.5.0 iOS 15.1+ Android API 24+ Web: fallback Get combined MCC + MNC string. ```typescript const operator = DeviceInfoModule.mobileNetworkOperator; // Example: "310260" (T-Mobile US), "45005" (SKT Korea) // Equivalent to: mobileCountryCode + mobileNetworkCode // Returns "" if no carrier ``` **Use cases**: - Carrier-specific feature toggling - Regional content delivery - Telecom analytics - Fraud detection (geo-location verification) *** ## Audio Accessories (4 APIs) Audio device detection. ### `isHeadphonesConnected(): Promise` Since v0.1.0 iOS 15.1+ (since v1.8.0) Android API 24+ Web: fallback iOS has a functional implementation from v1.8.0. Earlier async versions return a fixed fallback, even when a synchronous counterpart is implemented. See the [iOS implementation change](https://github.com/l2hyunwoo/react-native-nitro-device-info/commit/cb6eb026). Check if headphones are connected (wired or Bluetooth). On Android, this uses the same output-device detection as the synchronous getter. ```typescript const hasHeadphones = await DeviceInfoModule.isHeadphonesConnected(); ``` ### `getIsHeadphonesConnected(): boolean` Since v1.3.0 iOS 15.1+ Android API 24+ Web: fallback Synchronous variant. ```typescript const isHeadphonesConnected = DeviceInfoModule.getIsHeadphonesConnected(); ``` ### `getIsWiredHeadphonesConnected(): boolean` Since v1.3.0 iOS 15.1+ Android API 24+ Web: fallback Check if wired headphones are connected. On Android, this includes wired headphones/headsets and [USB headsets on API 26+](https://developer.android.com/reference/android/media/AudioDeviceInfo#TYPE_USB_HEADSET). Built-in speakers and Bluetooth devices do not count as wired headphones. ```typescript const hasWiredHeadphones = DeviceInfoModule.getIsWiredHeadphonesConnected(); ``` ### `getIsBluetoothHeadphonesConnected(): boolean` Since v1.3.0 iOS 15.1+ Android API 24+ Web: fallback Check if Bluetooth headphones are connected. ```typescript const hasBluetoothHeadphones = DeviceInfoModule.getIsBluetoothHeadphonesConnected(); ``` *** ## Location Services (3 APIs) Location provider information. ### `isLocationEnabled(): Promise` Since v0.1.0 iOS 15.1+ (since v1.8.0) Android API 24+ Web: fallback iOS has a functional implementation from v1.8.0. Earlier async versions return a fixed fallback, even when a synchronous counterpart is implemented. See the [iOS implementation change](https://github.com/l2hyunwoo/react-native-nitro-device-info/commit/cb6eb026). Check if location services are enabled. ```typescript const isLocationEnabled = await DeviceInfoModule.isLocationEnabled(); ``` ### `getIsLocationEnabled(): boolean` Since v1.3.0 iOS 15.1+ Android API 24+ Web: fallback Synchronous variant. ```typescript const isLocationEnabled = DeviceInfoModule.getIsLocationEnabled(); ``` ### `getAvailableLocationProviders(): string[]` Since v1.1.0 iOS 15.1+ Android API 24+ Web: fallback Get list of enabled location providers. ```typescript const providers = DeviceInfoModule.getAvailableLocationProviders(); // ["gps", "network"] ``` *** ## Localization (1 API) Language and regional settings. ### `systemLanguage: string` Since v1.3.0 iOS 15.1+ Android API 24+ Web: limited Get device system language in BCP 47 format. ```typescript const language = DeviceInfoModule.systemLanguage; // iOS: "en-US", "ko-KR", "ja-JP", "zh-Hans-CN" // Android: "en-US", "ko-KR", "ja-JP", "zh-Hans-CN" ``` **Examples**: | Language | Code | | ------------------ | ------------ | | English (US) | `en-US` | | Korean | `ko-KR` | | Japanese | `ja-JP` | | Simplified Chinese | `zh-Hans-CN` | | French (France) | `fr-FR` | | German | `de-DE` | **Use Case**: ```typescript const language = DeviceInfoModule.systemLanguage; if (language.startsWith('ko')) { console.log('Korean device detected'); } else if (language.startsWith('ja')) { console.log('Japanese device detected'); } ``` *** ## CPU & Architecture (3 APIs) Processor and ABI information. ### `supportedAbis: string[]` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get supported CPU architectures. ```typescript const abis = DeviceInfoModule.supportedAbis; // iOS: ["arm64"] // Android: ["arm64-v8a", "armeabi-v7a"] ``` ### `supported32BitAbis: string[]` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get list of supported 32-bit ABIs. ```typescript const abis32 = DeviceInfoModule.supported32BitAbis; // iOS: [] // Android API 21+: ["armeabi-v7a", "x86"] ``` **Platform**: Android API 21+, returns `[]` on iOS ### `supported64BitAbis: string[]` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get list of supported 64-bit ABIs. ```typescript const abis64 = DeviceInfoModule.supported64BitAbis; // iOS: ["arm64"] // Android API 21+: ["arm64-v8a", "x86_64"] ``` *** ## Android Platform (20+ APIs) Android-specific APIs and build information. ### `apiLevel: number` Since v1.2.0 iOS: fallback Android API 24+ Web: fallback Get Android API level. ```typescript const apiLevel = DeviceInfoModule.apiLevel; // Android 12 → 31 // Android 13 → 33 // iOS → -1 ``` **Platform**: Android only ### `navigationMode: NavigationMode` Since v1.3.0 iOS: fallback Android API 24+ Web: fallback Get Android navigation mode. ```typescript const navMode = DeviceInfoModule.navigationMode; // Android with gesture nav → "gesture" // Android with 3-button nav → "buttons" // Android with 2-button nav → "twobuttons" // iOS → "unknown" ``` **Type**: `'gesture' | 'buttons' | 'twobuttons' | 'unknown'` **Platform**: Android only (returns "unknown" on iOS) **Values**: | Value | Description | | ------------ | ---------------------------------------------------- | | `gesture` | Full gesture navigation (swipe-based) | | `buttons` | Traditional 3-button navigation (Back, Home, Recent) | | `twobuttons` | 2-button navigation (Back, Home with swipe up) | | `unknown` | Cannot determine (always on iOS) | **Use Case**: ```typescript const navMode = DeviceInfoModule.navigationMode; if (navMode === 'gesture') { // Avoid bottom gesture conflicts // Add extra bottom padding for bottom sheets console.log('Using gesture navigation - add extra padding'); } else if (navMode === 'buttons') { // Traditional navigation bar is present console.log('Using button navigation'); } ``` **Note**: Navigation mode detection requires Android 10 (API 29) or later. On older Android versions, returns `"buttons"` since gesture navigation was not available. ### `getHasGms(): boolean` Since v1.3.0 iOS: fallback Android API 24+ Web: fallback Check if Google Mobile Services is available. ```typescript const hasGms = DeviceInfoModule.getHasGms(); // Android with Play Services → true // Huawei devices without GMS → false // iOS → false ``` **Platform**: Android only ### `getHasHms(): boolean` Since v1.3.0 iOS: fallback Android API 24+ Web: fallback Check if Huawei Mobile Services is available. ```typescript const hasHms = DeviceInfoModule.getHasHms(); // Huawei devices → true // Other Android/iOS → false ``` **Platform**: Android (Huawei devices) only ### `hasSystemFeature(feature: string): boolean` Since v1.1.0 iOS: fallback Android API 24+ Web: fallback Check if specific system feature is available. ```typescript const hasNfc = DeviceInfoModule.hasSystemFeature('android.hardware.nfc'); // Android → true/false based on hardware // iOS → false ``` **Platform**: Android only **Common features**: - `android.hardware.camera` - `android.hardware.nfc` - `android.hardware.bluetooth` - `android.hardware.wifi` ### `systemAvailableFeatures: string[]` Since v1.2.0 iOS: fallback Android API 24+ Web: fallback Get list of all available system features. ```typescript const features = DeviceInfoModule.systemAvailableFeatures; // Android: ["android.hardware.camera", "android.hardware.nfc", ...] // iOS: [] ``` **Platform**: Android only ### `supportedMediaTypeList: string[]` Since v1.2.0 iOS: fallback Android API 24+ Web: fallback Get list of supported media/codec types. ```typescript const mediaTypes = DeviceInfoModule.supportedMediaTypeList; // Android: ["video/avc", "audio/mp4a-latm", ...] // iOS: [] ``` **Platform**: Android only ### Android Build Information Synchronous properties providing Android system build information. **Platform**: Android only (all return "unknown" or default values on iOS) ```typescript const serialNumber = DeviceInfoModule.serialNumber; // Android 8–9 needs granted READ_PHONE_STATE; Android 10+ is restricted const androidId = DeviceInfoModule.androidId; const previewSdkInt = DeviceInfoModule.previewSdkInt; // Android API 23+, 0 for release const securityPatch = DeviceInfoModule.securityPatch; // Android API 23+, "YYYY-MM-DD" const codename = DeviceInfoModule.codename; // "REL" for release const incremental = DeviceInfoModule.incremental; const board = DeviceInfoModule.board; const bootloader = DeviceInfoModule.bootloader; const device = DeviceInfoModule.device; // Board/platform name const display = DeviceInfoModule.display; // Build display ID const fingerprint = DeviceInfoModule.fingerprint; // Unique build identifier const hardware = DeviceInfoModule.hardware; const host = DeviceInfoModule.host; // Build host machine const product = DeviceInfoModule.product; const tags = DeviceInfoModule.tags; // Comma-separated const type = DeviceInfoModule.type; // "user", "userdebug", "eng" const baseOs = DeviceInfoModule.baseOs; // Android API 23+ const radioVersion = DeviceInfoModule.radioVersion; const buildId = DeviceInfoModule.buildId; ``` | Property | Availability | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `serialNumber` | Since v1.1.0 iOS: fallback Android API 24+: limited Web: fallback | | `androidId` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `previewSdkInt` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `securityPatch` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `codename` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `incremental` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `board` | Since v1.5.0 iOS: fallback Android API 24+ Web: fallback | | `bootloader` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `device` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `display` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `fingerprint` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `hardware` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `host` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `product` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `tags` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `type` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `baseOs` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | | `radioVersion` | Since v1.5.0 iOS: fallback Android API 24+ Web: fallback | | `buildId` | Since v1.1.0 iOS: fallback Android API 24+ Web: fallback | `serialNumber` is cached on first access. Android 8–9 requires a granted `READ_PHONE_STATE` permission. Android 10+ restricts ordinary apps even with that permission. *** ## iOS Platform (2 APIs) iOS-specific APIs. ### `getDeviceToken(): Promise` Since v1.1.0 iOS 15.1+ Android: rejects Web: rejects Get Apple DeviceCheck token. ```typescript try { const deviceToken = await DeviceInfoModule.getDeviceToken(); console.log('DeviceCheck token:', deviceToken); } catch (error) { console.error('DeviceCheck error:', error); } ``` **Platform**: iOS. DeviceCheck exists from iOS 11, but this package requires iOS 15.1+. Rejects on Android. ### `syncUniqueId(): Promise` Since v1.1.0 iOS 15.1+ Android: ID only Web: fallback Write the current IDFV to an app-specific Keychain item on iOS. This method does not enable iCloud Keychain synchronization or restore an earlier IDFV. ```typescript const uniqueId = await DeviceInfoModule.syncUniqueId(); // iOS: Writes and returns the current IDFV. // Android: Returns uniqueId without a Keychain operation. ``` **Platform**: iOS (no-op on Android) *** ## Installation & Distribution (3 APIs) App installation and distribution metadata. ### `installerPackageName: string` Since v1.1.0 iOS 15.1+ Android API 24+ Web: fallback Get package name of the app store that installed this app. ```typescript const installer = DeviceInfoModule.installerPackageName; // iOS: "com.apple.AppStore", "com.apple.TestFlight" // Android: "com.android.vending" (Play Store) ``` ### `getInstallReferrer(): Promise` Since v1.1.0 iOS: fallback Android API 24+ Web: fallback Get install referrer information (Android Play Store). ```typescript const referrer = await DeviceInfoModule.getInstallReferrer(); // Android with Play Services: referrer data // iOS: "unknown" ``` **Platform**: Android only (requires Google Play Services) ### `isSideLoadingEnabled(): boolean` Since v1.4.2 iOS: fallback Android API 24+ Web: fallback Check if sideloading (installing from unknown sources) is enabled. ```typescript const canSideload = DeviceInfoModule.isSideLoadingEnabled(); if (canSideload) { console.warn('Device allows sideloading - potential security risk'); } ``` **Platform behavior difference**: - **Android 7 and below**: Returns whether the device allows unknown sources globally (checks `Settings.Global.INSTALL_NON_MARKET_APPS`) - **Android 8.0+**: Returns whether THIS APP has permission to install other apps (per-app permission via `canRequestPackageInstalls()`) - **iOS**: This API always returns `false`; it does not detect sideloading. **Important**: On Android 8.0+, even if the user has enabled "Install unknown apps" for other apps, this will return `false` unless they specifically granted permission to this app. **Use cases**: - Security policy enforcement - Distribution channel detection - Enterprise deployment verification **Platform**: Android (returns `false` on iOS) *** ## Legacy Compatibility (2 APIs) Deprecated APIs for backward compatibility. ### `totalDiskCapacityOld: number` Since v1.2.0 iOS 15.1+ Android API 24+ Web: fallback Get total disk capacity using legacy Android API. ```typescript const totalDiskOld = DeviceInfoModule.totalDiskCapacityOld; // Android: Uses old StatFs API (pre-Jelly Bean compatibility) // iOS: Alias to totalDiskCapacity ``` ### `getFreeDiskStorageOld(): number` Since v1.1.0 iOS 15.1+ Android API 24+ Web: fallback Get free disk storage using legacy Android API. ```typescript const freeDiskOld = DeviceInfoModule.getFreeDiskStorageOld(); // Android: Uses old StatFs API (pre-Jelly Bean compatibility) // iOS: Alias to getFreeDiskStorage() ``` *** ### Unsupported compatibility properties These names exist for API compatibility. This package has no Windows native target. They return fixed defaults on iOS, Android, and web. | Property | Availability | Default | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | | `isMouseConnected` | Since v1.2.0 iOS: fallback Android: fallback Web: fallback | `false` | | `isKeyboardConnected` | Since v1.2.0 iOS: fallback Android: fallback Web: fallback | `false` | | `hostNames` | Since v1.2.0 iOS: fallback Android: fallback Web: fallback | `[]` | | `isTabletMode` | Since v1.2.0 iOS: fallback Android: fallback Web: fallback | `false` | *** ## Performance Notes Synchronous properties and methods run on the calling thread. Some query the OS or initialize a cache, so synchronous does not mean instantaneous. Promise-based methods do not have a guaranteed completion time. On iOS, `getUserAgent()` initializes a WebView on its first successful call and caches that result. Avoid repeated calls to expensive APIs during rendering. ### Caching These synchronous methods use a five-second cache: - `getIpAddressSync()` - `getMacAddressSync()` - `getCarrierSync()` A cache refresh queries the OS. Values can remain stale until the next call after expiry. For continuously changing battery or audio state, use [React hooks](/react-native-nitro-device-info/api/hooks.md). Measure latency in your app with its actual device, OS, build mode, and cache state. *** ## Platform Compatibility Matrix Support differs between members in the same category. Use the badges beside each API or grouped property above. See [badge definitions](/react-native-nitro-device-info/api/index.md#availability-badges) and [web limitations](/react-native-nitro-device-info/guide/web-support.md). *** ## Next Steps - View [Type Definitions](/react-native-nitro-device-info/api/types.md) for TypeScript types - Check out [Usage Examples](/react-native-nitro-device-info/examples/basic-usage.md) - Read the [Migration Guide](/react-native-nitro-device-info/api/migration.md) for upgrading from `react-native-device-info` --- url: /react-native-nitro-device-info/api/device-integrity.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Device Integrity API **Local-only** device integrity detection APIs for detecting rooted (Android) or jailbroken (iOS) devices. :::tip Need server-verifiable attestation? These checks are local and bypassable. For hardware-backed, server-verified attestation (Play Integrity / App Attest), see the [Device Attestation API](/react-native-nitro-device-info/api/device-attestation.md) — an opt-in package that complements these checks: use local detection as a fast offline pre-filter and attestation as the gate your server trusts. ::: ## Overview These APIs perform **local detection only** (file system checks, package detection, etc.) without any server-side verification. They're commonly used as one layer of defense in: - Financial/banking apps - Healthcare apps with sensitive data - Enterprise MDM solutions - Apps with DRM requirements :::warning Limitations **All detection methods are local-only and can be bypassed** by sophisticated tools (Magisk + Shamiko, RootHide, PlayIntegrityFix, etc.). - **"Not detected" does NOT guarantee a secure device** - These APIs do NOT use Play Integrity API or iOS App Attest - Use as one layer of defense-in-depth, not as sole security measure ::: Read the [availability badge definitions](/react-native-nitro-device-info/api/index.md#availability-badges). Both APIs belong to the core package; web only returns fallback values. ## API Reference ### `isDeviceCompromised()` Since v1.4.2 iOS 15.1+ Android API 24+ Web: fallback Synchronously checks if the device is rooted (Android) or jailbroken (iOS). ```typescript isDeviceCompromised(): boolean ``` **Returns:** `true` if device is compromised, `false` otherwise **Performance:** \<50ms **Emulator Policy:** Returns `false` on emulators/simulators for development convenience. *** ### `verifyDeviceIntegrity()` Since v1.4.2 iOS 15.1+ Android API 24+ Web: fallback Asynchronous wrapper for device integrity verification. ```typescript verifyDeviceIntegrity(): Promise ``` **Returns:** Promise resolving to `true` if device is rooted/jailbroken **Performance:** - iOS: up to 200ms (includes SSH port scanning) - Android: \<50ms (async wrapper for `isDeviceCompromised()`) **Platform Differences:** - **iOS:** Includes SSH port scanning (ports 22, 44) in addition to all checks performed by `isDeviceCompromised()`. This additional check can detect OpenSSH installed by jailbreak tools. - **Android:** Same as `isDeviceCompromised()`, provided as async wrapper for API consistency. **Emulator Policy:** Returns `false` on emulators/simulators. ## Detection Methods ### Android | Method | Priority | Description | | -------------- | -------- | ----------------------------------------------------- | | su binaries | High | `/system/xbin/su`, `/system/bin/su`, `/sbin/su`, etc. | | Magisk | High | `/data/adb/magisk`, Magisk Manager package | | KernelSU | High | `/data/adb/ksu`, KernelSU Manager package | | APatch | High | `/data/adb/apatch`, APatch Manager package | | Busybox | Medium | `/system/xbin/busybox` | | Build props | Medium | `ro.debuggable=1`, `ro.secure=0`, test-keys | | Superuser apps | Low | Legacy SuperSU, Superuser.apk | ### iOS | Method | Description | | ----------------- | --------------------------------------------- | | Jailbreak apps | Cydia, Sileo, Zebra, Installer 5 | | URL schemes | `cydia://`, `sileo://`, `zbra://`, `filza://` | | System file write | `/private/jailbreak.txt` write test | | DYLD injection | MobileSubstrate, libhooker, TweakInject | | Symbolic links | `/Applications`, `/Library/Ringtones` | | SSH ports | Port 22 (OpenSSH), Port 44 (checkra1n) | ## Usage Examples ### Basic Check ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function SecurityCheck() { const isCompromised = DeviceInfoModule.isDeviceCompromised(); if (isCompromised) { return ; } return ; } ``` ### Financial App Protection ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; async function performTransaction(amount: number) { // Use async API for enhanced verification const isCompromised = await DeviceInfoModule.verifyDeviceIntegrity(); if (isCompromised) { throw new Error('Transaction blocked: Device integrity check failed'); } // Proceed with transaction return processPayment(amount); } ``` ### Conditional Feature Access ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function DeviceAuthenticationLogin() { const isSecure = !DeviceInfoModule.isDeviceCompromised(); const hasDeviceAuthentication = DeviceInfoModule.isPinOrFingerprintSet; if (!isSecure) { // Fall back to password-only login on compromised devices return ; } if (hasDeviceAuthentication) { return ; } return ; } ``` ## Platform Support | API | iOS | Android | | ------------------------- | -------------- | ----------------- | | `isDeviceCompromised()` | ✅ | ✅ | | `verifyDeviceIntegrity()` | ✅ (+ SSH scan) | ✅ (async wrapper) | ## Best Practices 1. **Don't rely solely on detection** - Use as one layer of defense-in-depth 2. **Handle gracefully** - Don't crash, provide alternative flows 3. **Log for analytics** - Track detection rates for security insights 4. **Test on real devices** - Emulators always return `false` 5. **Update regularly** - New rooting tools emerge frequently ## See Also - [Device Attestation](/react-native-nitro-device-info/api/device-attestation.md) - [isEmulator](/react-native-nitro-device-info/api/device-info.md#isemulator-boolean) - [isPinOrFingerprintSet](/react-native-nitro-device-info/api/device-info.md#ispinorfingerprintset-boolean) --- url: /react-native-nitro-device-info/api/hooks.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # React Hooks React hooks for monitoring runtime device properties. They poll native getters and re-render when a sampled value changes. See [update intervals and initial values](/react-native-nitro-device-info/guide/react-hooks.md#update-intervals-and-initial-values). All seven hooks were introduced in v1.4.0. Native minimums are iOS 15.1 and Android API 24. Web requires v1.8.0 or later. See [availability badges](/react-native-nitro-device-info/api/index.md#availability-badges). This page documents root exports. Headphone hooks from `/compat` return `{ loading, result }` instead of `boolean`. ## Import ```typescript import { useBatteryLevel, useBatteryLevelIsLow, usePowerState, useIsHeadphonesConnected, useIsWiredHeadphonesConnected, useIsBluetoothHeadphonesConnected, useBrightness, } from 'react-native-nitro-device-info'; ``` *** ## Battery Hooks ### `useBatteryLevel()` Since v1.4.0 iOS 15.1+ Android API 24+ Web: limited Read battery level after mount and poll every five seconds. ```typescript function useBatteryLevel(): number | null ``` **Returns**: Battery level (0.0 to 1.0), or `null` during initial load or when unavailable. **Example**: ```tsx import { useBatteryLevel } from 'react-native-nitro-device-info'; function BatteryIndicator() { const batteryLevel = useBatteryLevel(); if (batteryLevel === null) { return Loading...; } return Battery: {Math.round(batteryLevel * 100)}%; } ``` *** ### `useBatteryLevelIsLow()` Since v1.4.0 iOS 15.1+ Android API 24+ Web: limited Monitor for low battery conditions with platform-specific thresholds. ```typescript function useBatteryLevelIsLow(): number | null ``` **Returns**: Battery level when below threshold, or `null` if battery is not low or unavailable. An unavailable reading does not trigger a low-battery warning. **Thresholds**: - **iOS**: 20% (matches iOS low power mode trigger) - **Android**: 15% (matches Android low battery warning) **Example**: ```tsx import { useBatteryLevelIsLow } from 'react-native-nitro-device-info'; function LowBatteryWarning() { const lowBattery = useBatteryLevelIsLow(); if (lowBattery !== null) { return ( Low Battery: {Math.round(lowBattery * 100)}% ); } return null; } ``` *** ### `usePowerState()` Since v1.4.0 iOS 15.1+ Android API 24+: limited Web: limited Monitor comprehensive power state including battery level, charging status, and low power mode. ```typescript function usePowerState(): Partial ``` On Android, `lowPowerMode` is always `false`. **Returns**: A `Partial` object. All properties are optional and may be `undefined` during initial load or if unavailable on the platform: - `batteryLevel?: number` - Battery charge level (0.0 to 1.0), or `-1` when unavailable - `batteryState?: BatteryState` - Charging status ('unknown', 'unplugged', 'charging', 'full') - `lowPowerMode?: boolean` - Whether low power mode is enabled (iOS only) **Example**: ```tsx import { usePowerState } from 'react-native-nitro-device-info'; function PowerStatus() { const powerState = usePowerState(); const level = powerState.batteryLevel; return ( Level: {level === undefined || level < 0 ? 'Loading or unavailable' : Math.round(level * 100) + '%'} Status: {powerState.batteryState ?? 'unknown'} Low Power: {powerState.lowPowerMode ? 'Yes' : 'No'} ); } ``` *** ## Headphone Hooks ### `useIsHeadphonesConnected()` Since v1.4.0 iOS 15.1+ Android API 24+ Web: fallback Monitor headphone connection state (wired or Bluetooth). ```typescript function useIsHeadphonesConnected(): boolean ``` **Returns**: `true` if any headphones are connected, `false` otherwise. **Example**: ```tsx import { useIsHeadphonesConnected } from 'react-native-nitro-device-info'; function AudioOutput() { const headphonesConnected = useIsHeadphonesConnected(); return ( Audio: {headphonesConnected ? 'Headphones' : 'Speaker'} ); } ``` *** ### `useIsWiredHeadphonesConnected()` Since v1.4.0 iOS 15.1+ Android API 24+ Web: fallback Monitor wired headphone connection state. ```typescript function useIsWiredHeadphonesConnected(): boolean ``` **Returns**: `true` if wired headphones are connected, `false` otherwise. **Example**: ```tsx import { useIsWiredHeadphonesConnected } from 'react-native-nitro-device-info'; function WiredAudioStatus() { const wiredConnected = useIsWiredHeadphonesConnected(); return ( ); } ``` *** ### `useIsBluetoothHeadphonesConnected()` Since v1.4.0 iOS 15.1+ Android API 24+ Web: fallback Monitor Bluetooth headphone/audio device connection state. ```typescript function useIsBluetoothHeadphonesConnected(): boolean ``` **Returns**: `true` if Bluetooth audio devices are connected, `false` otherwise. **Example**: ```tsx import { useIsBluetoothHeadphonesConnected } from 'react-native-nitro-device-info'; function BluetoothAudioStatus() { const bluetoothConnected = useIsBluetoothHeadphonesConnected(); return ( ); } ``` *** ## Display Hooks ### `useBrightness()` Since v1.4.0 iOS 15.1+ Android: fallback Web: fallback Monitor screen brightness changes (iOS only). ```typescript function useBrightness(): number | null ``` **Returns**: - **iOS**: Brightness level (0.0 to 1.0), or `null` during initial load - **Android**: `-1` (not supported) **Example**: ```tsx import { useBrightness } from 'react-native-nitro-device-info'; import { Platform } from 'react-native'; function BrightnessIndicator() { const brightness = useBrightness(); if (Platform.OS === 'android') { return Brightness monitoring is iOS only; } if (brightness === null) { return Loading...; } return Brightness: {Math.round(brightness * 100)}%; } ``` *** ## Platform Support Summary | Hook | iOS | Android | | ----------------------------------- | --- | ------- | | `useBatteryLevel` | ✅ | ✅ | | `useBatteryLevelIsLow` | ✅ | ✅ | | `usePowerState` | ✅ | ✅ | | `useIsHeadphonesConnected` | ✅ | ✅ | | `useIsWiredHeadphonesConnected` | ✅ | ✅ | | `useIsBluetoothHeadphonesConnected` | ✅ | ✅ | | `useBrightness` | ✅ | ❌ (-1) | *** ## Best Practices ### Handle Loading States ```tsx const batteryLevel = useBatteryLevel(); if (batteryLevel === null) { return ; } ``` ### Memoize Dependent Components ```tsx const BatteryIcon = React.memo(({ level }: { level: number }) => { return ; }); function Parent() { const level = useBatteryLevel(); return level !== null && ; } ``` ### Platform-Specific Handling ```tsx import { Platform } from 'react-native'; function BrightnessControl() { const brightness = useBrightness(); if (Platform.OS === 'android') { return null; // Not supported on Android } return ; } ``` *** ## Migration from react-native-device-info For migration that preserves `react-native-device-info` hook result shapes, use `/compat`: ```tsx // Before (react-native-device-info) import { useBatteryLevel } from 'react-native-device-info'; // After (compatibility entry point) import { useBatteryLevel } from 'react-native-nitro-device-info/compat'; // Usage remains identical const batteryLevel = useBatteryLevel(); ``` See the [Migration Guide](/react-native-nitro-device-info/api/migration.md) for more details. --- url: /react-native-nitro-device-info/api/index.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # API Reference Overview Choose the API entry point before copying an example. The root API and `/compat` API have different names and return types. ## Entry points | Import | Purpose | Example | | --------------------------------------------------------------------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------- | | `{ DeviceInfoModule }` from `react-native-nitro-device-info` | Native properties and methods | `DeviceInfoModule.model` | | `DeviceInfo` from `react-native-nitro-device-info/compat` | `react-native-device-info` 15.x-style functions | `DeviceInfo.getModel()` | | `{ useBatteryLevel }` from `react-native-nitro-device-info` | React hook returning a value | `number \| null` | | `{ useIsHeadphonesConnected }` from `react-native-nitro-device-info/compat` | Compatibility hook result | `{ loading, result }` | | `{ DeviceIntegrityModule }` from `react-native-nitro-device-integrity` | Device attestation with backend verification | See [Device Attestation](/react-native-nitro-device-info/api/device-attestation.md) | `DeviceInfo` from the root is a TypeScript type. It is not a default runtime object. See [Migration](/react-native-nitro-device-info/api/migration.md) for compatibility caveats. ## Availability badges Each API section shows its introduction version and current platform behavior. Grouped properties have badges in their table rows. Since v1.3.0 iOS 15.1+ Android API 24+ Web: fallback - **Since** identifies the first published release with this member name and property or method form. Earlier releases may have different return types or behavior. It does not mean that every platform implemented the feature in that release. - **iOS / Android** identifies a functional native implementation. The number is an OS minimum, not a package version. A separate `since v…` inside the platform badge identifies a later functional implementation. The current core package requires iOS 15.1+ and Android API 24+; dependencies can raise these minimums. - **Limited** identifies an estimate, restricted implementation, or browser API dependency. Read the section's limitations before using the result. - **Fallback** identifies an unsupported operation that returns a fixed default. **Rejects** identifies a method that fails on that platform. - **Unreleased** identifies an implementation on `main` that has not reached a published npm release. It is not a version number. Web entry points and their fallback values are available from **v1.8.0**. A `Web: limited` badge identifies browser-derived values. Browser permissions, API availability, and SSR can still produce fallbacks. A fallback does not provide the native feature. The iOS camera and device-authentication implementations are available from v1.9.0. Core releases through v1.8.3 expose those names but return constants on iOS. ### Version evidence Introduction versions were checked against [published npm versions and their `gitHead` values](https://registry.npmjs.org/react-native-nitro-device-info). These source snapshots show the relevant member declarations: | Published version | Source | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | v0.1.0 | [Initial interface](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/0.1.0/src/DeviceInfo.nitro.ts) | | v1.1.0 | [Expanded interface](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.1.0/src/DeviceInfo.nitro.ts) | | v1.2.0 | [Property-based interface](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.2.0/src/DeviceInfo.nitro.ts) | | v1.2.1 | [Key-store and Liquid Glass declarations](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.2.1/src/DeviceInfo.nitro.ts) | | v1.3.0 | [Runtime getter interface](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.3.0/src/DeviceInfo.nitro.ts) | | v1.4.0 | [React hook exports](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.4.0/src/hooks/index.ts) | | v1.4.2 | [Local integrity and Expo Device parity declarations](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.4.2/src/DeviceInfo.nitro.ts) | | v1.5.0 | [Carrier and build-field declarations](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.5.0/packages/react-native-nitro-device-info/src/DeviceInfo.nitro.ts) | | v1.8.0 | [Functional iOS async wrappers](https://github.com/l2hyunwoo/react-native-nitro-device-info/commit/cb6eb026) and [web entry point](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/v1.8.0/packages/react-native-nitro-device-info/src/index.web.ts) | ## Native API by task These members belong to `DeviceInfoModule`. Parentheses identify methods; entries without parentheses are properties. | Task | Example members | Reference | | ---------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | Identify the model and OS | `deviceId`, `model`, `systemVersion`, `deviceType` | [Core Device Information](/react-native-nitro-device-info/api/device-info.md#core-device-information-9-apis) | | Read identifiers | `uniqueId`, `manufacturer`, `deviceName` | [Core Device Information](/react-native-nitro-device-info/api/device-info.md#core-device-information-9-apis) | | Check hardware | `isTablet`, `isEmulator`, `isCameraPresent`, `isPinOrFingerprintSet` | [Device Capabilities](/react-native-nitro-device-info/api/device-info.md#device-capabilities-7-apis) | | Read display information | `getHasNotch()`, `getHasDynamicIsland()`, `getIsLandscape()`, `getBrightness()` | [Display & Screen](/react-native-nitro-device-info/api/device-info.md#display--screen-7-apis) | | Read memory and storage | `totalMemory`, `getUsedMemory()`, `totalDiskCapacity`, `getFreeDiskStorage()` | [System Resources](/react-native-nitro-device-info/api/device-info.md#system-resources-7-apis) | | Read battery state | `getBatteryLevel()`, `getPowerState()`, `getIsBatteryCharging()` | [Battery & Power](/react-native-nitro-device-info/api/device-info.md#battery--power-4-apis) | | Read app metadata | `version`, `buildNumber`, `bundleId`, `getFirstInstallTime()` | [Application Metadata](/react-native-nitro-device-info/api/device-info.md#application-metadata-9-apis) | | Read network information | `getIpAddress()`, `getIpAddressSync()`, `getMacAddress()` | [Network](/react-native-nitro-device-info/api/device-info.md#network-6-apis) | | Read carrier information | `getCarrier()`, `getCarrierSync()`, `mobileCountryCode` | [Carrier Information](/react-native-nitro-device-info/api/device-info.md#carrier-information-7-apis) | | Check audio outputs | `isHeadphonesConnected()`, `getIsWiredHeadphonesConnected()` | [Audio Accessories](/react-native-nitro-device-info/api/device-info.md#audio-accessories-4-apis) | | Check location services | `isLocationEnabled()`, `getIsLocationEnabled()`, `getAvailableLocationProviders()` | [Location Services](/react-native-nitro-device-info/api/device-info.md#location-services-3-apis) | | Check Android features | `apiLevel`, `getHasGms()`, `getHasHms()`, `hasSystemFeature(feature)` | [Android Platform](/react-native-nitro-device-info/api/device-info.md#android-platform-20-apis) | | Request Apple DeviceCheck or write an ID to Keychain | `getDeviceToken()`, `syncUniqueId()` | [iOS Platform](/react-native-nitro-device-info/api/device-info.md#ios-platform-2-apis) | | Read installation information | `installerPackageName`, `getInstallReferrer()`, `isSideLoadingEnabled()` | [Installation & Distribution](/react-native-nitro-device-info/api/device-info.md#installation--distribution-3-apis) | For the remaining members, see the [complete DeviceInfo reference](/react-native-nitro-device-info/api/device-info.md). ## Call and return contracts ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; const model: string = DeviceInfoModule.model; const battery: number = DeviceInfoModule.getBatteryLevel(); async function readIpAddress(): Promise { return await DeviceInfoModule.getIpAddress(); } ``` - **Property**: Read without parentheses. A property can query the OS; `readonly` does not mean that the value is constant. - **Synchronous method**: Call directly. Synchronous execution does not guarantee a fixed latency. - **Promise-based method**: Await inside an async function and handle rejection where the API can fail. - **React hook**: Call inside a React component or custom hook. See [Hooks API](/react-native-nitro-device-info/api/hooks.md) for loading values and polling intervals. Memory and storage use bytes. Battery and brightness use fractions from `0` to `1` when available. For example, `getBatteryLevel()` returns `-1` when unavailable, while `useBatteryLevel()` returns `null`. ## Platform and security limits An unsupported API may return a placeholder or reject. A `false` result can mean that a platform has no implementation. Check the individual API and the [Web Support guide](/react-native-nitro-device-info/guide/web-support.md). [Local device integrity](/react-native-nitro-device-info/api/device-integrity.md) checks in this package are bypassable heuristics. [Device attestation](/react-native-nitro-device-info/api/device-attestation.md) requires the separate `react-native-nitro-device-integrity` package and backend verification. ## Types and source Import `DeviceInfo`, `PowerState`, `BatteryState`, `DeviceType`, and `NavigationMode` with `import type`. See [Type Definitions](/react-native-nitro-device-info/api/types.md). The current website follows the repository's `main` branch. For an older installed release, check that release's declarations. The signature source is [`DeviceInfo.nitro.ts`](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/main/packages/react-native-nitro-device-info/src/DeviceInfo.nitro.ts); native implementations define platform behavior. --- url: /react-native-nitro-device-info/api/migration.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Migration Guide Migrating from `react-native-device-info` to `react-native-nitro-device-info`. ## Overview `react-native-nitro-device-info` ships a **drop-in compatibility layer** that exposes the exact `react-native-device-info` (RNDI) 15.x API surface — same function names, same signatures, same default `DeviceInfo` object, same hooks. You import from `react-native-nitro-device-info/compat` instead of `react-native-device-info`, and **your call sites stay unchanged**. There are two ways to migrate. Pick based on how much you want to change: | Path | Effort | What you get | | ------------------------- | ---------------------------------- | --------------------------------------------------------------------- | | **Drop-in (recommended)** | One command — rewrite imports only | Keep call sites; review placeholders and platform differences. | | **Native (optional)** | Manual rewrite of call sites | Direct property access + synchronous getters for maximum performance. | Start with the drop-in path. Move individual call sites to the native API later if you want the last bit of performance — the two can coexist. ## Drop-in Migration (recommended) ### 1. Install ```bash # Install the new library + its peer dependency npm install react-native-nitro-device-info react-native-nitro-modules # (or: yarn add react-native-nitro-device-info react-native-nitro-modules) # iOS cd ios && pod install && cd .. ``` ### 2. Run the codemod The library bundles a codemod that rewrites every `react-native-device-info` import to `react-native-nitro-device-info/compat`. It **only rewrites import specifiers** — it never touches your call sites. ```bash npx react-native-nitro-device-info migrate # or target a specific directory: npx react-native-nitro-device-info migrate src ``` It rewrites ES imports (default, named, namespace), re-exports, and CommonJS `require()`: ```typescript // Before import DeviceInfo from 'react-native-device-info'; import { getModel, useBatteryLevel } from 'react-native-device-info'; // After (rewritten automatically — call sites unchanged) import DeviceInfo from 'react-native-nitro-device-info/compat'; import { getModel, useBatteryLevel } from 'react-native-nitro-device-info/compat'; ``` Prefer to do it by hand? A project-wide find-and-replace of the import string `'react-native-device-info'` → `'react-native-nitro-device-info/compat'` achieves the same result. ### 3. Remove the old dependency ```bash npm uninstall react-native-device-info ``` ### 4. Review the documented caveats The compat layer targets the RNDI **15.x API surface**. A small number of APIs return placeholder values because they have no native equivalent in this library — see [Compat Layer Caveats](#compat-layer-caveats) below. If your app doesn't use those APIs, you're done. That's it — no call sites to change, no `await` to add or remove. ## Compat Layer Caveats The compat layer is signature-compatible across the whole RNDI surface, with these documented exceptions: | API | Compat behavior | Why | | ----------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `getInstanceId()` / `getInstanceIdSync()` | Returns `'unknown'` | RNDI deprecated these (Firebase/GMS Instance ID is slated for removal). No native equivalent. | | `getAppSetId()` | Returns `{ id: 'unknown', scope: -1 }` | Identical to RNDI's own value when the optional Play Services App Set dependency is absent. | | `getUserAgentSync()` | Returns `''` | This library computes the user agent asynchronously (iOS WebView). Use the async `getUserAgent()` for a real value. | | `getInstallReferrerSync()` | Returns `'unknown'` | The install referrer is only available asynchronously. Use the async `getInstallReferrer()`. | Other APIs delegate to this library’s native implementation. They can still return platform-specific placeholders or behave differently from RNDI. A few APIs differ in _shape_ but are converted for you (e.g. `getAvailableLocationProviders()` returns RNDI's `{ gps: true, network: true }` map, `getFreeDiskStorage(storageType?)` accepts and ignores the iOS storage-type argument, and the async accessory hooks return RNDI's `{ loading, result }` shape). ## Native Migration (optional, for maximum performance) If you want direct property access and synchronous getters instead of the compat shims, import `DeviceInfoModule` from the package root and rewrite call sites using the tables below. ### Key Differences **Architecture** - **react-native-device-info**: API and implementation depend on the installed release - **react-native-nitro-device-info**: Nitro HybridObject (JSI) **Properties vs methods** — most RNDI methods become direct property accessors: ```typescript // react-native-device-info // native API const deviceId = DeviceInfo.getDeviceId(); const deviceId = DeviceInfoModule.deviceId; const brand = DeviceInfo.getBrand(); const brand = DeviceInfoModule.brand; ``` **Synchronous by default** — values that were async in RNDI are now sync: ```typescript const uniqueId = DeviceInfoModule.uniqueId; // sync property const totalMemory = DeviceInfoModule.totalMemory; // sync property const batteryLevel = DeviceInfoModule.getBatteryLevel(); // sync method const isTablet = DeviceInfoModule.isTablet; // sync property ``` **Promise-based methods still need `await`**: ```typescript const ipAddress = await DeviceInfoModule.getIpAddress(); const carrier = await DeviceInfoModule.getCarrier(); const installTime = await DeviceInfoModule.getFirstInstallTime(); ``` ### Quick Migration Reference ### Device Information | react-native-device-info | `react-native-nitro-device-info` | Notes | | -------------------------------- | -------------------------------- | ----------------- | | `DeviceInfo.getDeviceId()` | `DeviceInfoModule.deviceId` | Now a property | | `DeviceInfo.getBrand()` | `DeviceInfoModule.brand` | Now a property | | `DeviceInfo.getModel()` | `DeviceInfoModule.model` | Now a property | | `DeviceInfo.getSystemName()` | `DeviceInfoModule.systemName` | Now a property | | `DeviceInfo.getSystemVersion()` | `DeviceInfoModule.systemVersion` | Now a property | | `await DeviceInfo.getUniqueId()` | `DeviceInfoModule.uniqueId` | Now sync property | | `DeviceInfo.getManufacturer()` | `DeviceInfoModule.manufacturer` | Now property | | `DeviceInfo.isTablet()` | `DeviceInfoModule.isTablet` | Now property | ### System Resources | react-native-device-info | `react-native-nitro-device-info` | Notes | | ----------------------------------------- | --------------------------------------- | ----------------- | | `await DeviceInfo.getTotalMemory()` | `DeviceInfoModule.totalMemory` | Now sync property | | `await DeviceInfo.getUsedMemory()` | `DeviceInfoModule.getUsedMemory()` | Now sync method | | `await DeviceInfo.getTotalDiskCapacity()` | `DeviceInfoModule.totalDiskCapacity` | Now sync property | | `await DeviceInfo.getFreeDiskStorage()` | `DeviceInfoModule.getFreeDiskStorage()` | Now sync method | ### Battery Information | react-native-device-info | `react-native-nitro-device-info` | Notes | | -------------------------------------- | ----------------------------------------- | --------------- | | `await DeviceInfo.getBatteryLevel()` | `DeviceInfoModule.getBatteryLevel()` | Now sync method | | `await DeviceInfo.getPowerState()` | `DeviceInfoModule.getPowerState()` | Now sync method | | `await DeviceInfo.isBatteryCharging()` | `DeviceInfoModule.getIsBatteryCharging()` | Now sync method | ### Application Metadata | react-native-device-info | `react-native-nitro-device-info` | Notes | | --------------------------------- | ---------------------------------- | -------------- | | `DeviceInfo.getVersion()` | `DeviceInfoModule.version` | Now property | | `DeviceInfo.getBuildNumber()` | `DeviceInfoModule.buildNumber` | Now property | | `DeviceInfo.getBundleId()` | `DeviceInfoModule.bundleId` | Now property | | `DeviceInfo.getApplicationName()` | `DeviceInfoModule.applicationName` | Now property | | `DeviceInfo.getReadableVersion()` | `DeviceInfoModule.readableVersion` | Now a property | ### Network & Connectivity | react-native-device-info | `react-native-nitro-device-info` | Notes | | -------------------------------------- | -------------------------------------------- | ----------------- | | `await DeviceInfo.getIpAddress()` | `await DeviceInfoModule.getIpAddress()` | Still async (I/O) | | `await DeviceInfo.getMacAddress()` | `await DeviceInfoModule.getMacAddress()` | Still async (I/O) | | `await DeviceInfo.getCarrier()` | `await DeviceInfoModule.getCarrier()` | Still async (I/O) | | `await DeviceInfo.isLocationEnabled()` | `await DeviceInfoModule.isLocationEnabled()` | Still async (I/O) | ### Step-by-Step (native path) > These steps assume you want the native API. For the zero-change path, use > [Drop-in Migration](#drop-in-migration-recommended) instead. #### 1. Install the New Library ```bash # Remove old library npm uninstall react-native-device-info # Install new library npm install react-native-nitro-device-info react-native-nitro-modules # iOS cd ios && pod install && cd .. ``` #### 2. Update Imports Find and replace imports across your codebase: ```typescript // Before import DeviceInfo from 'react-native-device-info'; // After import { DeviceInfoModule } from 'react-native-nitro-device-info'; ``` #### 3. Update Module Name Replace all `DeviceInfo` references with `DeviceInfoModule`: ```typescript // Before const brand = DeviceInfo.getBrand(); // After const brand = DeviceInfoModule.brand; // Also changed to property ``` #### 4. Convert Method Calls to Properties Update method calls that are now properties: ```typescript // Before const deviceId = DeviceInfo.getDeviceId(); const brand = DeviceInfo.getBrand(); const model = DeviceInfo.getModel(); const systemName = DeviceInfo.getSystemName(); const systemVersion = DeviceInfo.getSystemVersion(); const readableVersion = DeviceInfo.getReadableVersion(); // After const deviceId = DeviceInfoModule.deviceId; const brand = DeviceInfoModule.brand; const model = DeviceInfoModule.model; const systemName = DeviceInfoModule.systemName; const systemVersion = DeviceInfoModule.systemVersion; const readableVersion = DeviceInfoModule.readableVersion; ``` #### 5. Remove Unnecessary `await` Keywords Remove `await` from methods that are now synchronous: ```typescript // Before const uniqueId = await DeviceInfo.getUniqueId(); const totalMemory = await DeviceInfo.getTotalMemory(); const batteryLevel = await DeviceInfo.getBatteryLevel(); // After (no await needed, now sync properties/methods) const uniqueId = DeviceInfoModule.uniqueId; const totalMemory = DeviceInfoModule.totalMemory; const batteryLevel = DeviceInfoModule.getBatteryLevel(); ``` #### 6. Test Your Changes Run your app and verify: - All device info calls work correctly - No runtime errors from async/sync changes - TypeScript types are correct ## Complete Example ### Before (react-native-device-info) ```typescript import React, { useEffect, useState } from 'react'; import DeviceInfo from 'react-native-device-info'; function DeviceInfoScreen() { const [deviceId, setDeviceId] = useState(''); const [brand, setBrand] = useState(''); const [uniqueId, setUniqueId] = useState(''); const [totalMemory, setTotalMemory] = useState(0); const [batteryLevel, setBatteryLevel] = useState(0); const [ipAddress, setIpAddress] = useState(''); useEffect(() => { async function loadDeviceInfo() { // Everything was async or method-based const id = DeviceInfo.getDeviceId(); const b = DeviceInfo.getBrand(); const uid = await DeviceInfo.getUniqueId(); const mem = await DeviceInfo.getTotalMemory(); const bat = await DeviceInfo.getBatteryLevel(); const ip = await DeviceInfo.getIpAddress(); setDeviceId(id); setBrand(b); setUniqueId(uid); setTotalMemory(mem); setBatteryLevel(bat); setIpAddress(ip); } loadDeviceInfo(); }, []); return ( Device: {brand} {deviceId} Unique ID: {uniqueId} Memory: {totalMemory} Battery: {batteryLevel < 0 ? 'Unavailable' : `${(batteryLevel * 100).toFixed(0)}%`} IP: {ipAddress} ); } ``` ### After (`react-native-nitro-device-info`) ```typescript import React, { useEffect, useState } from 'react'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; function DeviceInfoScreen() { const [ipAddress, setIpAddress] = useState(''); // Sync properties/methods - instant access, no state needed const deviceId = DeviceInfoModule.deviceId; const brand = DeviceInfoModule.brand; const uniqueId = DeviceInfoModule.uniqueId; const totalMemory = DeviceInfoModule.totalMemory; const batteryLevel = DeviceInfoModule.getBatteryLevel(); useEffect(() => { // Only async operations need useEffect DeviceInfoModule.getIpAddress().then(setIpAddress); }, []); return ( Device: {brand} {deviceId} Unique ID: {uniqueId} Memory: {totalMemory} Battery: {batteryLevel < 0 ? 'Unavailable' : `${(batteryLevel * 100).toFixed(0)}%`} IP: {ipAddress} ); } ``` ## Benefits of Migration ### 1. Performance Improvement ```typescript // react-native-device-info: model and brand already return synchronously. const brand = DeviceInfo.getBrand(); const model = DeviceInfo.getModel(); const memory = await DeviceInfo.getTotalMemory(); // Native API: direct properties; measure latency in your app. const brand = DeviceInfoModule.brand; const model = DeviceInfoModule.model; const memory = DeviceInfoModule.totalMemory; ``` ### 2. Simpler Code No need for `async`/`await` for simple getters: ```typescript // Old - required async function async function getDeviceInfo() { const brand = DeviceInfo.getBrand(); const model = DeviceInfo.getModel(); return `${brand} ${model}`; } // New - direct access function getDeviceInfo() { return `${DeviceInfoModule.brand} ${DeviceInfoModule.model}`; } ``` ### 3. Better TypeScript Support Full type definitions with excellent IntelliSense: ```typescript import type { PowerState, BatteryState } from 'react-native-nitro-device-info'; const powerState: PowerState = DeviceInfoModule.getPowerState(); // TypeScript knows: powerState.batteryLevel, powerState.batteryState, powerState.lowPowerMode ``` ### 4. Future-Proof Architecture Built on React Native's New Architecture (Fabric + JSI) for long-term support. ## React Hooks Migration **Drop-in path:** every RNDI hook is re-exported from the compat layer with RNDI's exact signature (including the `{ loading, result }` shape for the async hooks). The codemod rewrites the import for you; usage is unchanged: ```tsx // Before import { useBatteryLevel, useDeviceName } from 'react-native-device-info'; // After (rewritten to the compat subpath — usage identical) import { useBatteryLevel, useDeviceName } from 'react-native-nitro-device-info/compat'; function BatteryWidget() { const batteryLevel = useBatteryLevel(); // number | null const { result: name } = useDeviceName(); // AsyncHookResult return {name}: {batteryLevel}; } ``` **Native path:** the package root exports 7 hooks directly, returning bare values (no `AsyncHookResult` wrapper). Use these if you migrate call sites to the native API. | react-native-device-info | Native root export | Notes | | ------------------------------------- | ------------------------------------- | --------------------------------------------------------- | | `useBatteryLevel()` | `useBatteryLevel()` | Identical (`number \| null`) | | `useBatteryLevelIsLow()` | `useBatteryLevelIsLow()` | Identical | | `usePowerState()` | `usePowerState()` | Identical | | `useIsHeadphonesConnected()` | `useIsHeadphonesConnected()` | Returns `boolean` (compat wraps to `{ loading, result }`) | | `useIsWiredHeadphonesConnected()` | `useIsWiredHeadphonesConnected()` | Returns `boolean` (compat wraps) | | `useIsBluetoothHeadphonesConnected()` | `useIsBluetoothHeadphonesConnected()` | Returns `boolean` (compat wraps) | | `useBrightness()` | `useBrightness()` | Identical (`number \| null`) | RNDI's remaining hooks (`useFirstInstallTime`, `useDeviceName`, `useHasSystemFeature`, `useIsEmulator`, `useManufacturer`) are available on the **compat path only**, where they return RNDI's `AsyncHookResult` shape. See the [React Hooks Guide](/react-native-nitro-device-info/guide/react-hooks.md) for detailed hook documentation. ### Behavioral Changes (native path only) These differences apply when you adopt the **native API** (`DeviceInfoModule`). The drop-in compat layer adapts function signatures and hook result shapes. It does not reproduce all platform behavior; review [Compat Layer Caveats](#compat-layer-caveats). 1. **Synchronous by default**: Most methods no longer return Promises 2. **Property accessors**: Some getters are now properties 3. **Module name**: Uses `DeviceInfoModule` instead of `DeviceInfo` 4. **Event listeners**: Raw battery/network state listeners are not exposed; use the provided React hooks (e.g. `useBatteryLevel`, `usePowerState`) for reactive monitoring instead. The compat layer re-exposes RNDI's hooks unchanged. ## Troubleshooting ### TypeScript Errors After Migration If you see type errors after migration: ```bash # Clear TypeScript cache rm -rf node_modules/.cache yarn install # Restart TypeScript server in your IDE ``` ### Runtime Errors If you get "Cannot read property" errors: 1. Ensure `react-native-nitro-modules` is installed as peer dependency 2. Run `pod install` on iOS 3. Clean build (`yarn android` / `yarn ios` with clean) ### Missing Methods If a method is not available: 1. Check the [API Reference](/react-native-nitro-device-info/api/device-info.md) for the correct method name 2. Some methods may have been renamed or consolidated 3. Open an issue on GitHub if you need a specific method *** ## Migrating from expo-device If you're migrating from `expo-device`, many APIs have compatible alternatives in `react-native-nitro-device-info`. ### Key Differences | Aspect | expo-device | react-native-nitro-device-info | | --------------- | ------------------ | ---------------------------------------------- | | Architecture | Expo Module API | Nitro Modules (JSI) | | Sync/Async | Mixed (some async) | Mostly synchronous | | Expo Dependency | Requires Expo | Works with bare React Native | | Performance | Good | Direct synchronous access; measure in your app | ### API Migration Reference | expo-device | react-native-nitro-device-info | Notes | | ------------------------------------ | ----------------------------------------- | ----------------------- | | `Device.brand` | `DeviceInfoModule.brand` | Same | | `Device.manufacturer` | `DeviceInfoModule.manufacturer` | Same | | `Device.modelName` | `DeviceInfoModule.model` | Different property name | | `Device.modelId` | `DeviceInfoModule.deviceId` | Different property name | | `Device.designName` | `DeviceInfoModule.device` | Android only | | `Device.productName` | `DeviceInfoModule.product` | Android only | | `Device.deviceYearClass` | `DeviceInfoModule.deviceYearClass` | Same | | `Device.totalMemory` | `DeviceInfoModule.totalMemory` | Same | | `Device.supportedCpuArchitectures` | `DeviceInfoModule.supportedAbis` | Android only | | `Device.osName` | `DeviceInfoModule.systemName` | Different property name | | `Device.osVersion` | `DeviceInfoModule.systemVersion` | Different property name | | `Device.osBuildId` | `DeviceInfoModule.display` | Android only | | `Device.osInternalBuildId` | `DeviceInfoModule.fingerprint` | Android only | | `Device.osBuildFingerprint` | `DeviceInfoModule.fingerprint` | Android only | | `Device.platformApiLevel` | `DeviceInfoModule.apiLevel` | Android only | | `Device.deviceName` | `DeviceInfoModule.deviceName` | Same | | `Device.DeviceType` | `DeviceInfoModule.deviceType` | Returns string enum | | `Device.getDeviceTypeAsync()` | `DeviceInfoModule.deviceType` | Now sync | | `Device.getUptimeAsync()` | `DeviceInfoModule.getUptime()` | Now sync, returns ms | | `Device.isRootedExperimentalAsync()` | `DeviceInfoModule.isDeviceCompromised()` | Sync, broader detection | | `Device.isSideLoadingEnabledAsync()` | `DeviceInfoModule.isSideLoadingEnabled()` | Now sync, Android only | ### Migration Example **Before** (`expo-device`): ```typescript import * as Device from 'expo-device'; async function getDeviceInfo() { const deviceType = await Device.getDeviceTypeAsync(); const isRooted = await Device.isRootedExperimentalAsync(); const canSideload = await Device.isSideLoadingEnabledAsync(); return { brand: Device.brand, model: Device.modelName, yearClass: Device.deviceYearClass, totalMemory: Device.totalMemory, deviceType, isRooted, canSideload, }; } ``` **After** (`react-native-nitro-device-info`): ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function getDeviceInfo() { // All synchronous - no async/await needed! return { brand: DeviceInfoModule.brand, model: DeviceInfoModule.model, yearClass: DeviceInfoModule.deviceYearClass, totalMemory: DeviceInfoModule.totalMemory, deviceType: DeviceInfoModule.deviceType, isRooted: DeviceInfoModule.isDeviceCompromised(), canSideload: DeviceInfoModule.isSideLoadingEnabled(), }; } ``` ### APIs Not Available These `expo-device` APIs do not have direct equivalents: | expo-device API | Alternative | | ----------------------------------- | ---------------------------------- | | `Device.isDevice` | Use `!DeviceInfoModule.isEmulator` | | `Device.getPlatformFeaturesAsync()` | Not available | ### Platform-Specific Considerations #### Uptime Behavior On iOS, `getUptime()` is supported only for app-event timing: measuring elapsed time, enabling timers, or converting app-event uptime to an absolute timestamp with `startupTime`. Keep raw uptime and boot timestamps out of generic device-info payloads. See [iOS Privacy Manifest](/react-native-nitro-device-info/guide/getting-started.md#ios-privacy-manifest) for the declared purposes and transmission limits. - **expo-device**: Returns uptime in milliseconds (excludes deep sleep) - **react-native-nitro-device-info**: Returns uptime in milliseconds (excludes deep sleep) - iOS: Uses `systemUptime` - Android: Uses `uptimeMillis()` - Both platforms return consistent "active time" matching expo-device behavior #### Device Year Class Both libraries use the same Facebook algorithm for calculating device year class based on RAM and CPU specifications. The year class represents an estimated year that the device's hardware was considered high-end. #### Root/Jailbreak Detection - **expo-device**: `isRootedExperimentalAsync()` - Experimental, basic checks - **react-native-nitro-device-info**: `isDeviceCompromised()` - Comprehensive detection - Android: Checks su binaries, root apps, system properties, test-keys - iOS: Checks Cydia, jailbreak files, sandbox escape, suspicious paths *** ## Migrating from react-native-carrier-info If you're using `react-native-carrier-info` for carrier information, you can consolidate into `react-native-nitro-device-info`. ### API Migration Reference | react-native-carrier-info | react-native-nitro-device-info | Notes | | ------------------------------------------- | ---------------------------------------- | ----------------- | | `await CarrierInfo.allowsVOIP()` | `DeviceInfoModule.carrierAllowsVOIP` | Now sync property | | `await CarrierInfo.carrierName()` | `DeviceInfoModule.getCarrierSync()` | Now sync method | | `await CarrierInfo.isoCountryCode()` | `DeviceInfoModule.carrierIsoCountryCode` | Now sync property | | `await CarrierInfo.mobileCountryCode()` | `DeviceInfoModule.mobileCountryCode` | Now sync property | | `await CarrierInfo.mobileNetworkCode()` | `DeviceInfoModule.mobileNetworkCode` | Now sync property | | `await CarrierInfo.mobileNetworkOperator()` | `DeviceInfoModule.mobileNetworkOperator` | Now sync property | ### Migration Example **Before** (`react-native-carrier-info`): ```typescript import CarrierInfo from 'react-native-carrier-info'; async function getCarrierDetails() { const carrierName = await CarrierInfo.carrierName(); const allowsVOIP = await CarrierInfo.allowsVOIP(); const isoCountryCode = await CarrierInfo.isoCountryCode(); const mcc = await CarrierInfo.mobileCountryCode(); const mnc = await CarrierInfo.mobileNetworkCode(); const operator = await CarrierInfo.mobileNetworkOperator(); return { carrierName, allowsVOIP, isoCountryCode, mcc, mnc, operator }; } ``` **After** (`react-native-nitro-device-info`): ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function getCarrierDetails() { // All synchronous - no async/await needed! return { carrierName: DeviceInfoModule.getCarrierSync(), allowsVOIP: DeviceInfoModule.carrierAllowsVOIP, isoCountryCode: DeviceInfoModule.carrierIsoCountryCode, mcc: DeviceInfoModule.mobileCountryCode, mnc: DeviceInfoModule.mobileNetworkCode, operator: DeviceInfoModule.mobileNetworkOperator, }; } ``` ### Key Benefits 1. **No async/await**: All carrier properties are synchronous 2. **Single dependency**: No need to install separate carrier-info package 3. **JSI performance**: Zero-overhead native access via Nitro Modules 4. **Unified API**: Carrier info alongside 80+ other device properties ### Platform Notes - **iOS**: Uses `CTTelephonyNetworkInfo` and `CTCarrier` APIs - **Android**: Uses `TelephonyManager` APIs - **carrierAllowsVOIP**: Returns actual value on iOS, always `true` on Android (no equivalent API) - **Empty strings**: All properties return `""` when no SIM card is present ## Need Help? - [Complete API Reference](/react-native-nitro-device-info/api/device-info.md) - [Type Definitions](/react-native-nitro-device-info/api/types.md) - [Examples](/react-native-nitro-device-info/examples/basic-usage.md) - [GitHub Issues](https://github.com/l2hyunwoo/react-native-nitro-device-info/issues) --- url: /react-native-nitro-device-info/api/types.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Type Definitions Complete TypeScript type definitions for `react-native-nitro-device-info`. ## Importing Types ```typescript import type { DeviceInfo, PowerState, BatteryState, DeviceType, NavigationMode, } from 'react-native-nitro-device-info'; ``` ## Core Types ### PowerState Complete power and battery state information. ```typescript interface PowerState { /** * Battery charge level (0.0 to 1.0, or -1 when unavailable) * @example 0.75 represents 75% battery */ batteryLevel: number; /** * Current battery charging status */ batteryState: BatteryState; /** * Whether low power mode is enabled * @platform iOS only - always false on Android */ lowPowerMode: boolean; } ``` **Usage**: ```typescript const powerState: PowerState = DeviceInfoModule.getPowerState(); console.log(powerState.batteryLevel < 0 ? 'Battery: unavailable' : `Battery: ${(powerState.batteryLevel * 100).toFixed(0)}%`); console.log(`Status: ${powerState.batteryState}`); console.log(`Low Power Mode: ${powerState.lowPowerMode ? 'Yes' : 'No'}`); ``` **Fields**: - **batteryLevel**: Number from 0.0 (0%) to 1.0 (100%), or `-1` when unavailable - **batteryState**: Current charging state (see BatteryState below) - **lowPowerMode**: iOS only - indicates if Low Power Mode is enabled ### BatteryState Battery charging status. ```typescript type BatteryState = 'unknown' | 'unplugged' | 'charging' | 'full'; ``` **Values**: - **unknown**: Battery state cannot be determined - **unplugged**: Battery is discharging (not plugged in) - **charging**: Battery is currently charging - **full**: Battery is fully charged (may still be plugged in) **Usage**: ```typescript const powerState = DeviceInfoModule.getPowerState(); switch (powerState.batteryState) { case 'charging': console.log('Device is charging'); break; case 'full': console.log('Battery is full'); break; case 'unplugged': console.log('Device is running on battery'); break; case 'unknown': console.log('Battery state unknown'); break; } ``` ### NavigationMode Android navigation mode types. ```typescript type NavigationMode = 'gesture' | 'buttons' | 'twobuttons' | 'unknown'; ``` **Values**: - **gesture**: Full gesture navigation (swipe-based) - **buttons**: Traditional 3-button navigation (Back, Home, Recent) - **twobuttons**: 2-button navigation (Back, Home with swipe up) - **unknown**: Cannot determine (always returns this on iOS) **Usage**: ```typescript const navMode = DeviceInfoModule.navigationMode; switch (navMode) { case 'gesture': console.log('Device uses gesture navigation'); // Add extra bottom padding for gesture conflicts break; case 'buttons': console.log('Device uses 3-button navigation'); break; case 'twobuttons': console.log('Device uses 2-button navigation'); break; case 'unknown': console.log('Navigation mode unknown (iOS)'); break; } ``` **Platform Behavior**: - **Android API 29+**: Returns actual navigation mode - **Android API \< 29**: Returns `"buttons"` (gesture nav didn't exist) - **iOS**: Always returns `"unknown"` ### DeviceType Device category classification. ```typescript type DeviceType = | 'Handset' // Smartphone | 'Tablet' // Tablet device | 'Tv' // TV or set-top box | 'Desktop' // Desktop computer | 'GamingConsole' // Gaming console | 'unknown'; // Unknown device type ``` **Values**: - **Handset**: Standard smartphone - **Tablet**: Tablet device (iPad, Android tablets) - **Tv**: Smart TV or set-top box - **Desktop**: Desktop or laptop computer - **GamingConsole**: Gaming console - **unknown**: Device type cannot be determined **Usage**: ```typescript const deviceType: DeviceType = DeviceInfoModule.deviceType; if (deviceType === 'Tablet') { // Apply tablet-specific layout console.log('Tablet detected, using tablet layout'); } else if (deviceType === 'Handset') { // Apply phone-specific layout console.log('Phone detected, using mobile layout'); } ``` **Platform Behavior**: - **iOS**: Accurately detects iPhone, iPad, Apple TV - **Android**: Uses screen size heuristics (>= 600dp smallest width = Tablet) ## DeviceInfo Interface Import the published interface rather than copying its declaration into your app: ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; import type { DeviceInfo } from 'react-native-nitro-device-info'; const deviceInfo: DeviceInfo = DeviceInfoModule; const model: string = deviceInfo.model; const hasGms: boolean = deviceInfo.getHasGms(); ``` `DeviceInfo` is a type, not a runtime singleton. Use `DeviceInfoModule` to read values. The complete signature source is [`DeviceInfo.nitro.ts`](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/main/packages/react-native-nitro-device-info/src/DeviceInfo.nitro.ts). Check your installed release's declarations when it differs from the current website. See [DeviceInfo Module](/react-native-nitro-device-info/api/device-info.md) for return values and platform behavior. ## Usage Examples ### Type-Safe Power State ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; import type { PowerState, BatteryState } from 'react-native-nitro-device-info'; function getBatteryStatus(): string { const powerState: PowerState = DeviceInfoModule.getPowerState(); if (powerState.batteryLevel < 0) return 'Battery: unavailable'; const percentage = (powerState.batteryLevel * 100).toFixed(0); const state: BatteryState = powerState.batteryState; let statusMessage = `Battery: ${percentage}%`; if (state === 'charging') { statusMessage += ' (Charging)'; } else if (state === 'full') { statusMessage += ' (Full)'; } if (powerState.lowPowerMode) { statusMessage += ' [Low Power Mode]'; } return statusMessage; } ``` ### Type-Safe Device Type Handling ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; import type { DeviceType } from 'react-native-nitro-device-info'; function getLayoutMode(): 'mobile' | 'tablet' | 'desktop' { const deviceType: DeviceType = DeviceInfoModule.deviceType; switch (deviceType) { case 'Handset': return 'mobile'; case 'Tablet': return 'tablet'; case 'Desktop': return 'desktop'; default: return 'mobile'; // Default to mobile for unknown types } } ``` ### Custom Type Aliases You can create your own type aliases for convenience: ```typescript import type { DeviceInfo } from 'react-native-nitro-device-info'; // Alias for device info type DI = DeviceInfo; // Custom types for your app type DeviceCapabilities = { hasNotch: boolean; hasDynamicIsland: boolean; isTablet: boolean; isEmulator: boolean; }; function getDeviceCapabilities(): DeviceCapabilities { return { hasNotch: DeviceInfoModule.getHasNotch(), hasDynamicIsland: DeviceInfoModule.getHasDynamicIsland(), isTablet: DeviceInfoModule.isTablet, isEmulator: DeviceInfoModule.isEmulator, }; } ``` ## TypeScript Configuration Ensure your `tsconfig.json` is configured correctly: ```json { "compilerOptions": { "moduleResolution": "node", "esModuleInterop": true, "strict": true } } ``` ## Type Safety Benefits ### IntelliSense Support Full autocomplete for all methods and properties: ```typescript // TypeScript knows all available methods const model: string = DeviceInfoModule.model; const charging: boolean = DeviceInfoModule.getIsBatteryCharging(); ``` ### Compile-Time Error Checking ```typescript // Intentional type errors: do not copy these into working code. // @ts-expect-error Property 'invalid' does not exist const invalid = DeviceInfoModule.invalid; // @ts-expect-error Expected 1 argument, got 0 const missingThreshold = DeviceInfoModule.isLowBatteryLevel(); // @ts-expect-error Threshold must be a number const invalidThreshold = DeviceInfoModule.isLowBatteryLevel('0.2'); ``` ### Type Guards ```typescript function checkBatteryState(state: BatteryState): string { // TypeScript ensures you handle all cases switch (state) { case 'unknown': return 'Battery state unknown'; case 'unplugged': return 'Running on battery'; case 'charging': return 'Charging'; case 'full': return 'Fully charged'; // TypeScript error if any case is missing } } ``` ## Next Steps - View the [Complete API Reference](/react-native-nitro-device-info/api/device-info.md) for all available methods - Check out [Usage Examples](/react-native-nitro-device-info/examples/basic-usage.md) - Read the [Migration Guide](/react-native-nitro-device-info/api/migration.md) for upgrading from other libraries --- url: /react-native-nitro-device-info/contributing/documentation.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Contributing to Documentation The documentation site uses Rspress. Source pages are in `docs/docs/`; the configuration is `docs/rspress.config.ts`. ## Run the site From the repository root: ```bash cd docs yarn install --immutable yarn dev ``` Open the URL printed by Rspress, including the `/react-native-nitro-device-info/` base path. From the same directory, build and preview the production site: ```bash yarn build yarn preview ``` Build output is `doc_build/` inside this directory. ## Choose the right page | Content | Location | Purpose | | ------------------------------ | ------------------------------------------------- | --------------------------------------------------------- | | Installation and configuration | `guide/getting-started.md`, `guide/expo-setup.md` | Requirements, commands, and verification | | First working example | `guide/quick-start.md` | A short path from installation to use | | Reactive usage | `guide/react-hooks.md` | Polling intervals, initial values, and component patterns | | Exact API contracts | `api/` | Signatures, units, platform behavior, and errors | | Migration | `api/migration.md` | Entry points, mappings, and compatibility exceptions | | Task-specific code | `examples/` | Examples that build on the guides | These paths are relative to `docs/docs/`. Static assets belong in `docs/docs/public/`. ## Write examples readers can use - Identify the import path. Root APIs and `/compat` APIs have different names and return types. - Use `tsx` for code containing JSX. - Include imports in standalone examples. Label fragments that depend on earlier code. - Explain unavailable values, units, platform restrictions, and Promise rejection. - Keep required setup before the code that needs it. - Label intentional type errors. Do not present nonexistent members as autocomplete examples. - State measured performance with the test conditions. A synchronous return type is not a timing guarantee. Use the exported TypeScript types. The signature source is [`DeviceInfo.nitro.ts`](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/main/packages/react-native-nitro-device-info/src/DeviceInfo.nitro.ts); Swift, Kotlin, and web implementations determine platform behavior. ## Maintain availability badges Add introduction and platform badges to every new API section or grouped property row. Use the existing `rp-badge` spans from the Rspress theme. Keep the text inside each span so Markdown exports and MCP searches retain it. Check the [badge definitions and version evidence](/react-native-nitro-device-info/api/index.md#availability-badges). Confirm a published npm version and its source before replacing `Unreleased` with `Since v…`. A manifest version or declaration alone does not prove a released platform implementation. When a platform replaces a constant fallback with a real implementation, update its badge and explain the first functional release. Preserve the original API introduction version. Check the Swift, Kotlin, and web implementations separately. ## Add or change a page 1. Create or edit a Markdown file under the appropriate content directory. 2. Add new pages to both `themeConfig.nav` and `themeConfig.sidebar` in `docs/rspress.config.ts`. 3. Use content-root links such as `/guide/quick-start`, or relative Markdown links. Do not repeat the deployment base in internal links. 4. Preserve existing routes and heading anchors when possible. 5. Update related examples and both READMEs if the change affects them. 6. Build and preview the site. Check changed links and search results. English is the source language. Keep a Korean counterpart for every page under `docs/docs/ko/`, and update both locale menus when adding a page. Record `translationOf` and `sourceCommit` in Korean frontmatter. Preserve API names, commands, types, numbers, units, return values, permissions, requirements, exceptions, and explicit heading IDs. The language selector changes the path without checking for a translation; missing counterparts cause 404s. See [Korean translation maintenance](https://github.com/l2hyunwoo/react-native-nitro-device-info/blob/main/docs/I18N_PLAN.ko.md). ## AI-readable documentation Rspress generates page Markdown, `llms.txt`, and `llms-full.txt` during the site build. The MCP server bundles a separate documentation snapshot during its build. Website deployment alone does not refresh a published MCP package. Rebuild and test that package when updating its documentation corpus. Keep API names, import paths, platform fallbacks, and compatibility caveats explicit in each relevant section. Search results may contain a single section without the rest of the page. ## Deployment Pull requests that change `docs/**` run the documentation validation workflow. It builds the site and uploads an artifact for review. Changes merged to `main` trigger the deployment workflow. If publication fails, check the [Actions logs](https://github.com/l2hyunwoo/react-native-nitro-device-info/actions) and GitHub Pages settings. --- url: /react-native-nitro-device-info/examples/advanced-usage.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Advanced Usage Examples Advanced patterns and techniques for using `react-native-nitro-device-info`. ## Platform-Specific Code ### Conditional Logic Based on Platform ```typescript import { Platform } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; function getDeviceDetails() { if (Platform.OS === 'ios') { return { hasNotch: DeviceInfoModule.getHasNotch(), hasDynamicIsland: DeviceInfoModule.getHasDynamicIsland(), isDisplayZoomed: DeviceInfoModule.isDisplayZoomed, brightness: DeviceInfoModule.getBrightness(), }; } else { return { apiLevel: DeviceInfoModule.apiLevel, securityPatch: DeviceInfoModule.securityPatch, hasGms: DeviceInfoModule.getHasGms(), hasHms: DeviceInfoModule.getHasHms(), }; } } ``` ### Android-Specific Features ```typescript import { Platform } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; function getAndroidDetails() { if (Platform.OS !== 'android') { return null; } return { // API Level apiLevel: DeviceInfoModule.apiLevel, // Build Information androidId: DeviceInfoModule.androidId, securityPatch: DeviceInfoModule.securityPatch, fingerprint: DeviceInfoModule.fingerprint, // ABIs (CPU architectures) supportedAbis: DeviceInfoModule.supportedAbis, supported32BitAbis: DeviceInfoModule.supported32BitAbis, supported64BitAbis: DeviceInfoModule.supported64BitAbis, // Mobile Services hasGooglePlayServices: DeviceInfoModule.getHasGms(), hasHuaweiMobileServices: DeviceInfoModule.getHasHms(), // Device State isAirplaneMode: DeviceInfoModule.getIsAirplaneMode(), isLowRamDevice: DeviceInfoModule.isLowRamDevice, // System Features hasNfc: DeviceInfoModule.hasSystemFeature('android.hardware.nfc'), hasBluetooth: DeviceInfoModule.hasSystemFeature('android.hardware.bluetooth'), // All Available Features availableFeatures: DeviceInfoModule.systemAvailableFeatures, }; } ``` ### iOS-Specific Features ```typescript import { Platform } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; async function getIOSDetails() { if (Platform.OS !== 'ios') { return null; } return { // Display Features hasNotch: DeviceInfoModule.getHasNotch(), hasDynamicIsland: DeviceInfoModule.getHasDynamicIsland(), isDisplayZoomed: DeviceInfoModule.isDisplayZoomed, // Screen Brightness brightness: DeviceInfoModule.getBrightness(), // DeviceCheck Token (async, requires network) deviceToken: await DeviceInfoModule.getDeviceToken().catch(() => null), // Write the current IDFV to the local app-specific Keychain item syncedUniqueId: await DeviceInfoModule.syncUniqueId(), }; } ``` ## Performance Optimization ### Caching Expensive Operations ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; class DeviceInfoCache { private static cache: Map = new Map(); // Cache User-Agent (slow on iOS first call) static async getUserAgent(): Promise { if (this.cache.has('userAgent')) { return this.cache.get('userAgent'); } const userAgent = await DeviceInfoModule.getUserAgent(); this.cache.set('userAgent', userAgent); return userAgent; } // Cache IP address with TTL static async getIpAddress(ttlMs: number = 60000): Promise { const now = Date.now(); const cached = this.cache.get('ipAddress'); if (cached && (now - cached.timestamp) < ttlMs) { return cached.value; } const ipAddress = await DeviceInfoModule.getIpAddress(); this.cache.set('ipAddress', { value: ipAddress, timestamp: now }); return ipAddress; } // Use synchronous cached values when available static getIpAddressSync(): string { return DeviceInfoModule.getIpAddressSync(); } static getCarrierSync(): string { return DeviceInfoModule.getCarrierSync(); } } ``` ### Batch Async Calls ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; async function fetchAllNetworkInfo() { // Fetch multiple async values in parallel const [ipAddress, macAddress, carrier, locationEnabled, headphones] = await Promise.all([ DeviceInfoModule.getIpAddress(), DeviceInfoModule.getMacAddress(), DeviceInfoModule.getCarrier(), DeviceInfoModule.isLocationEnabled(), DeviceInfoModule.isHeadphonesConnected(), ]); return { ipAddress, macAddress, carrier, locationEnabled, headphones, }; } ``` ### Use Synchronous Variants ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; // Prefer synchronous cached variants for better performance function getNetworkInfoFast() { return { // 5-second cache, instant access ipAddress: DeviceInfoModule.getIpAddressSync(), macAddress: DeviceInfoModule.getMacAddressSync(), carrier: DeviceInfoModule.getCarrierSync(), // Cached install times firstInstallTime: DeviceInfoModule.firstInstallTimeSync, lastUpdateTime: DeviceInfoModule.lastUpdateTimeSync, // Cached connectivity isLocationEnabled: DeviceInfoModule.getIsLocationEnabled(), isHeadphonesConnected: DeviceInfoModule.getIsHeadphonesConnected(), }; } ``` ## React Hooks ### Built-in Hooks (Recommended) The library provides built-in React hooks for common reactive state monitoring. These are the recommended way to monitor device state: ```typescript import { useBatteryLevel, useBatteryLevelIsLow, usePowerState, useIsHeadphonesConnected, useIsWiredHeadphonesConnected, useIsBluetoothHeadphonesConnected, useBrightness, } from 'react-native-nitro-device-info'; function DeviceMonitor() { // Battery monitoring const batteryLevel = useBatteryLevel(); // 0.0 - 1.0 const lowBattery = useBatteryLevelIsLow(); // null or level when low const powerState = usePowerState(); // { batteryLevel, batteryState, lowPowerMode } // Audio monitoring const headphones = useIsHeadphonesConnected(); // boolean const wired = useIsWiredHeadphonesConnected(); // boolean const bluetooth = useIsBluetoothHeadphonesConnected(); // boolean // Display monitoring (iOS only) const brightness = useBrightness(); // 0.0 - 1.0 on iOS, -1 on Android return ( Battery: {batteryLevel !== null ? `${Math.round(batteryLevel * 100)}%` : 'Loading...'} Charging: {powerState.batteryState === 'charging' ? 'Yes' : 'No'} Headphones: {headphones ? 'Connected' : 'Disconnected'} {lowBattery !== null && ⚠️ Low Battery Warning!} ); } ``` For complete documentation, see the [React Hooks Guide](/react-native-nitro-device-info/guide/react-hooks.md). ### Custom Hooks for Extended Functionality For use cases not covered by the built-in hooks, you can create custom hooks: #### Custom Device Info Hook ```typescript import { useEffect, useState } from 'react'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; type DeviceInfo = { deviceId: string; brand: string; model: string; systemVersion: string; isTablet: boolean; batteryLevel: number; ipAddress?: string; }; export function useDeviceInfo(): DeviceInfo { const [ipAddress, setIpAddress] = useState(); // Sync values - instant access const deviceId = DeviceInfoModule.deviceId; const brand = DeviceInfoModule.brand; const model = DeviceInfoModule.model; const systemVersion = DeviceInfoModule.systemVersion; const isTablet = DeviceInfoModule.isTablet; const batteryLevel = DeviceInfoModule.getBatteryLevel(); // Async values - fetch on mount useEffect(() => { DeviceInfoModule.getIpAddress() .then(setIpAddress) .catch(() => setIpAddress(undefined)); }, []); return { deviceId, brand, model, systemVersion, isTablet, batteryLevel, ipAddress, }; } // Usage function MyComponent() { const deviceInfo = useDeviceInfo(); return ( Running on {deviceInfo.brand} {deviceInfo.model} ); } ``` #### Custom Battery Monitoring Hook For custom polling intervals or additional logic, you can extend the built-in hooks: ```typescript import { useEffect, useState } from 'react'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; import type { PowerState } from 'react-native-nitro-device-info'; // Custom hook with configurable polling interval export function useBatteryMonitor(intervalMs: number = 5000) { const [powerState, setPowerState] = useState( DeviceInfoModule.getPowerState() ); useEffect(() => { const interval = setInterval(() => { setPowerState(DeviceInfoModule.getPowerState()); }, intervalMs); return () => clearInterval(interval); }, [intervalMs]); return powerState; } // Usage function BatteryMonitor() { const powerState = useBatteryMonitor(5000); // Update every 5 seconds return ( Battery: {powerState.batteryLevel < 0 ? 'Unavailable' : `${(powerState.batteryLevel * 100).toFixed(0)}%`} Status: {powerState.batteryState} {powerState.lowPowerMode && Low Power Mode Active} ); } ``` #### Memory Monitoring Hook ```typescript import { useEffect, useState } from 'react'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; type MemoryInfo = { totalMemory: number; usedMemory: number; usedPercentage: number; }; export function useMemoryMonitor(intervalMs: number = 1000): MemoryInfo { const [memoryInfo, setMemoryInfo] = useState(() => { const total = DeviceInfoModule.totalMemory; const used = DeviceInfoModule.getUsedMemory(); return { totalMemory: total, usedMemory: used, usedPercentage: (used / total) * 100, }; }); useEffect(() => { const interval = setInterval(() => { const total = DeviceInfoModule.totalMemory; const used = DeviceInfoModule.getUsedMemory(); setMemoryInfo({ totalMemory: total, usedMemory: used, usedPercentage: (used / total) * 100, }); }, intervalMs); return () => clearInterval(interval); }, [intervalMs]); return memoryInfo; } // Usage function MemoryMonitor() { const memory = useMemoryMonitor(1000); // Update every second return ( Used: {(memory.usedMemory / 1024 / 1024).toFixed(0)} MB Total: {(memory.totalMemory / 1024 / 1024).toFixed(0)} MB Usage: {memory.usedPercentage.toFixed(1)}% ); } ``` ## Adaptive UI Based on Device ### Responsive Layout ```typescript import React from 'react'; import { View, StyleSheet } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; function AdaptiveLayout({ children }: { children: React.ReactNode }) { const isTablet = DeviceInfoModule.isTablet; const hasNotch = DeviceInfoModule.getHasNotch(); return ( {children} ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, tabletContainer: { padding: 32, maxWidth: 768, alignSelf: 'center', }, notchContainer: { paddingTop: 44, // Extra padding for notch }, }); ``` ### Feature Detection UI ```typescript import React from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; function FeatureAwareUI() { const hasNotch = DeviceInfoModule.getHasNotch(); const hasDynamicIsland = DeviceInfoModule.getHasDynamicIsland(); const hasCamera = DeviceInfoModule.isCameraPresent; return ( {hasDynamicIsland && ( 🏝️ Dynamic Island Detected )} {hasNotch && !hasDynamicIsland && ( 📱 Notch Detected )} {!hasCamera && ( ⚠️ No Camera Available )} ); } ``` ## Error Handling ### Graceful Async Error Handling ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; async function getDeviceInfoSafely() { const deviceInfo = { // Sync values - always available deviceId: DeviceInfoModule.deviceId, brand: DeviceInfoModule.brand, model: DeviceInfoModule.model, // Async values - may fail ipAddress: 'Unknown', carrier: 'Unknown', deviceToken: null as string | null, }; // Try to get IP address try { deviceInfo.ipAddress = await DeviceInfoModule.getIpAddress(); } catch (error) { console.warn('Failed to get IP address:', error); } // Try to get carrier try { deviceInfo.carrier = await DeviceInfoModule.getCarrier(); } catch (error) { console.warn('Failed to get carrier:', error); } // Try to get device token (iOS only, may fail) try { deviceInfo.deviceToken = await DeviceInfoModule.getDeviceToken(); } catch (error) { console.log('DeviceCheck not available:', error); } return deviceInfo; } ``` ### TypeScript Type Guards ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; import type { BatteryState } from 'react-native-nitro-device-info'; function getBatteryStatusMessage(state: BatteryState): string { switch (state) { case 'charging': return '⚡ Charging'; case 'full': return '✅ Fully Charged'; case 'unplugged': return '🔋 On Battery'; case 'unknown': return '❓ Unknown'; default: // TypeScript ensures exhaustive checking const _exhaustive: never = state; return 'Unknown'; } } function checkBattery() { const powerState = DeviceInfoModule.getPowerState(); const message = getBatteryStatusMessage(powerState.batteryState); console.log(message); } ``` ## Advanced Android Features ### Check System Features ```typescript import { Platform } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; function getAndroidCapabilities() { if (Platform.OS !== 'android') { return {}; } return { hasNfc: DeviceInfoModule.hasSystemFeature('android.hardware.nfc'), hasBluetooth: DeviceInfoModule.hasSystemFeature('android.hardware.bluetooth'), hasWifi: DeviceInfoModule.hasSystemFeature('android.hardware.wifi'), hasCamera: DeviceInfoModule.hasSystemFeature('android.hardware.camera'), hasCameraFlash: DeviceInfoModule.hasSystemFeature('android.hardware.camera.flash'), hasFingerprint: DeviceInfoModule.hasSystemFeature('android.hardware.fingerprint'), hasGps: DeviceInfoModule.hasSystemFeature('android.hardware.location.gps'), }; } ``` ### Location Providers ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function getLocationCapabilities() { const providers = DeviceInfoModule.getAvailableLocationProviders(); return { hasGps: providers.includes('gps'), hasNetwork: providers.includes('network'), hasFused: providers.includes('fused'), }; } ``` ## Complete Advanced Example ```typescript import React, { useEffect, useState } from 'react'; import { View, Text, ScrollView, StyleSheet, Platform } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; import type { PowerState } from 'react-native-nitro-device-info'; export default function AdvancedDeviceInfo() { const [asyncData, setAsyncData] = useState({ ipAddress: 'Loading...', carrier: 'Loading...', }); const [powerState, setPowerState] = useState( DeviceInfoModule.getPowerState() ); // Fetch async data on mount useEffect(() => { Promise.all([ DeviceInfoModule.getIpAddress(), DeviceInfoModule.getCarrier(), ]) .then(([ip, carrier]) => { setAsyncData({ ipAddress: ip, carrier }); }) .catch(error => { console.error('Failed to fetch async data:', error); }); }, []); // Monitor battery every 5 seconds useEffect(() => { const interval = setInterval(() => { setPowerState(DeviceInfoModule.getPowerState()); }, 5000); return () => clearInterval(interval); }, []); // Sync device info const deviceId = DeviceInfoModule.deviceId; const brand = DeviceInfoModule.brand; const model = DeviceInfoModule.model; const isTablet = DeviceInfoModule.isTablet; const totalMemory = DeviceInfoModule.totalMemory; const usedMemory = DeviceInfoModule.getUsedMemory(); // Platform-specific info const platformInfo = Platform.OS === 'ios' ? { hasNotch: DeviceInfoModule.getHasNotch(), hasDynamicIsland: DeviceInfoModule.getHasDynamicIsland(), brightness: DeviceInfoModule.getBrightness(), } : { apiLevel: DeviceInfoModule.apiLevel, hasGms: DeviceInfoModule.getHasGms(), isAirplaneMode: DeviceInfoModule.getIsAirplaneMode(), }; return (
{powerState.lowPowerMode && ( )}
{Object.entries(platformInfo).map(([key, value]) => ( ))}
); } function Section({ title, children }: { title: string; children: React.ReactNode }) { return ( {title} {children} ); } function Info({ label, value }: { label: string; value: string }) { return ( {label}: {value} ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, section: { marginBottom: 24, padding: 16, backgroundColor: '#f5f5f5', borderRadius: 8, }, sectionTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 12, }, row: { flexDirection: 'row', marginBottom: 8, }, label: { fontWeight: '600', marginRight: 8, }, value: { flex: 1, }, }); ``` ## Next Steps - Learn about [React Hooks](/react-native-nitro-device-info/guide/react-hooks.md) for reactive state monitoring - Check the [API Reference](/react-native-nitro-device-info/api/device-info.md) for all available methods - View [Type Definitions](/react-native-nitro-device-info/api/types.md) for TypeScript types - Read the [Migration Guide](/react-native-nitro-device-info/api/migration.md) for upgrading from other libraries --- url: /react-native-nitro-device-info/examples/basic-usage.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Basic Usage Examples Learn how to use `react-native-nitro-device-info` with practical examples. ## Getting Started Import the module in your component: ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; ``` ## Simple Device Information ### Accessing Device Properties The simplest way to get device information is through direct property access: ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function showDeviceInfo() { console.log('Device ID:', DeviceInfoModule.deviceId); console.log('Brand:', DeviceInfoModule.brand); console.log('Model:', DeviceInfoModule.model); console.log('OS:', DeviceInfoModule.systemName); console.log('OS Version:', DeviceInfoModule.systemVersion); } showDeviceInfo(); // Output: // Device ID: iPhone14,2 // Brand: Apple // Model: iPhone 13 Pro // OS: iOS // OS Version: 15.0 ``` ### Basic React Component ```typescript import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function DeviceInfoCard() { return ( Device Information Brand: {DeviceInfoModule.brand} Model: {DeviceInfoModule.model} Device ID: {DeviceInfoModule.deviceId} OS: {DeviceInfoModule.systemName} {DeviceInfoModule.systemVersion} ); } const styles = StyleSheet.create({ card: { padding: 16, backgroundColor: '#f5f5f5', borderRadius: 8, }, title: { fontSize: 18, fontWeight: 'bold', marginBottom: 8, }, }); ``` ## Device Capabilities ### Check Device Type ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function getDeviceCategory(): string { if (DeviceInfoModule.isTablet) { return 'This is a tablet'; } else { return 'This is a phone'; } } console.log(getDeviceCategory()); ``` ### Check for Specific Features ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; // Check if device has a notch if (DeviceInfoModule.getHasNotch()) { console.log('Device has a notch - adjust UI accordingly'); } // Check if device has Dynamic Island (iPhone 14 Pro+) if (DeviceInfoModule.getHasDynamicIsland()) { console.log('Device has Dynamic Island'); } // Check if camera is available if (DeviceInfoModule.isCameraPresent) { console.log('Camera is available'); } // Check if running in simulator/emulator if (DeviceInfoModule.isEmulator) { console.log('Running in simulator/emulator'); } ``` ## Battery Information ### Simple Battery Display ```typescript import React from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function BatteryIndicator() { const batteryLevel = DeviceInfoModule.getBatteryLevel(); const isCharging = DeviceInfoModule.getIsBatteryCharging(); const batteryText = batteryLevel < 0 ? 'Unavailable' : `${(batteryLevel * 100).toFixed(0)}%`; return ( Battery: {batteryText} {isCharging && ⚡ Charging} ); } ``` ### Battery Level Warning ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; function checkBatteryStatus() { const batteryLevel = DeviceInfoModule.getBatteryLevel(); if (batteryLevel < 0) { console.log('Battery: unavailable'); return 'unavailable'; } if (batteryLevel < 0.2) { console.warn(`Battery low: ${(batteryLevel * 100).toFixed(0)}%`); return 'low'; } else if (batteryLevel < 0.5) { console.log(`Battery moderate: ${(batteryLevel * 100).toFixed(0)}%`); return 'moderate'; } else { console.log(`Battery good: ${(batteryLevel * 100).toFixed(0)}%`); return 'good'; } } ``` ### Complete Power State ```typescript import React from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; import type { PowerState } from 'react-native-nitro-device-info'; export default function PowerStateDisplay() { const powerState: PowerState = DeviceInfoModule.getPowerState(); const batteryText = powerState.batteryLevel < 0 ? 'Unavailable' : `${(powerState.batteryLevel * 100).toFixed(0)}%`; return ( Battery: {batteryText} Status: {powerState.batteryState} {powerState.lowPowerMode && 🔋 Low Power Mode} ); } ``` ## System Resources ### Memory Usage Display ```typescript import React from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function MemoryInfo() { const totalMemory = DeviceInfoModule.totalMemory; const usedMemory = DeviceInfoModule.getUsedMemory(); const totalGB = (totalMemory / 1024 / 1024 / 1024).toFixed(1); const usedMB = (usedMemory / 1024 / 1024).toFixed(0); return ( Total RAM: {totalGB} GB App Memory Usage: {usedMB} MB ); } ``` ### Storage Information ```typescript import React from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function StorageInfo() { const totalDisk = DeviceInfoModule.totalDiskCapacity; const freeDisk = DeviceInfoModule.getFreeDiskStorage(); const totalGB = (totalDisk / 1024 / 1024 / 1024).toFixed(0); const freeGB = (freeDisk / 1024 / 1024 / 1024).toFixed(1); return ( Total Storage: {totalGB} GB Free Space: {freeGB} GB ); } ``` ## Application Information ### App Version Display ```typescript import React from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function AppVersionInfo() { const appName = DeviceInfoModule.applicationName; const version = DeviceInfoModule.version; const buildNumber = DeviceInfoModule.buildNumber; const bundleId = DeviceInfoModule.bundleId; return ( {appName} Version: {version} Build: {buildNumber} Bundle ID: {bundleId} ); } ``` ### Readable Version String ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; // Get formatted version string const version = DeviceInfoModule.readableVersion; console.log(`App version: ${version}`); // "1.2.3.42" ``` ## Network Information (Async) ### Get IP Address ```typescript import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function NetworkInfo() { const [ipAddress, setIpAddress] = useState('Loading...'); useEffect(() => { DeviceInfoModule.getIpAddress() .then(setIpAddress) .catch(() => setIpAddress('Unavailable')); }, []); return ( IP Address: {ipAddress} ); } ``` ### Get Carrier Information ```typescript import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function CarrierInfo() { const [carrier, setCarrier] = useState('Loading...'); useEffect(() => { DeviceInfoModule.getCarrier() .then(setCarrier) .catch(() => setCarrier('No SIM')); }, []); return ( Carrier: {carrier} ); } ``` ### Multiple Async Calls ```typescript import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; type NetworkState = { ipAddress: string; carrier: string; locationEnabled: boolean; }; export default function CompleteNetworkInfo() { const [networkState, setNetworkState] = useState({ ipAddress: 'Loading...', carrier: 'Loading...', locationEnabled: false, }); useEffect(() => { // Fetch all network info in parallel Promise.all([ DeviceInfoModule.getIpAddress(), DeviceInfoModule.getCarrier(), DeviceInfoModule.isLocationEnabled(), ]) .then(([ip, carrier, location]) => { setNetworkState({ ipAddress: ip, carrier: carrier, locationEnabled: location, }); }) .catch(error => { console.error('Failed to fetch network info:', error); }); }, []); return ( IP: {networkState.ipAddress} Carrier: {networkState.carrier} Location: {networkState.locationEnabled ? 'Enabled' : 'Disabled'} ); } ``` ## Complete Example App Here's a complete example combining multiple features: ```typescript import React, { useEffect, useState } from 'react'; import { View, Text, ScrollView, StyleSheet } from 'react-native'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; export default function DeviceInfoScreen() { const [ipAddress, setIpAddress] = useState('Loading...'); // Synchronous data - instant access const deviceId = DeviceInfoModule.deviceId; const brand = DeviceInfoModule.brand; const model = DeviceInfoModule.model; const systemVersion = DeviceInfoModule.systemVersion; const isTablet = DeviceInfoModule.isTablet; const batteryLevel = DeviceInfoModule.getBatteryLevel(); const totalMemory = DeviceInfoModule.totalMemory; const freeDisk = DeviceInfoModule.getFreeDiskStorage(); // Async data - fetch on mount useEffect(() => { DeviceInfoModule.getIpAddress() .then(setIpAddress) .catch(() => setIpAddress('Unavailable')); }, []); return ( Device Information Brand: {brand} Model: {model} Device ID: {deviceId} OS Version: {systemVersion} Type: {isTablet ? 'Tablet' : 'Phone'} System Status Battery: {batteryLevel < 0 ? 'Unavailable' : `${(batteryLevel * 100).toFixed(0)}%`} RAM: {(totalMemory / 1024 / 1024 / 1024).toFixed(1)} GB Free Storage: {(freeDisk / 1024 / 1024 / 1024).toFixed(1)} GB Network IP Address: {ipAddress} ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, section: { marginBottom: 24, padding: 16, backgroundColor: '#f5f5f5', borderRadius: 8, }, sectionTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 12, }, }); ``` ## Next Steps - Explore [Advanced Usage](/react-native-nitro-device-info/examples/advanced-usage.md) for more complex patterns - Learn about [React Hooks](/react-native-nitro-device-info/guide/react-hooks.md) for reactive state monitoring - Check the [API Reference](/react-native-nitro-device-info/api/device-info.md) for all available methods - View [Type Definitions](/react-native-nitro-device-info/api/types.md) for TypeScript support --- url: /react-native-nitro-device-info/guide/expo-setup.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Expo Setup If you use Expo with [Continuous Native Generation](https://docs.expo.dev/workflow/continuous-native-generation/) (`expo prebuild` / dev client), `react-native-nitro-device-info` ships **config plugins** so you can adopt it without editing `ios/` or `android/` by hand. Use an [Expo development build](https://docs.expo.dev/develop/development-builds/introduction/) or EAS Build. Expo Go does not include this native module. Choose React Native and Nitro versions compatible with your Expo SDK. ## Install ```bash npx expo install react-native-nitro-device-info react-native-nitro-modules ``` Autolinking registers the native module — for most APIs that is all you need, and you can run `npx expo prebuild` without listing any plugin. ## When you need the config plugin A few APIs read native capabilities that require a permission or an entitlement. Those are **opt-in**: the plugin only adds them when you ask, because requesting permissions you do not use can get an app rejected from the stores. Add the plugin to the `plugins` array in `app.json` (or `app.config.js`) and enable what you need: ```json { "expo": { "plugins": [ [ "react-native-nitro-device-info", { "enableSerialNumber": true } ] ] } } ``` If Expo manages your native directories, regenerate them after changing plugin options. `--clean` deletes and recreates `ios/` and `android/`; preserve manual native changes first: ```bash npx expo prebuild --clean ``` Rebuild and install the native app after prebuild, using `npx expo run:ios`, `npx expo run:android`, or EAS Build. Restarting the JavaScript server alone does not apply native changes. ### Plugin options | Option | Default | Effect | | -------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enableSerialNumber` | `false` | Declares Android `READ_PHONE_STATE`. Your app must request runtime permission separately. Android 10+ restricts serial access further, so ordinary apps generally receive `"unknown"` even after granting it. | The plugin only declares the permission; it does not request it at runtime or bypass [Android serial-number restrictions](https://developer.android.com/reference/android/os/Build#getSerial\(\)). The library caches `serialNumber` on first access, so request any required permission before reading it. ### What is NOT injected (by design) - **`getInstallReferrer()`, `getHasGms()`** — the Play Install Referrer and Google Play Services dependencies are bundled in the library's Gradle build, so the consuming app needs no manifest or Gradle change. - **Location and carrier APIs** — `getIsLocationEnabled()` and the carrier getters read global system state without requesting authorization, so they need no `Info.plist` usage-description keys. - **`isSideLoadingEnabled()`** — see below. ## `isSideLoadingEnabled()` requires manual setup `isSideLoadingEnabled()` calls `canRequestPackageInstalls()`, which only returns `true` when the app declares the Android `REQUEST_INSTALL_PACKAGES` permission. The plugin does **not** add this permission, because Google Play classifies it as a restricted permission: it is only an acceptable use when your app actually installs packages with user-initiated flows. Declaring it just to query sideloading status can fail Play review. If your app genuinely qualifies, add the permission yourself with the [`expo-build-properties`](https://docs.expo.dev/versions/latest/sdk/build-properties/) plugin or a small custom plugin, and be ready to justify it in the Play Console permissions declaration. Without the permission, `isSideLoadingEnabled()` simply returns `false`. ## Device attestation (App Attest / Play Integrity) The optional `react-native-nitro-device-integrity` package has its own config plugin. ```bash npx expo install react-native-nitro-device-integrity ``` ```json { "expo": { "plugins": [ [ "react-native-nitro-device-integrity", { "appAttest": true } ] ] } } ``` | Option | Default | Effect | | ----------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `appAttest` | `false` | Adds the iOS `com.apple.developer.devicecheck.appattest-environment` entitlement (value `development`) so `DCAppAttestService` works. | The entitlement value is always written as `development`. iOS ignores it on builds distributed through TestFlight or the App Store and uses the production environment automatically, so a single value is correct for both. :::warning App Attest also needs a portal capability The plugin writes the entitlement, but it cannot enable the App Attest capability on your App ID. Turn on **App Attest** for your App ID in the Apple Developer portal (or let EAS / Xcode automatic signing manage it). Without that capability the build fails to sign (error `0xE8008016`). ::: Play Integrity (Android) and DeviceCheck (iOS) need no entitlement or permission — only a runtime `cloudProjectNumber` for Play Integrity — so they require no config plugin. ## Verifying the result After `npx expo prebuild --clean`, you can confirm the injected settings: - `android/app/src/main/AndroidManifest.xml` contains `` when `enableSerialNumber` is on. - `ios//.entitlements` contains the `appattest-environment` key when `appAttest` is on. Running prebuild again does not duplicate these entries — the plugins are idempotent. --- url: /react-native-nitro-device-info/guide/getting-started.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Getting Started This guide will help you install and configure `react-native-nitro-device-info` in your React Native project. ## Prerequisites Before installing, ensure your project meets these requirements: - **React Native**: Use a version supported by your installed Nitro runtime. The repository examples use React Native 0.85.3; this does not establish a minimum supported version. - **iOS**: Deployment target 15.1 or higher - **Android**: minSdkVersion 24 or higher (Android 7.0 Nougat) - **Node.js**: Follow your React Native toolchain requirements. Repository development uses Node.js 22. The iOS and Android values above are this library’s native build settings. React Native or Nitro can require a higher minimum. ## Installation Install the library and its peer dependency using your preferred package manager: ```bash # npm npm install react-native-nitro-device-info react-native-nitro-modules # yarn yarn add react-native-nitro-device-info react-native-nitro-modules # pnpm pnpm add react-native-nitro-device-info react-native-nitro-modules ``` > **Important**: `react-native-nitro-modules` >=0.35.0 \<1.0.0 is required as a peer dependency for JSI bindings. ## Platform Setup ### iOS Configuration After installation, install the CocoaPods dependencies: ```sh cd ios && pod install && cd .. ``` Rebuild the iOS app after installing the pods. Restarting Metro alone does not install native code. ### iOS Privacy Manifest > **v1.9.0**: Privacy manifest bundling is available from `1.9.0` and is not included in `1.8.3`. See [PR #144](https://github.com/l2hyunwoo/react-native-nitro-device-info/pull/144). The pod packages `ios/PrivacyInfo.xcprivacy` in `NitroDeviceInfo_privacy.bundle`. CocoaPods copies this resource bundle into the app, including when Expo prebuild or EAS Build installs the pod. No privacy-specific config plugin option or manual copy into the app target is needed. The declarations follow the resource-bundle pattern used by [Expo Device](https://github.com/expo/expo/blob/5729befbfdb34e4be8880c19b3c5eff99bd04795/packages/expo-device/ios/ExpoDevice.podspec#L23), with reasons selected for the APIs this library uses: | API category | Library APIs | Declared reasons | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | File timestamp | `getFirstInstallTime()` and `getLastUpdateTime()` read metadata inside the app container. `firstInstallTimeSync` reads metadata on its first access, then returns a cached value; `lastUpdateTimeSync` returns `-1` on iOS. | `C617.1`, also used by [Expo Application](https://github.com/expo/expo/blob/5729befbfdb34e4be8880c19b3c5eff99bd04795/packages/expo-application/ios/PrivacyInfo.xcprivacy) | | Disk space | `totalDiskCapacity`, `getFreeDiskStorage()` and their legacy variants | `E174.1`, `85F4.1`, also used by [Expo FileSystem](https://github.com/expo/expo/blob/5729befbfdb34e4be8880c19b3c5eff99bd04795/packages/expo-file-system/ios/PrivacyInfo.xcprivacy) | | System boot time | `getUptime()` for elapsed time between app events or timers; `startupTime` for converting app-event uptime into an absolute timestamp | `35F9.1` for elapsed time/timers; `8FFB.1` for app-event timestamps | These reasons have [Apple-defined usage limits](https://developer.apple.com/documentation/bundleresources/describing-use-of-required-reason-api). Disk-space data is for visible storage information or storage-dependent app behavior, with restrictions on sending it off-device. On iOS, the supported uses of `getUptime()` and `startupTime` are limited to the app-event timing purposes in the table. Raw device uptime and boot timestamps must not be displayed or collected as general device information, sent off-device, or used for fingerprinting. Under `35F9.1`, only elapsed time between events within the app may be sent off-device. Under `8FFB.1`, only the resulting absolute timestamps of events within the app may be sent off-device. See the [timing API examples](/react-native-nitro-device-info/api/device-info.md#getuptime-number). Expo Device also declares `35F9.1`, but its declaration does not authorize broader usage of these APIs. The library declares no collected data or tracking of its own. Your app remains responsible for declarations covering its own data collection, tracking, and other SDKs. Do not use these APIs for device fingerprinting. After building or archiving the iOS app, verify that the app contains `NitroDeviceInfo_privacy.bundle/PrivacyInfo.xcprivacy`. Existing app-level privacy manifests can remain in place. ### Android Configuration Gradle autolinking registers the library when you rebuild your Android app. Permission-dependent APIs can still require configuration; see [Expo Setup](/react-native-nitro-device-info/guide/expo-setup.md). ### Expo apps Use a development build or EAS Build. Expo Go does not include this native module. Follow [Expo Setup](/react-native-nitro-device-info/guide/expo-setup.md) for installation, native configuration, and rebuilding. ## Verify Installation To verify the installation was successful, add this code to your app: ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; console.log('Device ID:', DeviceInfoModule.deviceId); console.log('Brand:', DeviceInfoModule.brand); console.log('System Version:', DeviceInfoModule.systemVersion); ``` If you see device information logged to the console, the installation was successful! ## Next Steps Now that you have the library installed, check out the [Quick Start](/react-native-nitro-device-info/guide/quick-start.md) guide to learn how to use it in your app. You can also: - Explore the [API Reference](/react-native-nitro-device-info/api/index.md) for all available methods - View [Examples](/react-native-nitro-device-info/examples/basic-usage.md) for common use cases - Check out the [Migration Guide](/react-native-nitro-device-info/api/migration.md) if coming from `react-native-device-info` --- url: /react-native-nitro-device-info/guide/introduction.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Introduction `react-native-nitro-device-info` reads device information from Swift and Kotlin through [Nitro Modules](https://nitro.margelo.com/). It provides synchronous properties, synchronous methods, Promise-based methods, and React hooks. ## Start with your task | Task | Read first | | -------------------------------------------- | --------------------------------------------------------------------------- | | Install in a React Native app | [Getting Started](/react-native-nitro-device-info/guide/getting-started.md) | | Install in an Expo app | [Expo Setup](/react-native-nitro-device-info/guide/expo-setup.md) | | Read device information | [Quick Start](/react-native-nitro-device-info/guide/quick-start.md) | | Update a component when device state changes | [React Hooks Guide](/react-native-nitro-device-info/guide/react-hooks.md) | | Replace `react-native-device-info` | [Migration Guide](/react-native-nitro-device-info/api/migration.md) | | Build for web or server rendering | [Web Support](/react-native-nitro-device-info/guide/web-support.md) | | Find an exact signature or platform fallback | [API Reference](/react-native-nitro-device-info/api/index.md) | | Use documentation with an AI assistant | [MCP Integration](/react-native-nitro-device-info/guide/mcp-integration.md) | ## Choose an API entry point The package has two API entry points. Their names and return types differ. ```typescript // Native API: named singleton, properties, and methods. import { DeviceInfoModule } from 'react-native-nitro-device-info'; const model = DeviceInfoModule.model; const battery = DeviceInfoModule.getBatteryLevel(); ``` ```typescript // Compatibility API: react-native-device-info-style functions. import DeviceInfo from 'react-native-nitro-device-info/compat'; async function readBattery() { return await DeviceInfo.getBatteryLevel(); } const model = DeviceInfo.getModel(); ``` The compatibility layer targets `react-native-device-info` 15.x. Review its [placeholder values and behavior differences](/react-native-nitro-device-info/api/migration.md#compat-layer-caveats) before migrating. ## Platforms and return values - **iOS**: The library's deployment target is 15.1+. - **Android**: The library's minimum SDK is API 24 (Android 7.0). - **Web**: A JavaScript fallback provides browser-derived values where available. Other APIs return placeholders; see [Web Support](/react-native-nitro-device-info/guide/web-support.md). Your React Native and Nitro versions can impose higher platform requirements. Synchronous calls return directly and run on the calling thread. They do not guarantee a particular execution time. Unsupported or unavailable values can be `"unknown"`, `-1`, `false`, or an empty collection. Check each API's contract before using a result. ## Device information and security [Local integrity checks](/react-native-nitro-device-info/api/device-integrity.md) detect root or jailbreak indicators. They are bypassable and do not prove that a device is trustworthy. For tokens that your backend verifies, use the separate, optional [`react-native-nitro-device-integrity` package](/react-native-nitro-device-info/api/device-attestation.md). For the architecture and measurement guidance, read [Why Nitro Module](/react-native-nitro-device-info/guide/why-nitro-module.md). --- url: /react-native-nitro-device-info/guide/mcp-integration.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # MCP Server for AI Integration Enable AI coding assistants like Claude, Cursor, and Copilot to access accurate react-native-nitro-device-info documentation through the MCP (Model Context Protocol) server. ## Check the documentation version and entry point The MCP package bundles API specs and Markdown when it is built. It does not fetch the latest website at runtime. Use a server release whose documented APIs match your installed library version, and verify against the installed TypeScript declarations. For AI-assisted changes, specify these details: - Installed library version and target platforms - Native root imports or `/compat` imports - Expo development build, bare React Native, or web/SSR - Whether a result can be unavailable or a Promise can reject Use `get_api` for the exact signature, then `search_docs` for setup and platform caveats. A search result can contain only part of a page. The website also provides [llms.txt](https://l2hyunwoo.github.io/react-native-nitro-device-info/llms.txt) and [llms-full.txt](https://l2hyunwoo.github.io/react-native-nitro-device-info/llms-full.txt). These follow the website build rather than an installed npm release. ## What is MCP? [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) is an open protocol by Anthropic that enables AI tools to access external data sources and tools. The MCP server for react-native-nitro-device-info allows AI assistants to: - Retrieve API declarations and documentation sections - Generate correct TypeScript code with proper types - Answer platform-specific questions (iOS vs Android) - Help troubleshoot common issues ## Quick Setup (Recommended) Run the `init` command in your React Native project to automatically configure MCP for Cursor and Claude Code: ```bash cd your-react-native-project npx @react-native-nitro-device-info/mcp-server init ``` This creates: - `.cursor/mcp.json` - Cursor IDE configuration - `.mcp.json` - Claude Code project configuration Then restart your IDE and start asking questions! ## Manual Installation ### Using npx No installation required. Configure your AI tool to run: ```bash npx @react-native-nitro-device-info/mcp-server ``` ### Global Installation ```bash npm install -g @react-native-nitro-device-info/mcp-server ``` Then run: ```bash nitro-device-info-mcp ``` ## Manual Configuration ### Claude Desktop **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` ```json { "mcpServers": { "nitro-device-info": { "command": "npx", "args": ["@react-native-nitro-device-info/mcp-server"] } } } ``` After saving, restart Claude Desktop completely (Cmd+Q, then reopen). ### Cursor IDE Create `.cursor/mcp.json` in your project root: ```json { "mcpServers": { "nitro-device-info": { "command": "npx", "args": ["@react-native-nitro-device-info/mcp-server"] } } } ``` ### Other MCP Clients For any MCP-compatible client using stdio transport: ```json { "command": "npx", "args": ["@react-native-nitro-device-info/mcp-server"], "transport": "stdio" } ``` ## Available Tools The MCP server provides three tools: | Tool | Purpose | Example Query | | ------------- | ------------------------------------- | ------------------------- | | `search_docs` | Natural language documentation search | "how to get device model" | | `get_api` | Detailed info about a specific API | "show me getBatteryLevel" | | `list_apis` | List APIs by category/platform/type | "list all network APIs" | ## Usage Examples ### Basic API Questions > "How do I get the device's battery level?" The AI will query the MCP server and provide: ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; // Get battery level (0.0 to 1.0) const batteryLevel = DeviceInfoModule.getBatteryLevel(); console.log(batteryLevel < 0 ? 'Battery: unavailable' : `Battery: ${Math.round(batteryLevel * 100)}%`); ``` ### API Discovery > "What APIs are available for network information?" ### Platform-Specific Questions > "Why does getIpAddress return empty on iOS simulator?" ### Code Generation > "Generate code to display all device info on a screen" ## Verification After configuration, verify the MCP server is working: 1. Ask your AI tool: "What tools does the nitro-device-info MCP server provide?" 2. Expected response should mention `search_docs`, `get_api`, and `list_apis` ## Troubleshooting ### Server Not Loading 1. Check Node.js version (requires v20.0.0+): ```bash node --version ``` 2. Verify npx works: ```bash npx --version ``` 3. Test server directly: ```bash npx @react-native-nitro-device-info/mcp-server --help ``` 4. Check Claude Desktop logs (macOS): ```bash tail -f ~/Library/Logs/Claude/mcp*.log ``` ### Common Issues | Issue | Cause | Solution | | ------------------- | --------------------- | ----------------------------------------- | | "command not found" | Node.js not in PATH | Reinstall Node.js or add to PATH | | "npm ERR! 404" | Package not published | Wait for npm publish or build from source | | JSON parse error | Invalid config syntax | Check for trailing commas, quotes | | Server timeout | Slow network/registry | Use global install for offline use | ## Requirements - Node.js 20.0.0 or higher - npm 10.0.0 or higher - MCP-compatible AI tool (Claude Desktop, Cursor, etc.) --- url: /react-native-nitro-device-info/guide/quick-start.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Quick Start Complete [Getting Started](/react-native-nitro-device-info/guide/getting-started.md) or [Expo Setup](/react-native-nitro-device-info/guide/expo-setup.md) and rebuild your native app first. This page uses the native API from the package root. For `react-native-device-info`-style functions, use the [`/compat` entry point](/react-native-nitro-device-info/api/migration.md). ## Read a property, call a method, await a Promise ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; // Properties: no parentheses and no await. const model = DeviceInfoModule.model; const isTablet = DeviceInfoModule.isTablet; // Synchronous methods: parentheses, no await. const batteryLevel = DeviceInfoModule.getBatteryLevel(); const hasGms = DeviceInfoModule.getHasGms(); // Promise-based methods: await inside an async function. async function readNetworkInfo() { try { const [ipAddress, carrier] = await Promise.all([ DeviceInfoModule.getIpAddress(), DeviceInfoModule.getCarrier(), ]); console.log({ ipAddress, carrier }); } catch (error) { console.error('Could not read network information', error); } } console.log({ model, isTablet, hasGms }); console.log(batteryLevel < 0 ? 'Battery: unavailable' : `Battery: ${Math.round(batteryLevel * 100)}%`); void readNetworkInfo(); ``` `getBatteryLevel()` returns `-1` when unavailable. `getHasGms()` returns `false` on iOS. Promise return types do not specify a completion deadline. ## Display changing values in React A direct getter reads a snapshot. Use a hook when the component must update as the value changes. ```tsx import { Text, View } from 'react-native'; import { DeviceInfoModule, useBatteryLevel, } from 'react-native-nitro-device-info'; export default function DeviceInfoScreen() { const batteryLevel = useBatteryLevel(); return ( Model: {DeviceInfoModule.model} OS: {DeviceInfoModule.systemVersion} Battery: {batteryLevel === null ? 'Loading or unavailable' : `${Math.round(batteryLevel * 100)}%`} ); } ``` `useBatteryLevel()` reads after mount and polls every five seconds. It returns `null` before the first reading or when the battery level is unavailable. See [React Hooks](/react-native-nitro-device-info/guide/react-hooks.md) for update intervals and other return types. ## Check units and unsupported values | Value | Unit or meaning | Check before use | | -------------------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------- | | `totalMemory`, `getUsedMemory()` | Bytes; device RAM and current app memory respectively | Availability depends on the platform | | `getBatteryLevel()` | Fraction from `0` to `1` | `-1` means unavailable | | `getBrightness()` | Fraction from `0` to `1` on iOS | `-1` on Android | | `apiLevel` | Android API level | `-1` on iOS | | `uniqueId` | iOS IDFV or Android ANDROID_ID | Can change; do not treat it as an account or permanent device identity | See [DeviceInfo Module](/react-native-nitro-device-info/api/device-info.md) for exact signatures, caching, permissions, and platform behavior. Web uses [fallback values](/react-native-nitro-device-info/guide/web-support.md). ## Next steps - [Basic Usage](/react-native-nitro-device-info/examples/basic-usage.md): examples grouped by task - [API Reference](/react-native-nitro-device-info/api/index.md): find properties, methods, hooks, and types - [Migration Guide](/react-native-nitro-device-info/api/migration.md): choose compatibility or native APIs --- url: /react-native-nitro-device-info/guide/react-hooks.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # React Hooks Guide This guide shows how to use React hooks for monitoring runtime device properties in your React Native application. ## Overview React hooks read device getters after mount and poll for updates. They clear their timers when the component unmounts. These hooks do not subscribe to native events or guarantee immediate notifications. **Benefits**: - Automatic cleanup on component unmount - Reactive updates when device state changes - Familiar React hook pattern - TypeScript support out of the box ## Installation The hooks are included with `react-native-nitro-device-info`: ```bash # npm npm install react-native-nitro-device-info react-native-nitro-modules # yarn yarn add react-native-nitro-device-info react-native-nitro-modules # Don't forget pod install for iOS cd ios && pod install ``` ## Update intervals and initial values | Root hook | Poll interval | Initial or unavailable value | | ------------------------ | ---------------- | ------------------------------------------------- | | `useBatteryLevel()` | 5 seconds | `null` | | `useBatteryLevelIsLow()` | 2 seconds | `null`; also returned when the battery is not low | | `usePowerState()` | 5 seconds | Initially `{}`; `batteryLevel` can be `-1` | | Headphone hooks | 1 second | Initially `false` | | `useBrightness()` | 500 milliseconds | Initially `null`; `-1` on Android | Timers depend on JavaScript scheduling and can be delayed in the background. A hook does not report a change at the exact moment it occurs. The examples use root imports. Headphone hooks from `/compat` instead return `{ loading, result }`; see the [Migration Guide](/react-native-nitro-device-info/api/migration.md). ## Quick Examples ### Battery Monitoring Monitor battery level with automatic re-renders: ```tsx import { useBatteryLevel, usePowerState } from 'react-native-nitro-device-info'; function BatteryWidget() { const batteryLevel = useBatteryLevel(); const powerState = usePowerState(); return ( Battery {batteryLevel !== null ? `${Math.round(batteryLevel * 100)}%` : 'Loading or unavailable'} {powerState.batteryState === 'charging' ? '⚡ Charging' : '🔋 On Battery'} ); } // Note: styles (widget, label, value, status) need to be defined in a StyleSheet ``` ### Low Battery Alerts Show warnings when battery is low: ```tsx import { useBatteryLevelIsLow } from 'react-native-nitro-device-info'; function LowBatteryAlert() { const lowBattery = useBatteryLevelIsLow(); // Only renders when battery is below threshold if (lowBattery === null) { return null; } return ( ⚠️ Low Battery: {Math.round(lowBattery * 100)}% Please connect your charger ); } // Note: styles (alert, alertText, alertHint) need to be defined in a StyleSheet ``` ### Headphone Detection Adapt your UI based on audio output: ```tsx import { useIsHeadphonesConnected, useIsWiredHeadphonesConnected, useIsBluetoothHeadphonesConnected } from 'react-native-nitro-device-info'; function AudioOutputIndicator() { const anyHeadphones = useIsHeadphonesConnected(); const wiredHeadphones = useIsWiredHeadphonesConnected(); const bluetoothHeadphones = useIsBluetoothHeadphonesConnected(); const getOutputIcon = () => { if (bluetoothHeadphones) return '🎧 Bluetooth'; if (wiredHeadphones) return '🔌 Wired'; return '🔊 Speaker'; }; return ( {getOutputIcon()} ); } ``` ### Brightness Monitoring (iOS) Track screen brightness changes: ```tsx import { useBrightness } from 'react-native-nitro-device-info'; import { Platform } from 'react-native'; function BrightnessDisplay() { const brightness = useBrightness(); if (Platform.OS === 'android') { return Brightness monitoring is iOS only; } if (brightness === null) { return Loading...; } return ( Brightness: {Math.round(brightness * 100)}% ); } // Note: styles.brightnessBar needs to be defined in a StyleSheet ``` ## Complete Example: Device Monitor Dashboard ```tsx import React from 'react'; import { View, Text, StyleSheet, ScrollView } from 'react-native'; import { useBatteryLevel, usePowerState, useBatteryLevelIsLow, useIsHeadphonesConnected, useIsWiredHeadphonesConnected, useIsBluetoothHeadphonesConnected, useBrightness, } from 'react-native-nitro-device-info'; export function DeviceMonitorDashboard() { // Battery hooks const batteryLevel = useBatteryLevel(); const powerState = usePowerState(); const lowBattery = useBatteryLevelIsLow(); // Headphone hooks const headphones = useIsHeadphonesConnected(); const wiredHeadphones = useIsWiredHeadphonesConnected(); const bluetoothHeadphones = useIsBluetoothHeadphonesConnected(); // Display hooks const brightness = useBrightness(); return ( Device Monitor {/* Battery Section */} 🔋 Battery {lowBattery !== null && ( ⚠️ Low Battery! )} {/* Audio Section */} 🎧 Audio Output {/* Display Section */} 📱 Display = 0 ? formatPercent(brightness) : 'N/A' } /> ); } function Row({ label, value }: { label: string; value: string }) { return ( {label} {value} ); } function formatPercent(value: number | null): string { if (value === null) return 'Loading...'; return `${Math.round(value * 100)}%`; } const styles = StyleSheet.create({ container: { flex: 1, padding: 16, backgroundColor: '#fff', }, title: { fontSize: 24, fontWeight: 'bold', marginBottom: 16, }, section: { marginBottom: 20, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 8, }, sectionTitle: { fontSize: 18, fontWeight: '600', marginBottom: 8, }, row: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 4, }, label: { fontWeight: '500', }, value: { color: '#666', }, warning: { backgroundColor: '#fff3cd', padding: 8, borderRadius: 4, marginTop: 8, }, warningText: { color: '#856404', }, }); ``` ## Troubleshooting ### Hook returns null indefinitely Check that the native module is properly linked: ```tsx import { DeviceInfoModule } from 'react-native-nitro-device-info'; // Debug: check if module is available console.log('DeviceInfoModule:', DeviceInfoModule); ``` ### Updates not received Ensure the app is in the foreground to receive updates from hooks. ### Brightness returns -1 This is expected on Android - brightness monitoring is iOS-only. ## See Also - [Hooks API Reference](/react-native-nitro-device-info/api/hooks.md) - Complete hook signatures and types - [Migration Guide](/react-native-nitro-device-info/api/migration.md) - Migrating from react-native-device-info - [Basic Usage Examples](/react-native-nitro-device-info/examples/basic-usage.md) - More usage examples --- url: /react-native-nitro-device-info/guide/web-support.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Web Support Since v1.8.0 Web: limited / fallback Web entry points were introduced in v1.8.0. Each [API reference section](/react-native-nitro-device-info/api/index.md#availability-badges) distinguishes browser-derived values from fixed fallbacks. `react-native-nitro-device-info` is built on [Nitro](https://nitro.margelo.com/), a JSI/native technology. A browser has no native module, so the goal on web is narrower than on native: **the package must be import-safe and return honest fallback values** — not reproduce every device API. This lets teams whose monorepo targets both native and web (react-native-web, Next.js SSR) depend on the package without their web build crashing. ## How it works The package ships a pure-JS web implementation (`DeviceInfo.web.ts`) that satisfies the full `DeviceInfo` interface. Your bundler selects it automatically — there is **no separate package to install and no import path to change**. ```ts // Same import on every platform. import { DeviceInfoModule, createDeviceInfo } from 'react-native-nitro-device-info'; ``` Selection happens through two complementary mechanisms, so it works across the common web toolchains: - **Metro / react-native-web (Expo web):** Metro resolves the `.web.ts` platform extension (`index.web.ts` is tried before `index.ts`) and also asserts the `browser` export condition for the web platform. - **webpack / Next.js:** the package's `package.json` `exports` map declares a `"browser"` condition that points at the web build, which webpack honors for `target: 'web'`. If a server bundler selects the native entry, its HybridObject is created lazily on first property access. Importing that entry does not create a HybridObject. Reading `DeviceInfoModule.model`, calling a method, or calling `createDeviceInfo()` still requires native bindings and can throw on the server. ## Hooks and compat entry Since v1.9.0 Hooks and the `/compat` entry import the `DeviceInfoModule` singleton through the package's conditional exports. Browser bundles select the web implementation without requiring `.web.js` extension priority. The root `browser` export takes precedence over `source` when both conditions are enabled. ## What is real vs. fallback The fallback returns a real value where a browser API can answer, and otherwise the same neutral constants the native side uses for an unsupported platform (`"unknown"` / `-1` / `false` / `[]`). **Values are never fabricated to look real.** ### Derived from a browser API (when available) | Member | Source | | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `systemName` | parsed from `navigator.userAgent` (`"Windows"`/`"macOS"`/`"iOS"`/`"Android"`/`"Linux"`, else `"web"`) | | `systemLanguage` | `navigator.language` | | `brand`, `manufacturer` | `navigator.vendor` | | `totalMemory` | `navigator.deviceMemory` × 1024³ (coarse, spec-bucketed; `-1` if unsupported) | | `getIsLandscape()` | `screen.width > screen.height` | | `getUserAgent()` | `navigator.userAgent` | | `getBatteryLevel()`, `getPowerState()`, `getIsBatteryCharging()` | Battery Status API (`navigator.getBattery()`), requested once; getters read the live BatteryManager; `-1` / `"unknown"` if absent or denied | | `isLowBatteryLevel(threshold)` | Compares the browser battery reading with the supplied threshold; returns `false` without a reading | When the underlying global is missing (an older browser, or a server with no `navigator`/`screen`), each of these degrades to the fallback constant rather than throwing. ### Always a fallback constant on web - All Android `Build.*` fields (`androidId`, `serialNumber`, `fingerprint`, `board`, `bootloader`, `apiLevel`, `securityPatch`, …) - Carrier / MCC / MNC information - Disk capacity and used-memory figures - Headphone, location, notch, and Dynamic Island checks - Airplane mode: `getIsAirplaneMode()` returns `false`; browsers cannot determine this state - Integrity checks — `isDeviceCompromised()` returns `false` - App metadata (`version`, `buildNumber`, `bundleId`, `applicationName`, …) - Windows-only fields (`isMouseConnected`, `hostNames`, …) ### Promise methods Methods that return a `Promise` keep their signature and **resolve** the fallback — they do not reject — so existing `await` call sites keep working: ```ts await DeviceInfoModule.getIpAddress(); // "unknown" await DeviceInfoModule.verifyDeviceIntegrity(); // false ``` The one exception is `getDeviceToken()`, which **rejects** on web. It is Apple DeviceCheck, which has no web equivalent — this mirrors its documented behavior on Android. ## SSR notes The web implementation guards browser globals and can return fallback values during server rendering. This applies only when your server bundle selects the web implementation. If the server selects the native entry, keep device reads in client-only code, such as a `useEffect`. React renders component bodies on the server; a property read in the component body can therefore trigger native initialization. Check your framework’s server resolver before reading device values during SSR. Server and browser values can differ. Render a stable loading state first if browser-derived values would otherwise cause a hydration mismatch. --- url: /react-native-nitro-device-info/guide/why-nitro-module.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # Why Nitro Module? [Nitro Modules](https://nitro.margelo.com/) connects JavaScript to native code through JSI (JavaScript Interface). This library uses a Nitro HybridObject implemented in Swift and Kotlin. ## How a call reaches native code 1. `DeviceInfo.nitro.ts` declares the properties, methods, and return types. 2. Nitrogen generates the C++, Swift, and Kotlin bindings. 3. `DeviceInfoModule` creates its native HybridObject on first access. 4. A property read or method call reaches the native implementation through those bindings. The native implementation determines whether a value is cached or queried from the operating system. ```typescript import { DeviceInfoModule } from 'react-native-nitro-device-info'; const model = DeviceInfoModule.model; // Synchronous property. const battery = DeviceInfoModule.getBatteryLevel(); // Synchronous method. async function readIpAddress() { return await DeviceInfoModule.getIpAddress(); // Promise-based method. } ``` ## Synchronous access and its limits Synchronous getters let you read values without managing a Promise. This is useful for device metadata and one-time component rendering. Synchronous work still runs on the calling thread. A getter can query the operating system or populate a cache. JSI does not guarantee that it completes within one millisecond. Do not infer call behavior from a name or from another device-info library. Use the [API Reference](/react-native-nitro-device-info/api/index.md) to check whether a member is a property, a synchronous method, or a Promise-based method. ## React hooks use polling The supplied hooks read native getters at intervals and clear their timers on unmount. They do not subscribe to native device events. For example, `useBatteryLevel()` polls every five seconds. It does not provide an immediate notification for each battery change. See the [React Hooks Guide](/react-native-nitro-device-info/guide/react-hooks.md) for all intervals. ## Migration uses a separate entry point The root export uses properties such as `DeviceInfoModule.model`. The `/compat` export provides functions such as `DeviceInfo.getModel()`. The compatibility layer targets `react-native-device-info` 15.x. Some methods return placeholders, and native platform behavior can differ. Review the [Migration Guide](/react-native-nitro-device-info/api/migration.md) before replacing imports. ## Measure in your app Use the repository's [benchmark app](https://github.com/l2hyunwoo/react-native-nitro-device-info/tree/main/example/benchmark) to compare the calls your app needs. Record the device, OS, library versions, build mode, and whether caches were warm. Measure both call latency and the effect on rendering. This documentation does not define latency guarantees or a measured speedup over other libraries. ## Next steps - [Getting Started](/react-native-nitro-device-info/guide/getting-started.md): dependencies and native setup - [Quick Start](/react-native-nitro-device-info/guide/quick-start.md): properties, methods, and React usage - [API Reference](/react-native-nitro-device-info/api/index.md): signatures and platform limitations --- url: /react-native-nitro-device-info/index.md --- > For AI agents: the complete documentation index is available at /react-native-nitro-device-info/llms.txt, the full documentation bundle is available at /react-native-nitro-device-info/llms-full.txt. # React Native Nitro Device Info > Device Info at the Speed of Nitro ⚡️ [Get Started](/guide/getting-started) | [View on GitHub](https://github.com/l2hyunwoo/react-native-nitro-device-info) ## Features - **⚡ Zero-overhead JSI**: Direct JavaScript-to-native communication with no bridge overhead - **📱 100+ Properties**: Comprehensive device information and system metrics - **📦 TypeScript-first**: Full type definitions included for excellent developer experience - **🚀 Synchronous APIs**: Read properties and synchronous methods directly; await Promise-based methods - **🌐 Cross-platform**: Works on iOS 15.1+ and Android API 24+ (Android 7.0+) - **🔄 Easy Migration**: Migrate react-native-device-info 15.x imports with the /compat entry point; review documented caveats