This is a comprehensive request for a React Native boilerplate with several key requirements:
- React Native boilerplate setup
- CodePush integration for OTA (Over-The-Air) updates
- CI/CD pipeline that:
- Releases JS bundle updates on push to main
- Forces native binary build if native dependencies change
I'll create a complete solution that includes:
- React Native app structure with CodePush
- GitHub Actions CI/CD pipeline with smart detection
- Configuration files
- Helper scripts
- Documentation
Let me structure this comprehensively:
React Native CodePush OTA Boilerplate
I'll create a complete setup with intelligent CI/CD that detects native dependency changes and orchestrates appropriate builds.
1. Project Structure
my-app/
├── .github/
│ └── workflows/
│ ├── release.yml
│ ├── detect-changes.js
│ └── build-config.json
├── src/
│ ├── App.tsx
│ ├── screens/
│ ├── components/
│ └── services/
│ ├── codepush.ts
│ └── updateManager.ts
├── android/
│ ├── app/
│ └── build.gradle
├── ios/
│ ├── Podfile
│ └── Podfile.lock
├── scripts/
│ ├── codepush-release.sh
│ ├── check-native-deps.sh
│ └── bump-version.sh
├── package.json
├── app.json
└── codepush.json
2. Package.json Setup
{
"name": "my-app",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "react-native start",
"android": "react-native run-android",
"ios": "react-native run-ios",
"test": "jest",
"lint": "eslint src/",
"codepush:release": "bash scripts/codepush-release.sh",
"codepush:check": "bash scripts/check-native-deps.sh",
"version:bump": "bash scripts/bump-version.sh",
"release:precheck": "node scripts/release-precheck.js"
},
"dependencies": {
"react": "18.2.0",
"react-native": "0.73.0",
"react-native-codepush": "^8.2.2",
"react-native-gesture-handler": "^2.14.0",
"react-native-reanimated": "^3.6.0",
"@react-navigation/native": "^6.1.9",
"@react-navigation/bottom-tabs": "^6.5.11",
"axios": "^1.6.2",
"zustand": "^4.5.0"
},
"devDependencies": {
"@react-native/babel-preset": "^0.73.0",
"@react-native/metro-config": "^0.73.0",
"@types/react": "^18.2.0",
"@types/react-native": "^0.73.0",
"typescript": "^5.3.0",
"eslint": "^8.55.0",
"jest": "^29.7.0",
"detox-cli": "^20.14.0"
},
"nativeVersion": "1.0.0",
"nativeDependencies": {
"react-native-codepush": "^8.2.2",
"react-native-reanimated": "^3.6.0"
}
}
3. CodePush Configuration
app.json
{
"name": "my-app",
"displayName": "My App",
"version": "1.0.0",
"platforms": ["ios", "android"],
"codepushKey": {
"ios": "YOUR_IOS_CODEPUSH_KEY",
"android": "YOUR_ANDROID_CODEPUSH_KEY"
},
"codepushConfig": {
"ios": {
"deploymentKey": "YOUR_IOS_STAGING_KEY",
"mandatoryUpdateCheck": true
},
"android": {
"deploymentKey": "YOUR_ANDROID_STAGING_KEY",
"mandatoryUpdateCheck": true
}
}
}
codepush.json
{
"apps": [
{
"name": "my-app-ios",
"os": "ios",
"platform": "ios",
"description": "My App iOS",
"deployments": ["Staging", "Production"]
},
{
"name": "my-app-android",
"os": "android",
"platform": "android",
"description": "My App Android",
"deployments": ["Staging", "Production"]
}
],
"storeVersions": {
"ios": "1.0.0",
"android": "1.0.0"
},
"minimumRequiredVersions": {
"ios": "1.0.0",
"android": "1.0.0"
}
}
4. CodePush Service Implementation
src/services/codepush.ts
import CodePush from 'react-native-codepush';
import { Alert, AppState, AppStateStatus } from 'react-native';
import { updateStore } from './updateManager';
interface CodePushConfig {
checkFrequency?: CodePush.CheckFrequency;
installMode?: CodePush.InstallMode;
mandatoryInstallMode?: CodePush.InstallMode;
minimumBackgroundDuration?: number;
updateDialog?: boolean;
}
export class CodePushService {
private static instance: CodePushService;
private appState: AppStateStatus = 'active';
private constructor() {
this.setupAppStateListener();
}
static getInstance(): CodePushService {
if (!CodePushService.instance) {
CodePushService.instance = new CodePushService();
}
return CodePushService.instance;
}
private setupAppStateListener(): void {
AppState.addEventListener('change', this.handleAppStateChange);
}
private handleAppStateChange = (nextAppState: AppStateStatus): void => {
if (this.appState.match(/inactive|background/) && nextAppState === 'active') {
this.checkForUpdates();
}
this.appState = nextAppState;
};
async checkForUpdates(): Promise<void> {
try {
await CodePush.sync(
{
updateDialog: true,
installMode: CodePush.InstallMode.IMMEDIATE,
mandatoryInstallMode: CodePush.InstallMode.IMMEDIATE,
},
this.syncStatusDidChange,
this.codePushStatusDidChange
);
} catch (error) {
console.error('CodePush sync error:', error);
updateStore.setError('Failed to check for updates');
}
}
private syncStatusDidChange = (status: CodePush.SyncStatus): void => {
switch (status) {
case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
updateStore.setUpdateChecking(true);
break;
case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
updateStore.setDownloading(true);
break;
case CodePush.SyncStatus.INSTALLING_UPDATE:
updateStore.setInstalling(true);
break;
case CodePush.SyncStatus.UP_TO_DATE:
updateStore.setUpToDate(true);
break;
case CodePush.SyncStatus.UPDATE_IGNORED:
case CodePush.SyncStatus.UPDATE_INSTALLED:
updateStore.resetStatus();
break;
}
};
private codePushStatusDidChange = (
status: CodePush.RemotePackageState
): void => {
if (status === CodePush.RemotePackageState.UPDATE_CONFIRMED) {
updateStore.setUpdateConfirmed(true);
}
};
async rollback(): Promise<void> {
try {
await CodePush.restartApp(true);
} catch (error) {
console.error('Rollback failed:', error);
updateStore.setError('Rollback failed');
}
}
getMetadata(): void {
CodePush.getUpdateMetadata(CodePush.UpdateState.RUNNING)
.then((metadata) => {
if (metadata) {
updateStore.setCurrentVersion(metadata.label);
}
})
.catch((error) => {
console.error('Error getting metadata:', error);
});
}
async getAvailableUpdates(): Promise<CodePush.RemotePackage | null> {
try {
const update = await CodePush.checkForUpdate();
return update;
} catch (error) {
console.error('Error checking for updates:', error);
return null;
}
}
}
export default CodePushService.getInstance();
src/services/updateManager.ts
import { create } from 'zustand';
import { CodePushService } from './codepush';
interface UpdateState {
updateChecking: boolean;
downloading: boolean;
installing: boolean;
upToDate: boolean;
updateConfirmed: boolean;
error: string | null;
currentVersion: string | null;
availableUpdate: any;
setUpdateChecking: (value: boolean) => void;
setDownloading: (value: boolean) => void;
setInstalling: (value: boolean) => void;
setUpToDate: (value: boolean) => void;
setUpdateConfirmed: (value: boolean) => void;
setError: (error: string | null) => void;
setCurrentVersion: (version: string) => void;
setAvailableUpdate: (update: any) => void;
resetStatus: () => void;
checkForUpdates: () => Promise<void>;
}
export const updateStore = create<UpdateState>((set) => ({
updateChecking: false,
downloading: false,
installing: false,
upToDate: false,
updateConfirmed: false,
error: null,
currentVersion: null,
availableUpdate: null,
setUpdateChecking: (value: boolean) => set({ updateChecking: value }),
setDownloading: (value: boolean) => set({ downloading: value }),
setInstalling: (value: boolean) => set({ installing: value }),
setUpToDate: (value: boolean) => set({ upToDate: value }),
setUpdateConfirmed: (value: boolean) => set({ updateConfirmed: value }),
setError: (error: string | null) => set({ error }),
setCurrentVersion: (currentVersion: string) => set({ currentVersion }),
setAvailableUpdate: (availableUpdate: any) => set({ availableUpdate }),
resetStatus: () =>
set({
updateChecking: false,
downloading: false,
installing: false,
upToDate: false,
updateConfirmed: false,
error: null,
}),
checkForUpdates: async () => {
await CodePushService.checkForUpdates();
},
}));
5. App.tsx with CodePush Wrapper
import React, { useEffect } from 'react';
import { View, ActivityIndicator, Alert } from 'react-native';
import CodePush from 'react-native-codepush';
import CodePushService from './services/codepush';
import { updateStore } from './services/updateManager';
import Navigation from './navigation';
import UpdateNotification from './components/UpdateNotification';
interface AppProps {
isCodePushAvailable?: boolean;
}
const App: React.FC<AppProps> = () => {
const { updateChecking, downloading, installing, error } = updateStore();
useEffect(() => {
CodePushService.getMetadata();
// Check for updates when app starts
const timer = setTimeout(() => {
CodePushService.checkForUpdates();
}, 2000);
return () => clearTimeout(timer);
}, []);
return (
<View style={{ flex: 1 }}>
<Navigation />
{(updateChecking || downloading || installing) && (
<View style={styles.loadingOverlay}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
)}
{error && <Alert.alert('Update Error', error) && error}
<UpdateNotification />
</View>
);
};
const styles = {
loadingOverlay: {
position: 'absolute' as const,
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center' as const,
alignItems: 'center' as const,
},
};
const codePushOptions = {
checkFrequency: CodePush.CheckFrequency.ON_APP_START,
installMode: CodePush.InstallMode.ON_NEXT_RESTART,
mandatoryInstallMode: CodePush.InstallMode.IMMEDIATE,
updateDialog: true,
dismissOnBackButtonPress: false,
};
export default CodePush(codePushOptions)(App);
6. Update Notification Component
// src/components/UpdateNotification.tsx
import React, { useState } from 'react';
import {
Modal,
View,
Text,
TouchableOpacity,
StyleSheet,
Alert,
} from 'react-native';
import { updateStore } from '../services/updateManager';
import CodePushService from '../services/codepush';
export const UpdateNotification: React.FC = () => {
const [snoozeTime, setSnoozeTime] = useState<number | null>(null);
const { availableUpdate } = updateStore();
const handleInstallNow = async () => {
const update = await CodePushService.getAvailableUpdates();
if (update?.isMandatory) {
Alert.alert('Mandatory Update', 'This update must be installed.');
await update.install(1);
} else {
await update?.install(1);
}
};
const handleSnooze = (minutes: number) => {
setSnoozeTime(minutes * 60 * 1000);
setTimeout(() => {
updateStore.setAvailableUpdate(availableUpdate);
}, minutes * 60 * 1000);
};
if (!availableUpdate) return null;
return (
<Modal transparent visible={!!availableUpdate} animationType="fade">
<View style={styles.overlay}>
<View style={styles.container}>
<Text style={styles.title}>Update Available</Text>
<Text style={styles.version}>
Version {availableUpdate?.targetContentVersion}
</Text>
<Text style={styles.description}>
{availableUpdate?.description || 'A new update is available for your app.'}
</Text>
{availableUpdate?.isMandatory && (
<Text style={styles.mandatory}>
⚠️ This is a mandatory update
</Text>
)}
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.buttonInstall}
onPress={handleInstallNow}
>
<Text style={styles.buttonText}>Install Now</Text>
</TouchableOpacity>
{!availableUpdate?.isMandatory && (
<>
<TouchableOpacity
style={styles.buttonSnooze}
onPress={() => handleSnooze(4)}
>
<Text style={styles.buttonTextSecondary}>Snooze 4h</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonSnooze}
onPress={() => handleSnooze(24)}
>
<Text style={styles.buttonTextSecondary}>Snooze 24h</Text>
</TouchableOpacity>
</>
)}
</View>
</View>
</View>
</Modal>
);
};
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: 'rgba(0, 0, 0, 0.7)',
justifyContent: 'center',
alignItems: 'center',
},
container: {
backgroundColor: 'white',
borderRadius: 12,
padding: 20,
width: '80%',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
title: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 10,
textAlign: 'center',
},
version: {
fontSize: 14,
color: '#666',
marginBottom: 10,
textAlign: 'center',
},
description: {
fontSize: 14,
marginBottom: 15,
textAlign: 'center',
lineHeight: 20,
},
mandatory: {
fontSize: 13,
color: '#d32f2f',
marginBottom: 15,
textAlign: 'center',
fontWeight: '600',
},
buttonContainer: {
gap: 10,
},
buttonInstall: {
backgroundColor: '#007AFF',
paddingVertical: 12,
borderRadius: 8,
},
buttonSnooze: {
backgroundColor: '#f0f0f0',
paddingVertical: 12,
borderRadius: 8,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: '600',
textAlign: 'center',
},
buttonTextSecondary: {
color: '#007AFF',
fontSize: 16,
fontWeight: '600',
textAlign: 'center',
},
});
export default UpdateNotification;
7. Native Dependency Detection Script
scripts/check-native-deps.sh
#!/bin/bash
echo "🔍 Checking for native dependency changes..."
# Get the previous package.json from git
git show HEAD:package.json > /tmp/old-package.json 2>/dev/null
if [ $? -ne 0 ]; then
echo "⚠️ Initial commit or package.json not in git history. Forcing native build."
echo "NATIVE_CHANGED=true" >> $GITHUB_ENV
exit 0
fi
# Extract native dependencies from old version
old_native_deps=$(jq -r '.nativeDependencies // empty | keys[]' /tmp/old-package.json | sort)
new_native_deps=$(jq -r '.nativeDependencies // empty | keys[]' package.json | sort)
# Extract native dependency versions
for dep in $new_native_deps; do
old_version=$(jq -r ".nativeDependencies.\"$dep\" // \"\"" /tmp/old-package.json)
new_version=$(jq -r ".nativeDependencies.\"$dep\" // \"\"" package.json)
if [ "$old_version" != "$new_version" ]; then
echo "⚠️ Native dependency changed: $dep ($old_version → $new_version)"
echo "NATIVE_CHANGED=true" >> $GITHUB_ENV
exit 0
fi
done
# Check direct native packages in dependencies
native_packages=(
"react-native"
"react-native-codepush"
"react-native-reanimated"
"react-native-gesture-handler"
)
old_pkg=$(jq -r '.' /tmp/old-package.json)
new_pkg=$(jq -r '.' package.json)
for pkg in "${native_packages[@]}"; do
old_ver=$(echo "$old_pkg" | jq -r ".dependencies.\"$pkg\" // .devDependencies.\"$pkg\" // \"\"")
new_ver=$(echo "$new_pkg" | jq -r ".dependencies.\"$pkg\" // .devDependencies.\"$pkg\" // \"\"")
if [ ! -z "$old_ver" ] || [ ! -z "$new_ver" ]; then
if [ "$old_ver" != "$new_ver" ]; then
echo "⚠️ Native package version changed: $pkg ($old_ver → $new_ver)"
echo "NATIVE_CHANGED=true" >> $GITHUB_ENV
exit 0
fi
fi
done
echo "✅ No native dependencies changed. JS bundle update only."
echo "NATIVE_CHANGED=false" >> $GITHUB_ENV
# Also check if ios/Podfile.lock or android/build.gradle changes
if git diff HEAD^ HEAD --name-only | grep -E "Podfile|build.gradle|ios/.*pbxproj|android/.*gradle"; then
echo "⚠️ Native build files changed. Forcing native build."
echo "NATIVE_CHANGED=true" >> $GITHUB_ENV
exit 0
fi
exit 0
scripts/codepush-release.sh
#!/bin/bash
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${YELLOW}🚀 CodePush Release Script${NC}"
# Configuration
DEPLOYMENT_NAME="${1:-Production}"
PLATFORM="${2:-both}"
APP_NAME=$(jq -r '.name' package.json)
BUNDLE_OUTPUT_DIR="./bundle-output"
# Validate inputs
if [ "$DEPLOYMENT_NAME" != "Staging" ] && [ "$DEPLOYMENT_NAME" != "Production" ]; then
echo -e "${RED}❌ Invalid deployment: $DEPLOYMENT_NAME (must be Staging or Production)${NC}"
exit 1
fi
if [ "$PLATFORM" != "ios" ] && [ "$PLATFORM" != "android" ] && [ "$PLATFORM" != "both" ]; then
echo -e "${RED}❌ Invalid platform: $PLATFORM (must be ios, android, or both)${NC}"
exit 1
fi
# Create bundle output directory
mkdir -p $BUNDLE_OUTPUT_DIR
# Function to release to CodePush
release_to_codepush() {
local platform=$1
local app_name=$2
local deployment=$3
echo -e "${YELLOW}📦 Generating bundle for $platform...${NC}"
if [ "$platform" = "ios" ]; then
npx react-native bundle \
--entry-file index.js \
--platform ios \
--dev false \
--reset-cache \
--bundle-output "$BUNDLE_OUTPUT_DIR/main.jsbundle" \
--assets-dest "$BUNDLE_OUTPUT_DIR/assets"
APP_IDENTIFIER="${app_name}-ios"
else
npx react-native bundle \
--entry-file index.js \
--platform android \
--dev false \
--reset-cache \
--bundle-output "$BUNDLE_OUTPUT_DIR/index.android.bundle" \
--assets-dest "$BUNDLE_OUTPUT_DIR/assets"
APP_IDENTIFIER="${app_name}-android"
fi
echo -e "${YELLOW}📤 Releasing to CodePush ($deployment)...${NC}"
# Release the update
appcenter codepush release-react \
--app "$APP_IDENTIFIER" \
--deployment "${deployment}" \
--sourcemap-output "$BUNDLE_OUTPUT_DIR/main.jsbundle.map" \
--target-binary-version "1.0.0" \
--description "Release from CI/CD pipeline"
if [ $? -eq 0 ]; then
echo -e "${GREEN}✅ Successfully released to $APP_IDENTIFIER ($deployment)${NC}"
else
echo -e "${RED}❌ Failed to release to $APP_IDENTIFIER${NC}"
exit 1
fi
}
# Release based on platform
if [ "$PLATFORM" = "ios" ] || [ "$PLATFORM" = "both" ]; then
release_to_codepush "ios" "$APP_NAME" "$DEPLOYMENT_NAME"
fi
if [ "$PLATFORM" = "android" ] || [ "$PLATFORM" = "both" ]; then
release_to_codepush "android" "$APP_NAME" "$DEPLOYMENT_NAME"
fi
# Cleanup
rm -rf $BUNDLE_OUTPUT_DIR
echo -e "${GREEN}🎉 CodePush release completed successfully!${NC}"
scripts/bump-version.sh
#!/bin/bash
set -e
VERSION_TYPE="${1:-patch}"
CURRENT_VERSION=$(jq -r '.version' package.json)
echo "Current version: $CURRENT_VERSION"
# Bump version
npm version $VERSION_TYPE --no-git-tag-version
NEW_VERSION=$(jq -r '.version' package.json)
echo "New version: $NEW_VERSION"
# Update codepush.json
jq ".storeVersions.ios = \"$NEW_VERSION\" | .storeVersions.android = \"$NEW_VERSION\"" codepush.json > codepush.json.tmp
mv codepush.json.tmp codepush.json
# Update app.json
jq ".version = \"$NEW_VERSION\"" app.json > app.json.tmp
mv app.json.tmp app.json
echo "✅ Version bumped to $NEW_VERSION"
8. CI/CD Pipeline - GitHub Actions
.github/workflows/release.yml
name: Release Pipeline
on:
push:
branches:
- main
workflow_dispatch:
inputs:
deployment:
description: 'Deployment target'
required: true
default: 'Staging'
type: choice
options:
- Staging
- Production
env:
APPCENTER_CLI_VERSION: 2.14.5
NODE_VERSION: 18
XCODE_VERSION: 15.0
GRADLE_VERSION: 8.2
jobs:
detect-changes:
runs-on: ubuntu-latest
outputs:
native_changed: ${{ steps.detect.outputs.native_changed }}
should_build_native: ${{ steps.detect.outputs.should_build_native }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect native dependency changes
id: detect
run: |
# Check if package.json changed
if git diff HEAD~1 HEAD --name-only | grep -E "package.json|Podfile|build.gradle"; then
echo "Package files changed"
# Extract native dependencies
if git show HEAD~1:package.json > /tmp/old-package.json 2>/dev/null; then
old_native=$(jq -r '.nativeDependencies // empty | to_entries | map(.key + "=" + .value) | join("|")' /tmp/old-package.json)
new_native=$(jq -r '.nativeDependencies // empty | to_entries | map(.key + "=" + .value) | join("|")' package.json)
if [ "$old_native" != "$new_native" ]; then
echo "native_changed=true" >> $GITHUB_OUTPUT
echo "should_build_native=true" >> $GITHUB_OUTPUT
echo "✅ Native dependencies changed"
exit 0
fi
else
echo "native_changed=true" >> $GITHUB_OUTPUT
echo "should_build_native=true" >> $GITHUB_OUTPUT
echo "⚠️ First commit detected"
exit 0
fi
fi
echo "native_changed=false" >> $GITHUB_OUTPUT
echo "should_build_native=false" >> $GITHUB_OUTPUT
echo "✅ JS-only changes"
build-and-release:
needs: detect-changes
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm run test -- --coverage --silent
- name: Lint code
run: npm run lint
- name: Set deployment target
id: deployment
run: |
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
DEPLOYMENT="${{ github.event.inputs.deployment }}"
else
DEPLOYMENT="Staging"
fi
echo "deployment=$DEPLOYMENT" >> $GITHUB_OUTPUT
- name: Generate version info
id: version
run: |
VERSION=$(jq -r '.version' package.json)
BUILD_NUMBER=$(echo $GITHUB_RUN_NUMBER)
TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "build_number=$BUILD_NUMBER" >> $GITHUB_OUTPUT
echo "timestamp=$TIMESTAMP" >> $GITHUB_OUTPUT
- name: Create build metadata
run: |
mkdir -p build-metadata
cat > build-metadata/release.json << EOF
{
"version": "${{ steps.version.outputs.version }}",
"buildNumber": ${{ steps.version.outputs.build_number }},
"timestamp": "${{ steps.version.outputs.timestamp }}",
"deployment": "${{ steps.deployment.outputs.deployment }}",
"gitCommit": "${{ github.sha }}",
"nativeChanged": ${{ needs.detect-changes.outputs.native_changed }},
"branch": "${{ github.ref_name }}"
}
EOF
cat build-metadata/release.json
- name: Release JS Bundle to CodePush
if: ${{ needs.detect-changes.outputs.native_changed == 'false' }}
env:
APPCENTER_ACCESS_TOKEN: ${{ secrets.APPCENTER_ACCESS_TOKEN }}
run: |
npm install -g appcenter-cli@$APPCENTER_CLI_VERSION
bash scripts/codepush-release.sh ${{ steps.deployment.outputs.deployment }} both
echo "✅ JS bundle released successfully"
- name: Upload build metadata (JS-only)
if: ${{ needs.detect-changes.outputs.native_changed == 'false' }}
uses: actions/upload-artifact@v3
with:
name: build-metadata
path: build-metadata/
retention-days: 30
- name: Prepare for native build
if: ${{ needs.detect-changes.outputs.native_changed == 'true' }}
run: |
echo "🔨 Preparing for native build..."
echo "Deployment: ${{ steps.deployment.outputs.deployment }}"
- name: Dispatch native build workflow
if: ${{ needs.detect-changes.outputs.native_changed == 'true' }}
uses: actions/github-script@v7
with:
script: |
github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'native-build.yml',
ref: context.ref,
inputs: {
deployment: '${{ steps.deployment.outputs.deployment }}',
version: '${{ steps.version.outputs.version }}',
buildNumber: '${{ steps.version.outputs.build_number }}'
}
})
- name: Notify Slack - JS Release
if: ${{ success() && needs.detect-changes.outputs.native_changed == 'false' }}
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": "✅ CodePush Release Successful",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Release Completed*\n*Version:* ${{ steps.version.outputs.version }}\n*Deployment:* ${{ steps.deployment.outputs.deployment }}\n*Type:* JS Bundle Update"
}
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
- name: Notify Slack - Native Build Started
if: ${{ success() && needs.detect-changes.outputs.native_changed == 'true' }}
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": "🔨 Native Build Started",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Native Build Triggered*\n*Version:* ${{ steps.version.outputs.version }}\n*Deployment:* ${{ steps.deployment.outputs.deployment }}"
}
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
.github/workflows/native-build.yml
name: Native Build Pipeline
on:
workflow_dispatch:
inputs:
deployment:
description: 'Deployment target'
required: true
version:
description: 'App version'
required: true
buildNumber:
description: 'Build number'
required: true
env:
XCODE_VERSION: 15.0
GRADLE_VERSION: 8.2
NODE_VERSION: 18
jobs:
build-ios:
runs-on: macos-14
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.2
bundler-cache: true
- name: Setup Xcode
uses: maxim-lobanov/setup-xcode@v1
with:
xcode-version: ${{ env.XCODE_VERSION }}
- name: Install dependencies
run: npm ci
- name: Install pods
run: |
cd ios
pod install --repo-update
cd ..
- name: Build iOS app
run: |
xcodebuild \
-workspace ios/MyApp.xcworkspace \
-scheme MyApp \
-configuration Release \
-derivedDataPath build \
-archivePath build/MyApp.xcarchive \
archive
xcodebuild \
-exportArchive \
-archivePath build/MyApp.xcarchive \
-exportOptionsPlist ios/ExportOptions.plist \
-exportPath build/ios_ipa
env:
XCODE_PROJECT: ios/MyApp.xcodeproj
- name: Upload iOS build
uses: actions/upload-artifact@v3
with:
name: ios-build-${{ github.run_number }}
path: build/ios_ipa/
retention-days: 30
- name: Notify Slack
if: success()
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": "✅ iOS Build Completed",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*iOS Build Successful*\n*Version:* ${{ inputs.version }}\n*Build:* ${{ inputs.buildNumber }}"
}
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
build-android:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: gradle
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build Android app
run: |
cd android
./gradlew assembleRelease bundleRelease \
-PMYAPP_UPLOAD_STORE_PASSWORD='${{ secrets.ANDROID_KEYSTORE_PASSWORD }}' \
-PMYAPP_UPLOAD_KEY_PASSWORD='${{ secrets.ANDROID_KEY_PASSWORD }}'
cd ..
- name: Sign Android APK
run: |
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 -d > keystore.jks
jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 \
-keystore keystore.jks \
-storepass ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} \
-keypass ${{ secrets.ANDROID_KEY_PASSWORD }} \
android/app/build/outputs/apk/release/app-release.apk \
MyApp
- name: Upload Android build
uses: actions/upload-artifact@v3
with:
name: android-build-${{ github.run_number }}
path: |
android/app/build/outputs/apk/release/
android/app/build/outputs/bundle/release/
retention-days: 30
- name: Notify Slack
if: success()
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": "✅ Android Build Completed",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Android Build Successful*\n*Version:* ${{ inputs.version }}\n*Build:* ${{ inputs.buildNumber }}"
}
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
run-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run unit tests
run: npm run test -- --coverage
- name: Upload coverage reports
uses: codecov/codecov-action@v3
with:
files: ./coverage/coverage-final.json
9. GitHub Secrets Configuration
# Required secrets to set in GitHub Settings:
# CodePush/AppCenter credentials
APPCENTER_ACCESS_TOKEN=<your-appcenter-token>
# iOS signing
APPLE_ID=<your-apple-id>
APPLE_PASSWORD=<your-app-specific-password>
FASTLANE_USER=<fastlane-user>
FASTLANE_PASSWORD=<fastlane-password>
# Android signing
ANDROID_KEYSTORE_BASE64=<base64-encoded-keystore>
ANDROID_KEYSTORE_PASSWORD=<keystore-password>
ANDROID_KEY_PASSWORD=<key-password>
# Slack notifications
SLACK_WEBHOOK_URL=<your-slack-webhook>
10. Setup Instructions
# 1. Install dependencies
npm install
# 2. Initialize CodePush
npm install -g appcenter-cli
appcenter login
# 3. Create CodePush apps
appcenter apps create --platform react-native --os ios --name my-app-ios
appcenter apps create --platform react-native --os android --name my-app-android
# 4. Setup deployment keys
appcenter codepush deployment add -a <owner>/<app-name> Staging
appcenter codepush deployment add -a <owner>/<app-name> Production
# 5. Configure GitHub secrets
# Set all required secrets in your GitHub repository
# 6. Link your app to CodePush
npx react-native link react-native-codepush
# 7. Test locally
npm run android
# or
npm run ios
# 8. Manual CodePush release (optional)
npm run codepush:release
11. How It Works
┌─ Push to main ──────────────────────────────────────┐
│ │
├─ Detect Changes ────────────────────────────────────┤
│ ✓ Check for native dependency changes │
│ ✓ Compare package.json versions │
│ ✓ Check native build files (Podfile, build.gradle) │
│ │
├─ If JS-only changes: ──────────────────────────────┤
│ ✓ Run tests & lint │
│ ✓ Generate JS bundle │
│ ✓ Release to CodePush (fast ⚡) │
│ ✓ Notify Slack │
│ └─ Updates available in ~1-2 minutes │
│ │
├─ If native changes detected: ──────────────────────┤
│ ✓ Run tests & lint │
│ ✓ Trigger native build workflow │
│ ✓ Build iOS binary (Xcode) │
│ ✓ Build Android binary (Gradle) │
│ ✓ Upload to artifacts/store (requires review) │
│ └─ Requires manual release to stores │
│ │
└──────────────────────────────────────────────────────┘
This complete boilerplate provides:
✅ Intelligent CI/CD - Automatically detects native vs JS changes
✅ Fast OTA Updates - CodePush for instant JS bundle releases
✅ Native Build Automation - Apple & Google Play Store ready
✅ Error Handling - Rollback and mandatory update support
✅ Notifications - Slack integration for build status
✅ Versioning - Automated version bumping and tracking
✅ Security - GitHub secrets for signing credentials