### Start Metro Server for Example App
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Starts the Metro bundler to serve the example application. This is necessary for running the example app on a device or simulator.
```sh
yarn example start
```
--------------------------------
### Installation and Configuration
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Instructions for installing the library and configuring it for iOS, Android, and Expo projects.
```APIDOC
## Installation
### Install the Package
```bash
# Install with blob-util for download management
yarn add react-native-ota-hot-update && yarn add react-native-blob-util
# For iOS
cd ios && pod install
```
### iOS Configuration (AppDelegate.mm)
```objective-c
#import "OtaHotUpdate.h"
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [OtaHotUpdate getBundle];
#endif
}
```
### iOS Configuration for React Native 0.77+ (AppDelegate.swift)
```swift
import react_native_ota_hot_update
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
OtaHotUpdate.getBundle()
#endif
}
```
### Android Configuration (MainApplication.kt)
```kotlin
import com.otahotupdate.OtaHotUpdate
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getJSBundleFile(): String? {
return OtaHotUpdate.bundleJS(this@MainApplication)
}
}
```
### Expo Configuration (app.json)
```json
{
"plugins": [
"react-native-ota-hot-update"
]
}
```
```
--------------------------------
### Complete Update Flow Example in TypeScript
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
This snippet demonstrates a full implementation of checking for updates, downloading new versions, and installing them with UI feedback. It requires setting up an update API endpoint and handling platform-specific download URLs. The `hotUpdate.downloadBundleUri` function is used for the download and installation process, with callbacks for progress and success/failure.
```typescript
import React, { useState, useEffect } from 'react';
import { View, Text, Button, Alert, StyleSheet } from 'react-native';
import hotUpdate from 'react-native-ota-hot-update';
import ReactNativeBlobUtil from 'react-native-blob-util';
import { Platform } from 'react-native';
const UPDATE_API = 'https://your-server.com/api/update.json';
export default function UpdateScreen() {
const [currentVersion, setCurrentVersion] = useState(0);
const [downloadProgress, setDownloadProgress] = useState(0);
const [isUpdating, setIsUpdating] = useState(false);
useEffect(() => {
hotUpdate.getCurrentVersion().then(setCurrentVersion);
}, []);
const checkAndUpdate = async () => {
try {
const response = await fetch(UPDATE_API);
const updateInfo = await response.json();
if (updateInfo.version <= currentVersion) {
Alert.alert('Up to Date', 'You have the latest version.');
return;
}
Alert.alert(
'Update Available',
`Version ${updateInfo.version} is available. ${updateInfo.releaseNotes || ''}`,
[
{ text: 'Later', style: 'cancel' },
{ text: 'Update Now', onPress: () => downloadUpdate(updateInfo) }
]
);
} catch (error) {
Alert.alert('Error', 'Failed to check for updates');
}
};
const downloadUpdate = async (updateInfo: any) => {
setIsUpdating(true);
setDownloadProgress(0);
const url = Platform.OS === 'ios'
? updateInfo.downloadIosUrl
: updateInfo.downloadAndroidUrl;
hotUpdate.downloadBundleUri(ReactNativeBlobUtil, url, updateInfo.version, {
progress: (received, total) => {
setDownloadProgress((+received / +total) * 100);
},
updateSuccess: () => {
setIsUpdating(false);
Alert.alert('Success', 'Update installed!', [
{ text: 'Restart Now', onPress: () => hotUpdate.resetApp() }
]);
},
updateFail: (message) => {
setIsUpdating(false);
Alert.alert('Update Failed', message || 'Unknown error');
},
maxBundleVersions: 3,
metadata: { releaseNotes: updateInfo.releaseNotes }
});
};
return (
Current Version: {currentVersion}
{isUpdating && (
{downloadProgress.toFixed(0)}%
)}
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 20, justifyContent: 'center' },
version: { fontSize: 18, marginBottom: 20, textAlign: 'center' },
progressContainer: { height: 20, backgroundColor: '#eee', borderRadius: 10, marginBottom: 20 },
progressBar: { height: '100%', backgroundColor: '#007AFF', borderRadius: 10 }
});
```
--------------------------------
### Run Example App on iOS
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Builds and runs the example application on an iOS simulator or device.
```sh
yarn example ios
```
--------------------------------
### Run Example App on Android
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Builds and runs the example application on an Android device or emulator.
```sh
yarn example android
```
--------------------------------
### Run Android Example with New Architecture
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Enables the new architecture for the Android example app by setting the ORG_GRADLE_PROJECT_newArchEnabled environment variable.
```sh
ORG_GRADLE_PROJECT_newArchEnabled=true yarn example android
```
--------------------------------
### Install Pods for iOS with New Architecture
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Installs CocoaPods dependencies for the iOS example app, enabling the new architecture by setting the RCT_NEW_ARCH_ENABLED environment variable.
```sh
cd example/ios
RCT_NEW_ARCH_ENABLED=1 pod install
cd -
```
--------------------------------
### Start Metro Server (npm)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/example/README.md
Use this command to start the Metro bundler, which is essential for React Native development. Ensure you are in the root directory of your project.
```bash
npm start
```
--------------------------------
### Install react-native-ota-hot-update
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Install the package using yarn and also install blob-util for download management. For iOS, navigate to the ios directory and run pod install.
```bash
yarn add react-native-ota-hot-update && yarn add react-native-blob-util
# For iOS
cd ios && pod install
```
--------------------------------
### Start Metro Server (Yarn)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/example/README.md
An alternative command to start the Metro bundler using Yarn. This is required for the development server to serve your JavaScript bundle.
```bash
yarn start
```
--------------------------------
### Get List of All Bundles
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_SERVER.md
Retrieves a list of all available OTA update bundles installed on the device.
```APIDOC
### Get List of All Bundles
```javascript
import hotUpdate from 'react-native-ota-hot-update';
const bundles = await hotUpdate.getBundleList();
console.log(`Found ${bundles.length} bundles:`);
bundles.forEach(bundle => {
console.log(`- Version ${bundle.version} (${bundle.id}) - ${bundle.isActive ? 'ACTIVE' : 'inactive'}`);
});
```
```
--------------------------------
### Install Project Dependencies with Yarn
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Run this command in the root directory to install all project dependencies using Yarn workspaces. Do not use npm for development.
```sh
yarn
```
--------------------------------
### Install with Blob Util
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Install the react-native-ota-hot-update library along with react-native-blob-util if you do not need to manage the download progress manually. Remember to run pod install for iOS.
```bash
yarn add react-native-ota-hot-update && yarn add react-native-blob-util
cd ios && pod install
```
--------------------------------
### Install Preview Release
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Install the preview version of react-native-ota-hot-update for enhanced bundle management features. This version is experimental and intended for testing.
```bash
yarn add react-native-ota-hot-update@2.4.0-rc.1
```
--------------------------------
### downloadBundleUri - Download and Install Bundle from Server
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Downloads a JavaScript bundle from a URL, extracts it, and installs it for use on the next app restart. Supports progress tracking and automatic restart.
```APIDOC
## downloadBundleUri - Download and Install Bundle from Server
Downloads a JavaScript bundle from a URL, extracts it, and installs it for use on the next app restart. This is the primary method for server-based OTA updates with support for progress tracking, version management, and automatic restart.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
import ReactNativeBlobUtil from 'react-native-blob-util';
import { Platform, Alert } from 'react-native';
// Fetch version info from your server
const checkForUpdates = async () => {
const response = await fetch('https://your-server.com/update.json');
const updateInfo = await response.json();
// Expected format: { version: 2, downloadAndroidUrl: "...", downloadIosUrl: "..." }
const currentVersion = await hotUpdate.getCurrentVersion();
if (updateInfo.version > currentVersion) {
const url = Platform.OS === 'ios'
? updateInfo.downloadIosUrl
: updateInfo.downloadAndroidUrl;
hotUpdate.downloadBundleUri(ReactNativeBlobUtil, url, updateInfo.version, {
headers: {
'Authorization': 'Bearer your-token' // Optional auth headers
},
progress: (received, total) => {
const percent = (+received / +total) * 100;
console.log(`Download progress: ${percent.toFixed(1)}%`);
},
updateSuccess: () => {
Alert.alert('Success', 'Update installed successfully!');
},
updateFail: (message) => {
Alert.alert('Update Failed', message || 'Unknown error');
},
restartAfterInstall: true,
restartDelay: 500,
maxBundleVersions: 5, // Keep up to 5 bundle versions for rollback
metadata: {
description: 'Bug fixes and performance improvements',
releaseDate: new Date().toISOString()
}
});
}
};
```
```
--------------------------------
### Download and Install Bundle from Server
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Download a JavaScript bundle from a URL, extract it, and install it for the next app restart. Supports progress tracking, version management, and automatic restarts. Requires react-native-blob-util.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
import ReactNativeBlobUtil from 'react-native-blob-util';
import { Platform, Alert } from 'react-native';
// Fetch version info from your server
const checkForUpdates = async () => {
const response = await fetch('https://your-server.com/update.json');
const updateInfo = await response.json();
// Expected format: { version: 2, downloadAndroidUrl: "...", downloadIosUrl: "..." }
const currentVersion = await hotUpdate.getCurrentVersion();
if (updateInfo.version > currentVersion) {
const url = Platform.OS === 'ios'
? updateInfo.downloadIosUrl
: updateInfo.downloadAndroidUrl;
hotUpdate.downloadBundleUri(ReactNativeBlobUtil, url, updateInfo.version, {
headers: {
'Authorization': 'Bearer your-token' // Optional auth headers
},
progress: (received, total) => {
const percent = (+received / +total) * 100;
console.log(`Download progress: ${percent.toFixed(1)}%`);
},
updateSuccess: () => {
Alert.alert('Success', 'Update installed successfully!');
},
updateFail: (message) => {
Alert.alert('Update Failed', message || 'Unknown error');
},
restartAfterInstall: true,
restartDelay: 500,
maxBundleVersions: 5, // Keep up to 5 bundle versions for rollback
metadata: {
description: 'Bug fixes and performance improvements',
releaseDate: new Date().toISOString()
}
});
}
};
```
--------------------------------
### Activate a Specific Bundle by Path
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_SERVER.md
Activates a specific OTA update bundle by providing its file path. Requires a manual app restart after setup.
```javascript
import hotUpdate from 'react-native-ota-hot-update';
// Get the bundle list
const bundles = await hotUpdate.getBundleList();
// Find and activate a specific bundle
const bundleToActivate = bundles.find(b => b.version === 3);
if (bundleToActivate && !bundleToActivate.isActive) {
const success = await hotUpdate.setupExactBundlePath(bundleToActivate.path);
if (success) {
setTimeout(() => {
hotUpdate.resetApp();
}, 300);
}
}
```
--------------------------------
### Get List of All Bundles
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_SERVER.md
Retrieves a list of all available OTA update bundles. Useful for inspecting current versions and their status.
```javascript
import hotUpdate from 'react-native-ota-hot-update';
const bundles = await hotUpdate.getBundleList();
console.log(`Found ${bundles.length} bundles:`);
bundles.forEach(bundle => {
console.log(`- Version ${bundle.version} (${bundle.id}) - ${bundle.isActive ? 'ACTIVE' : 'inactive'}`);
});
```
--------------------------------
### Example Update JSON Structure
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_SERVER.md
This JSON file specifies the download URLs for Android and iOS bundles, along with the version number. Ensure your zip file structure matches the expected format, containing the bundle and an assets folder.
```json
{
"version": 1,
"downloadAndroidUrl": "https://firebasestorage.googleapis.com/v0/b/ota-demo-68f38.appspot.com/o/index.android.bundle.zip?alt=media",
"downloadIosUrl": "https://firebasestorage.googleapis.com/v0/b/ota-demo-68f38.appspot.com/o/main.jsbundle.zip?alt=media"
}
```
--------------------------------
### Download Bundle with Custom Max Versions
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_SERVER.md
Use this to download a bundle and specify the maximum number of versions to keep. It also allows setting metadata and configuring restart behavior after installation. Ensure react-native-blob-util is installed and imported.
```javascript
import hotUpdate from 'react-native-ota-hot-update';
import ReactNativeBlobUtil from 'react-native-blob-util';
hotUpdate.downloadBundleUri(
ReactNativeBlobUtil,
'https://example.com/bundle.zip',
5,
{
maxBundleVersions: 5, // Keep up to 5 versions
metadata: {
description: 'New feature release',
releaseNotes: 'Added new UI components',
},
updateSuccess: () => {
console.log('Update successful!');
},
restartAfterInstall: true,
}
);
```
--------------------------------
### iOS Background Download Handling (AppDelegate.mm)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Implement background task management in AppDelegate.mm to ensure OTA updates can download while the app is inactive. This involves starting and ending background tasks appropriately.
```bash
- (void)applicationWillResignActive:(UIApplication *)application {
if (self.taskIdentifier != UIBackgroundTaskInvalid) {
[application endBackgroundTask:self.taskIdentifier];
self.taskIdentifier = UIBackgroundTaskInvalid;
}
__weak AppDelegate *weakSelf = self;
self.taskIdentifier = [application beginBackgroundTaskWithName:nil expirationHandler:^{
if (weakSelf) {
[application endBackgroundTask:weakSelf.taskIdentifier];
weakSelf.taskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
```
--------------------------------
### getBundleList - Get All Stored Bundles
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Retrieves a list of all stored bundle versions with their metadata. Useful for building bundle management UIs or debugging version history.
```APIDOC
## getBundleList - Get All Stored Bundles
### Description
Retrieves a list of all stored bundle versions with their metadata. Useful for building bundle management UIs or debugging version history.
### Method
`await hotUpdate.getBundleList()`
### Parameters
None
### Request Example
```typescript
import hotUpdate from 'react-native-ota-hot-update';
import type { BundleInfo } from 'react-native-ota-hot-update';
const bundles: BundleInfo[] = await hotUpdate.getBundleList();
console.log(bundles);
```
### Response
#### Success Response (200)
- **bundles** (Array) - An array of objects, where each object contains information about a stored bundle.
- **id** (string) - Unique identifier for the bundle.
- **version** (string | number) - The version number of the bundle.
- **date** (Date) - The date and time the bundle was installed.
- **path** (string) - The file path to the bundle on the device.
- **isActive** (boolean) - Indicates if this is the currently active bundle.
- **metadata** (object) - Any additional metadata associated with the bundle.
#### Response Example
```json
[
{
"id": "output_v5_2025_01_25_14_30",
"version": 5,
"date": "2025-01-25T14:30:00.000Z",
"path": "/data/user/0/com.example/files/ReactNativeOta/output_v5_2025_01_25_14_30",
"isActive": true,
"metadata": {}
},
{
"id": "output_v4_2025_01_20_10_15",
"version": 4,
"date": "2025-01-20T10:15:00.000Z",
"path": "/data/user/0/com.example/files/ReactNativeOta/output_v4_2025_01_20_10_15",
"isActive": false,
"metadata": {}
}
]
```
```
--------------------------------
### Get Stored Bundle List with getBundleList
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Retrieves a list of all stored bundle versions with their metadata. This is useful for building bundle management UIs or debugging version history. The output includes bundle ID, version, date, path, active status, and metadata.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
import type { BundleInfo } from 'react-native-ota-hot-update';
const listBundles = async () => {
const bundles: BundleInfo[] = await hotUpdate.getBundleList();
console.log(`Found ${bundles.length} bundles:`);
bundles.forEach(bundle => {
console.log(
`
ID: ${bundle.id}
Version: ${bundle.version}
Date: ${bundle.date.toLocaleString()}
Path: ${bundle.path}
Active: ${bundle.isActive ? 'YES' : 'no'}
Metadata: ${JSON.stringify(bundle.metadata)}
`
);
});
// Find the active bundle
const activeBundle = bundles.find(b => b.isActive);
if (activeBundle) {
console.log(`Active bundle: v${activeBundle.version}`);
}
return bundles;
};
// Output example:
// Found 3 bundles:
// ID: output_v5_2025_01_25_14_30, Version: 5, Active: YES
// ID: output_v4_2025_01_20_10_15, Version: 4, Active: no
// ID: output_v3_2025_01_15_09_00, Version: 3, Active: no
```
--------------------------------
### rollbackToPreviousBundle - Rollback to Previous Version
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Rolls back to the previously installed bundle version. Useful when a new update causes issues and the user needs to revert to a working version. The library automatically maintains multiple bundle versions based on `maxBundleVersions` configuration.
```APIDOC
## rollbackToPreviousBundle - Rollback to Previous Version
### Description
Rolls back to the previously installed bundle version. Useful when a new update causes issues and the user needs to revert to a working version. The library automatically maintains multiple bundle versions based on `maxBundleVersions` configuration.
### Method
`await hotUpdate.rollbackToPreviousBundle()`
### Parameters
None
### Request Example
```typescript
import hotUpdate from 'react-native-ota-hot-update';
const success = await hotUpdate.rollbackToPreviousBundle();
if (success) {
// Handle successful rollback
} else {
// Handle rollback failure
}
```
### Response
#### Success Response (200)
- **success** (boolean) - True if rollback was successful, false otherwise.
#### Response Example
```json
{
"success": true
}
```
```
--------------------------------
### setupExactBundlePath - Activate Specific Bundle
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Activates a specific bundle path, allowing you to switch between stored bundle versions without needing to download them again. This is useful for testing different versions or rolling back to a previous state.
```APIDOC
## setupExactBundlePath - Activate Specific Bundle
### Description
Sets a specific bundle path as the active bundle. Used to switch between stored bundle versions without downloading.
### Method
`hotUpdate.setupExactBundlePath(bundlePath: string): Promise`
### Parameters
#### Path Parameters
- **bundlePath** (string) - Required - The file path to the bundle to be activated.
### Request Example
```typescript
import hotUpdate from 'react-native-ota-hot-update';
const activateBundle = async (bundlePath: string) => {
const success = await hotUpdate.setupExactBundlePath(bundlePath);
// ... handle success or failure
};
```
### Response
#### Success Response (200)
- **success** (boolean) - `true` if the bundle was successfully activated, `false` otherwise.
#### Response Example
```json
{
"success": true
}
```
```
--------------------------------
### Android Configuration (MainApplication.kt)
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Configure MainApplication.kt for OTA updates on Android. This involves overriding the getJSBundleFile method to use OtaHotUpdate.bundleJS.
```kotlin
import com.otahotupdate.OtaHotUpdate
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getJSBundleFile(): String? {
return OtaHotUpdate.bundleJS(this@MainApplication)
}
}
```
--------------------------------
### Run iOS App (npm)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/example/README.md
This command initiates the build and execution of your React Native app on an iOS simulator or device. Remember to configure `ios/.xcode.env.local` if necessary.
```bash
npm run ios
```
--------------------------------
### resetApp - Restart Application
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Restarts the React Native application to apply the newly installed bundle. Should be called after a successful update installation, typically with a small delay.
```APIDOC
## resetApp - Restart Application
### Description
Restarts the React Native application to apply the newly installed bundle. Should be called after a successful update installation, typically with a small delay.
### Method
`hotUpdate.resetApp()`
### Parameters
None
### Request Example
```typescript
import hotUpdate from 'react-native-ota-hot-update';
hotUpdate.resetApp();
```
### Response
None
```
--------------------------------
### Restart Application with resetApp
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Restarts the React Native application to apply a newly installed bundle. It's recommended to call this after a successful update installation, potentially with a small delay.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
import { Alert } from 'react-native';
// Restart immediately
hotUpdate.resetApp();
// Restart after user confirmation
const promptRestart = () => {
Alert.alert(
'Update Installed',
'Restart the app to apply the update?',
[
{ text: 'Later', style: 'cancel' },
{
text: 'Restart Now',
onPress: () => {
setTimeout(() => hotUpdate.resetApp(), 300);
}
}
]
);
};
```
--------------------------------
### Publish New Versions with Release-it
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Initiates the release process using release-it, which handles version bumping, tagging, and publishing to npm.
```sh
yarn release
```
--------------------------------
### removeUpdate - Remove Current Update
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Removes the currently installed OTA update and reverts to the original bundle that was shipped with the app. Optionally restarts the app after removal.
```APIDOC
## removeUpdate - Remove Current Update
### Description
Removes the currently installed OTA update and reverts to the original bundle that was shipped with the app. Optionally restarts the app after removal.
### Method
`hotUpdate.removeUpdate(restartApp: boolean)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **restartApp** (boolean) - Required - If true, the app will restart after the update is removed. If false, the change will apply on the next app launch.
### Request Example
```typescript
// Remove update and restart
hotUpdate.removeUpdate(true);
// Remove update without restart (apply on next app launch)
hotUpdate.removeUpdate(false);
```
### Response
None
```
--------------------------------
### Clone Git Repository Command
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_GIT.md
Use this command to clone your Git repository locally. Replace `` and `OTA-bundle` with your specific details.
```bash
git clone https://github.com//OTA-bundle.git
```
--------------------------------
### Remove Current Update with removeUpdate
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Removes the currently installed OTA update and reverts to the original bundle. Optionally restarts the app after removal. Use `clearAllBundles` for a factory reset.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
// Remove update and restart
hotUpdate.removeUpdate(true);
// Remove update without restart (apply on next app launch)
hotUpdate.removeUpdate(false);
// Factory reset - remove all OTA bundles
const factoryReset = async () => {
await hotUpdate.clearAllBundles();
hotUpdate.resetApp();
};
```
--------------------------------
### Rollback to Previous Bundle with rollbackToPreviousBundle
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Rolls back to the previously installed bundle version. This is useful when a new update causes issues. The library automatically maintains multiple bundle versions based on the `maxBundleVersions` configuration.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
import { Alert } from 'react-native';
const handleRollback = async () => {
const success = await hotUpdate.rollbackToPreviousBundle();
if (success) {
Alert.alert(
'Rollback Successful',
'Previous bundle restored. Restart to apply changes.',
[ { text: 'Cancel', style: 'cancel' }, { text: 'Restart', onPress: () => hotUpdate.resetApp() } ]
);
} else {
Alert.alert('Rollback Failed', 'No previous bundle available to restore.');
}
};
```
--------------------------------
### Create Git Branches for Platforms
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_GIT.md
Optional but recommended commands to create separate Git branches for iOS and Android updates. This helps in managing platform-specific releases.
```bash
git checkout -b iOS
git push origin iOS
git checkout -b android
git push origin android
```
--------------------------------
### Git Commit and Push Commands
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_GIT.md
Commands to add, commit, and push your bundle files to the Git repository. Ensure you have staged all necessary files.
```bash
git add .
git commit -m "Initial commit with bundle files"
git push origin main
```
--------------------------------
### Activate Specific Bundle Path
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Activates a specific bundle path, allowing switching between stored versions without downloading. Requires a restart to apply changes.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
import { Alert } from 'react-native';
const activateBundle = async (bundlePath: string) => {
const success = await hotUpdate.setupExactBundlePath(bundlePath);
if (success) {
Alert.alert('Bundle Activated', 'Restart to apply the new bundle', [
{ text: 'Later', style: 'cancel' },
{ text: 'Restart', onPress: () => setTimeout(() => hotUpdate.resetApp(), 300) }
]);
} else {
Alert.alert('Error', 'Failed to activate bundle');
}
};
// Switch to a specific version from bundle list
const switchToVersion = async (targetVersion: number) => {
const bundles = await hotUpdate.getBundleList();
const targetBundle = bundles.find(b => b.version === targetVersion);
if (targetBundle && !targetBundle.isActive) {
await activateBundle(targetBundle.path);
}
};
```
--------------------------------
### iOS AppDelegate Configuration (Objective-C)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Configure your iOS AppDelegate.m file to use OtaHotUpdate.getBundle() for non-debug builds. This ensures that the app loads the bundled JS from the OTA update service.
```bash
#import "OtaHotUpdate.h"
...
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [OtaHotUpdate getBundle]; ## add this line
#endif
}
```
--------------------------------
### Get and Set Current Bundle Version
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Manage the current bundle version. getCurrentVersion retrieves the locally persisted version (defaults to 0). setCurrentVersion manually sets the version, useful for debugging or forced updates. Also includes a helper to check if an update is needed.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
// Get current version (returns number, defaults to 0)
const displayVersion = async () => {
const currentVersion = await hotUpdate.getCurrentVersion();
console.log(`Current bundle version: ${currentVersion}`);
// Output: Current bundle version: 5
};
// Manually set version (useful for debugging or forced updates)
const forceVersion = async () => {
const success = await hotUpdate.setCurrentVersion(10);
if (success) {
console.log('Version set to 10');
}
};
// Compare with server version
const checkNeedsUpdate = async (serverVersion: number) => {
const currentVersion = await hotUpdate.getCurrentVersion();
return serverVersion > currentVersion;
};
```
--------------------------------
### iOS AppDelegate Configuration (Swift)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Configure your AppDelegate.swift file for React Native 0.77 or above. Add OtaHotUpdate.getBundle() to load the JS bundle from the OTA update service in non-debug builds.
```swift
import react_native_ota_hot_update
...
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
OtaHotUpdate.getBundle() // -> Add this line
#endif
}
```
--------------------------------
### Define API Endpoint for Requesting Update Bundles
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/OTA_CMS.md
The `requestUpdateBundle` function in `api.ts` handles fetching the latest OTA update bundle from a CMS. It dynamically constructs the API endpoint based on the platform (iOS or Android) and the current app version, then makes a GET request using `axios`.
```typescript
import axios from "axios";
import DeviceInfo from "react-native-device-info";
import { Platform } from "react-native";
// Function to request the latest OTA bundle from the CMS
export async function requestUpdateBundle() {
const endpoint = Platform.OS === 'ios' ? "ios" : "androids";
const version = DeviceInfo.getVersion(); // Get the current app version
const response = await axios.get(
`http://localhost:1337/api/${endpoint}?populate=*&filters[targetVersion][$eq]=${version}&sort=id:desc`
);
return response.data;
}
```
--------------------------------
### Run Android App (npm)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/example/README.md
Execute this command to build and run your React Native application on an Android emulator or device. Ensure Metro bundler is running in a separate terminal.
```bash
npm run android
```
--------------------------------
### Update Server Configuration JSON
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
This JSON file provides version information and download URLs for OTA updates. Configure `downloadAndroidUrl` and `downloadIosUrl` to point to your bundle zip files.
```json
{
"version": 5,
"downloadAndroidUrl": "https://your-server.com/bundles/index.android.bundle.zip",
"downloadIosUrl": "https://your-server.com/bundles/main.jsbundle.zip",
"releaseNotes": "Bug fixes and performance improvements",
"mandatory": false
}
```
--------------------------------
### iOS Background Download Handling (AppDelegate.swift)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Implement background task management in AppDelegate.swift for React Native 0.77+. This includes handling applicationDidEnterBackground and applicationWillEnterForeground to manage OTA update downloads.
```swift
public override func applicationDidEnterBackground(_ application: UIApplication) {
if taskIdentifier != .invalid {
application.endBackgroundTask(taskIdentifier)
taskIdentifier = .invalid
}
taskIdentifier = application.beginBackgroundTask(withName: "OTAUpdate") { [weak self] in
if let strongSelf = self {
application.endBackgroundTask(strongSelf.taskIdentifier)
strongSelf.taskIdentifier = .invalid
}
}
}
public override func applicationWillEnterForeground(_ application: UIApplication) {
if taskIdentifier != .invalid {
application.endBackgroundTask(taskIdentifier)
taskIdentifier = .invalid
}
}
```
--------------------------------
### Run iOS App (Yarn)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/example/README.md
Launch your React Native application on iOS using Yarn. Ensure the `ios/.xcode.env.local` file is correctly configured before running.
```bash
yarn ios
```
--------------------------------
### getUpdateMetadata / setUpdateMetadata - Bundle Metadata Management
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Manages custom metadata associated with the current update. You can store and retrieve information like release notes, feature flags, or other update-specific details.
```APIDOC
## getUpdateMetadata / setUpdateMetadata - Bundle Metadata Management
### Description
Gets or sets custom metadata associated with the current update. Useful for storing release notes, feature flags, or other update-specific information.
### Methods
1. **`hotUpdate.setUpdateMetadata(metadata: object): Promise`**
2. **`hotUpdate.getUpdateMetadata(): Promise`**
### Parameters
#### `setUpdateMetadata`
- **metadata** (object) - Required - An object containing the metadata to store.
#### `getUpdateMetadata`
- **`T`** (generic type) - Optional - The expected type of the metadata object.
### Request Example (`setUpdateMetadata`)
```typescript
import hotUpdate from 'react-native-ota-hot-update';
interface UpdateMeta {
releaseNotes: string;
features: string[];
criticalUpdate: boolean;
}
const metadata: UpdateMeta = {
releaseNotes: 'Fixed login bug and improved performance',
features: ['dark-mode', 'push-notifications'],
criticalUpdate: false
};
const success = await hotUpdate.setUpdateMetadata(metadata);
console.log('Metadata stored:', success);
```
### Response Example (`getUpdateMetadata`)
```typescript
import hotUpdate from 'react-native-ota-hot-update';
interface UpdateMeta {
releaseNotes: string;
features: string[];
criticalUpdate: boolean;
}
const metadata = await hotUpdate.getUpdateMetadata();
if (metadata) {
console.log('Release notes:', metadata.releaseNotes);
console.log('Features:', metadata.features.join(', '));
if (metadata.criticalUpdate) {
console.log('This was a critical update');
}
}
```
```
--------------------------------
### iOS Configuration (AppDelegate.mm)
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Configure AppDelegate.mm for OTA updates. In debug mode, it uses the default JS bundle URL. In release mode, it retrieves the bundle URL using OtaHotUpdate.getBundle().
```objective-c
#import "OtaHotUpdate.h"
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [OtaHotUpdate getBundle];
#endif
}
```
--------------------------------
### Android MainApplication.kt Integration
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Integrate the OtaHotUpdate module into your Android project by adding the import statement and overriding the getJSBundleFile method in MainApplication.kt.
```bash
import com.otahotupdate.OtaHotUpdate
...
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
...
override fun getJSBundleFile(): String? {
return OtaHotUpdate.bundleJS(this@MainApplication)
}
...
}
```
--------------------------------
### Implement Full OTA Update Logic in useUpdateVersion Hook
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/OTA_CMS.md
This comprehensive `useUpdateVersion` hook integrates update checking and application. It defines `startUpdateBundle` to download and apply updates using `react-native-ota-hot-update`, and `checkUpdate` to query the CMS, compare versions, and prompt the user. It handles update success, failure, and progress reporting.
```typescript
import React from "react";
import HotUpdate from "react-native-ota-hot-update";
import { requestUpdateBundle } from "./api";
import { Alert } from "react-native";
import ReactNativeBlobUtil from "react-native-blob-util";
// Custom hook to check for and apply OTA updates
export const useUpdateVersion = () => {
// Function to start downloading and applying the update bundle
const startUpdateBundle = (url: string, version: number) => {
HotUpdate.downloadBundleUri(ReactNativeBlobUtil, url, version, {
updateSuccess: () => {
// Restart the app to apply the update immediately
HotUpdate.resetApp();
},
updateFail: () => {
// Log or show a message for update failure
},
restartAfterInstall: true, // Automatically restart the app after installing the update
progress: (received, total) => {
// Update UI to show download progress
},
});
};
// Function to check for updates by querying the CMS
const checkUpdate = async () => {
const bundle = await requestUpdateBundle();
const currentVersion = await HotUpdate.getCurrentVersion();
if (bundle?.data?.length) {
// Filter the latest enabled bundle from the response
const [itemVersion] = bundle.data.filter(item => item.enable);
const latestVersion = itemVersion?.id || 0; // Use the bundle ID as the version number
if (latestVersion > currentVersion) {
// Prompt the user to update the app
Alert.alert(
"New version available!",
"A new version has been released. Please update.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Update",
onPress: () =>
startUpdateBundle(
itemVersion?.attributes?.bundle?.data?.attributes?.url,
latestVersion
),
},
]
);
}
}
};
React.useEffect(() => {
if (!__DEV__) {
// Automatically check for updates when the app starts in production mode
checkUpdate();
}
}, []);
};
```
--------------------------------
### Implement Git Hot Update Check
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_GIT.md
This TypeScript code snippet demonstrates how to initiate a Git hot update check. It handles cloning or pulling changes based on the platform and provides feedback through alerts and progress updates.
```typescript
const onCheckGitVersion = () => {
hotUpdate.git.checkForGitUpdate({
branch: Platform.OS === 'ios' ? 'iOS' : 'android',
bundlePath:
Platform.OS === 'ios'
? 'output/main.jsbundle'
: 'output/index.android.bundle',
url: 'https://github.com//OTA-bundle.git',
onCloneFailed(msg: string) {
Alert.alert('Clone project failed!', msg, [
{
text: 'Cancel',
onPress: () => {},
style: 'cancel',
},
]);
},
onCloneSuccess() {
Alert.alert('Clone project success!', 'Restart to apply the changes', [
{
text: 'OK',
onPress: () => hotUpdate.resetApp(),
},
{
text: 'Cancel',
onPress: () => {},
style: 'cancel',
},
]);
},
onPullFailed(msg: string) {
Alert.alert('Pull project failed!', msg, [
{
text: 'Cancel',
onPress: () => {},
style: 'cancel',
},
]);
},
onPullSuccess() {
Alert.alert('Pull project success!', 'Restart to apply the changes', [
{
text: 'OK',
onPress: () => hotUpdate.resetApp(),
},
{
text: 'Cancel',
onPress: () => {},
style: 'cancel',
},
]);
},
onProgress(received: number, total: number) {
const percent = (+received / +total) * 100;
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setProgress(percent);
},
onFinishProgress() {
setLoading(false);
},
});
};
```
--------------------------------
### getCurrentVersion / setCurrentVersion - Version Management
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
APIs for retrieving the current bundle version and manually setting it, crucial for managing update availability.
```APIDOC
## getCurrentVersion / setCurrentVersion - Version Management
Gets or sets the current bundle version number, used to determine if updates are available. The version is persisted locally and compared against server versions to determine update availability.
```typescript
import hotUpdate from 'react-native-ota-hot-update';
// Get current version (returns number, defaults to 0)
const displayVersion = async () => {
const currentVersion = await hotUpdate.getCurrentVersion();
console.log(`Current bundle version: ${currentVersion}`);
// Output: Current bundle version: 5
};
// Manually set version (useful for debugging or forced updates)
const forceVersion = async () => {
const success = await hotUpdate.setCurrentVersion(10);
if (success) {
console.log('Version set to 10');
}
};
// Compare with server version
const checkNeedsUpdate = async (serverVersion: number) => {
const currentVersion = await hotUpdate.getCurrentVersion();
return serverVersion > currentVersion;
};
```
```
--------------------------------
### Lint Code with ESLint
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Runs ESLint to check for code style and potential errors.
```sh
yarn lint
```
--------------------------------
### Download and Apply OTA Update
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_SERVER.md
This JavaScript function uses the `react-native-ota-hot-update` library to download a new bundle from a given URL and apply it. It requires a download manager like `react-native-blob-util` and handles success and failure callbacks. Ensure you pass the correct version number for caching and future updates.
```javascript
import hotUpdate from 'react-native-ota-hot-update';
import ReactNativeBlobUtil from 'react-native-blob-util';
hotUpdate.downloadBundleUri(ReactNativeBlobUtil, url, version, {
updateSuccess: () => {
console.log('Update successful!');
},
updateFail: (message) => {
Alert.alert('Update failed!', message, [
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
]);
},
restartAfterInstall: true,
maxBundleVersions: 5, // Optional: Keep up to 5 versions (default: 2)
metadata: { // Optional: Store metadata with the bundle
description: 'New feature release',
releaseNotes: 'Added new UI components',
},
});
```
--------------------------------
### Run Unit Tests with Jest
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/CONTRIBUTING.md
Executes the unit tests defined in the project using Jest.
```sh
yarn test
```
--------------------------------
### iOS Configuration for React Native 0.77+ (AppDelegate.swift)
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Configure AppDelegate.swift for OTA updates in newer React Native versions. It conditionally loads the JS bundle URL based on the build environment.
```swift
import react_native_ota_hot_update
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
OtaHotUpdate.getBundle()
#endif
}
```
--------------------------------
### Update Options
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/DOC_OTA_SERVER.md
Configuration options for controlling the OTA update process.
```APIDOC
## `UpdateOption`
| Option | Required | Type | Description |
|-------------------------|----------|------------|--------------------------------------------------------------------------------------------------|
| `headers` | No | `Object` | Headers for downloading the bundle file (e.g., for authentication tokens). |
| `updateSuccess` | No | `Callback` | Triggered when the update is installed successfully. |
| `updateFail` | No | `Callback` | Triggered when the update fails. Passes a `message` parameter. |
| `restartAfterInstall` | No | `boolean` | Defaults to `false`. If `true`, restarts the app after a successful installation. |
| `restartDelay` | No | `number` | Time in milliseconds to wait before restarting the app after an update. Defaults: `300ms`. |
| `progress` | No | `Callback` | Reports download progress. |
| `extensionBundle` | No | `string` | Extension of the bundle file. Defaults: `.bundle` (Android), `.jsbundle` (iOS). |
| `metadata` | No | `any` | Metadata for the update. Can contain information such as version details, description, etc. |
| `maxBundleVersions` | No | `number` | Maximum number of bundle versions to keep in history. Defaults to `2`. If the number of bundles exceeds this value, older bundles will be automatically deleted. |
```
--------------------------------
### iOS Background Download Configuration (AppDelegate.h)
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Declare a UIBackgroundTaskIdentifier property in AppDelegate.h to manage background download tasks for OTA updates on iOS.
```bash
@property (nonatomic, assign) UIBackgroundTaskIdentifier taskIdentifier;
```
--------------------------------
### Android React Native 0.82+ ReactHost Configuration
Source: https://github.com/vantuan88291/react-native-ota-hot-update/blob/main/README.md
Configure the ReactHost for Android projects using React Native 0.82 or above, specifying the JS bundle file path using OtaHotUpdate.bundleJS.
```bash
override val reactHost: ReactHost by lazy {
getDefaultReactHost(
context = applicationContext,
packageList =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
},
jsBundleFilePath = OtaHotUpdate.bundleJS(applicationContext)
)
}
```
--------------------------------
### Export Android Bundle Script
Source: https://context7.com/vantuan88291/react-native-ota-hot-update/llms.txt
Use this script to create a zipped JavaScript bundle and sourcemap for Android. Ensure the output directory and zip files are handled correctly.
```json
{
"scripts": {
"export-android": "mkdir -p android/output && react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/output/index.android.bundle --assets-dest android/output --sourcemap-output android/sourcemap.js && cd android && find output -type f | zip index.android.bundle.zip -@ && zip sourcemap.zip sourcemap.js && cd .. && rm -rf android/output && rm -rf android/sourcemap.js"
}
}
```