●PLAY — Google Play's target API level 36 requirement took effect yesterday, August 31. From today, new apps and updates must target Android 16●VISIBILITY — Apps still on API 35 stay listed but disappear for users on newer Android versions. No error is raised; new installs simply fade, which makes the change easy to miss●EXTENSION — If you missed the deadline, an extension through November 1, 2026 can be requested in Play Console — best filed alongside a concrete migration plan●APPLE — On the Apple side, the event lands September 9 and iOS 27 is reported to ship September 14. Testing generated apps on iOS 27 hardware before release week is time well spent●EXPO — Expo released expo-paste-input on August 28, a native module that brings image, GIF, and sticker paste to React Native TextInput●EAS — EAS Observe reached general availability on August 20, putting crash and performance monitoring on the same EAS platform as builds and updates●PLAY — Google Play's target API level 36 requirement took effect yesterday, August 31. From today, new apps and updates must target Android 16●VISIBILITY — Apps still on API 35 stay listed but disappear for users on newer Android versions. No error is raised; new installs simply fade, which makes the change easy to miss●EXTENSION — If you missed the deadline, an extension through November 1, 2026 can be requested in Play Console — best filed alongside a concrete migration plan●APPLE — On the Apple side, the event lands September 9 and iOS 27 is reported to ship September 14. Testing generated apps on iOS 27 hardware before release week is time well spent●EXPO — Expo released expo-paste-input on August 28, a native module that brings image, GIF, and sticker paste to React Native TextInput●EAS — EAS Observe reached general availability on August 20, putting crash and performance monitoring on the same EAS platform as builds and updates
Rork Max × Expo Modules API: Building and Distributing Custom Native Modules
Learn how to design, implement, test, and publish custom native modules using the Expo Modules API. Extend Rork Max with platform-specific features using Swift and Kotlin.
Rork Max covers a remarkable range of app development needs through AI-powered code generation and the Expo ecosystem. However, when building production-grade applications, you'll inevitably encounter situations where existing libraries fall short.
Accessing proprietary hardware sensors, building high-performance bridges to specific OS APIs, or wrapping third-party SDKs — these scenarios demand writing native code directly. The Expo Modules API provides a modern, elegant solution to this challenge.
Compared to the legacy React Native Bridge, the Expo Modules API delivers significant improvements in type safety, performance, and developer experience.
We'll build a small accelerometer module and follow it all the way through: Swift and Kotlin implementations, the TypeScript layer, testing, and npm publication. Toward the end I've also written up the design traps I only discovered after running the module on a real device.
Who this article is for:
Developers who have shipped (or are about to ship) a Rork Max app
React Native developers ready to dive into native platform extensions
Anyone wanting to publish reusable native modules as npm packages
Expo Modules API Architecture and Design Philosophy
How It Differs from the Legacy Bridge
The traditional React Native Bridge relied on JSON serialization for JavaScript-to-native communication. While flexible, this approach had fundamental limitations.
Legacy Bridge issues:
Performance overhead from asynchronous JSON serialization
No type safety (prone to runtime errors)
Different implementation patterns required for iOS and Android
Expo Modules API solutions:
Synchronous communication via JSI (JavaScript Interface) for better performance
Type-safe design that leverages native Swift/Kotlin types directly
Unified, declarative API across both platforms
// Legacy Bridge — asynchronous communication via JSON// NativeModules.MyModule.doSomething(callback)// Expo Modules API — synchronous JSI-based callsimport { requireNativeModule } from 'expo-modules-core';const MyModule = requireNativeModule('MyModule');const result = MyModule.doSomething(); // Synchronous result
Module Lifecycle
Modules built with the Expo Modules API follow this lifecycle:
Registration: Automatic module discovery via expo-module.config.json
Definition: Module definition by extending the Module class in Swift/Kotlin
Linking: Expo's autolinking integrates the module into native projects automatically
Runtime: Direct invocation from JavaScript through JSI
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Understand the Expo Modules API architecture and implement modules in Swift and Kotlin from scratch
✦Apply unit testing and E2E testing strategies for custom native modules
✦Master the workflow for publishing your module as an npm package for the community
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Implementing the Native Module in Kotlin (Android)
Basic Structure
The Android implementation follows the same declarative API pattern. The nearly symmetrical code structure between Swift and Kotlin keeps the learning curve low.
// android/src/main/java/expo/modules/mynativesensor/MyNativeSensorModule.ktpackage expo.modules.mynativesensorimport android.content.Contextimport android.hardware.Sensorimport android.hardware.SensorEventimport android.hardware.SensorEventListenerimport android.hardware.SensorManagerimport expo.modules.kotlin.modules.Moduleimport expo.modules.kotlin.modules.ModuleDefinitionimport expo.modules.kotlin.Promiseclass MyNativeSensorModule : Module(), SensorEventListener { private var sensorManager: SensorManager? = null private var accelerometer: Sensor? = null private var isTracking = false override fun definition() = ModuleDefinition { // Module name (must match iOS) Name("MyNativeSensor") // Constants Constants( "isAccelerometerAvailable" to (getAccelerometer() != null), "isGyroAvailable" to (getGyroscope() != null) ) // Events Events("onSensorUpdate", "onError") // Synchronous function Function("getCurrentReading") { // On Android, real-time sensor values can't be // fetched directly — return the last cached reading lastReading ?: mapOf( "x" to 0.0, "y" to 0.0, "z" to 0.0, "timestamp" to System.currentTimeMillis().toDouble() ) } // Async function AsyncFunction("startTracking") { interval: Double, promise: Promise -> val manager = getSensorManager() val sensor = getAccelerometer() if (sensor == null) { promise.reject( "SENSOR_UNAVAILABLE", "Accelerometer is not available", null ) return@AsyncFunction } val delayMicros = (interval * 1_000_000).toInt() manager?.registerListener( this@MyNativeSensorModule, sensor, delayMicros ) isTracking = true promise.resolve(true) } // Stop function Function("stopTracking") { sensorManager?.unregisterListener(this@MyNativeSensorModule) isTracking = false true } // Cleanup OnDestroy { if (isTracking) { sensorManager?.unregisterListener( this@MyNativeSensorModule ) } } } // Cache the last sensor reading private var lastReading: Map<String, Double>? = null override fun onSensorChanged(event: SensorEvent?) { event?.let { val reading = mapOf( "x" to it.values[0].toDouble(), "y" to it.values[1].toDouble(), "z" to it.values[2].toDouble(), "timestamp" to (it.timestamp / 1_000_000.0) ) lastReading = reading sendEvent("onSensorUpdate", reading) } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} private fun getSensorManager(): SensorManager? { if (sensorManager == null) { sensorManager = appContext.reactContext ?.getSystemService(Context.SENSOR_SERVICE) as? SensorManager } return sensorManager } private fun getAccelerometer(): Sensor? { if (accelerometer == null) { accelerometer = getSensorManager() ?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } return accelerometer } private fun getGyroscope(): Sensor? { return getSensorManager() ?.getDefaultSensor(Sensor.TYPE_GYROSCOPE) }}
Designing the TypeScript API Layer
Type Definitions
Strict TypeScript type definitions for the native module ensure type safety on the JavaScript side.
# 1. Compile TypeScriptnpm run build# 2. Dry run (verify contents without actually publishing)npm pack --dry-run# Output: lists all files that would be included# 3. Log in to npmnpm login# 4. Publish (scoped packages require --access public)npm publish --access public# Expected output:# npm notice Publishing to https://registry.npmjs.org/ with tag latest# + @your-scope/my-native-sensor@1.0.0
Versioning Best Practices
It's important to clearly communicate Expo SDK compatibility in your module's versioning:
v1.0.x — Expo SDK 52 support
v1.1.x — Expo SDK 53 support (backward compatible)
v2.0.x — Expo SDK 54 support (breaking changes)
Including a support matrix in your README makes life much easier for users.
Performance Optimization Tips
Here are techniques to get the most out of your custom native modules.
Controlling Event Frequency
For modules that fire events at high frequency (like sensor data), implement throttling to prevent JavaScript thread congestion:
// iOS: Throttle events to a minimum intervalprivate var lastEventTime: TimeInterval = 0private let minInterval: TimeInterval = 0.016 // ~60fpsprivate func throttledSendEvent(_ data: [String: Any]) { let now = CACurrentMediaTime() guard now - lastEventTime >= minInterval else { return } lastEventTime = now sendEvent("onSensorUpdate", data)}
Preventing Memory Leaks
Always implement the OnDestroy handler in your native modules to release listeners and timers. Be aware, though, that OnDestroy fires only just before the module is deallocated — not when the app moves to the background. This trips people up often enough that the next section covers it in detail.
Notes from Shipping This on a Real Device
The code above builds and runs as written. What caught me out on device was the plainest of distinctions: running correctly and running cheaply are two different things.
As an indie developer you have no reviewer. Battery drain and a slightly sticky scroll go unmentioned until you notice them yourself — and by then the build may already be on the App Store.
Here are three traps I hit in my own module, re-checked against the expo-modules-core 57.0.12 source.
OnDestroy Does Not Fire on Background Transitions
OnDestroy is registered as EventListener(.moduleDestroy, closure), and the source comment says it plainly: "called when the module is about to be deallocated." It fires just before deallocation — not the moment you press the home button.
My module put its stop logic in OnDestroy alone. The accelerometer kept spinning after the app went to the background. I found out from battery drain, not from a crash report.
Background transitions have their own hooks.
When
iOS (Swift)
Android (Kotlin)
Moved to background
OnAppEntersBackground
OnActivityEntersBackground
Returned to foreground
OnAppEntersForeground
OnActivityEntersForeground
About to be deallocated
OnDestroy
OnDestroy
// add these inside definition()OnAppEntersBackground { if self.isTracking { self.motionManager.stopAccelerometerUpdates() }}OnAppEntersForeground { if self.isTracking { // keep the previous interval and resume with the same settings self.resumeAccelerometerUpdates() }}
Keep OnDestroy as the final safety net. The two serve different purposes, and one without the other leaves a gap.
Keep Sensor Callbacks Off the Main Queue
The earlier sample used startAccelerometerUpdates(to: .main). It reads well, but set accelerometerUpdateInterval to 0.01 and you are queuing 100 closures per second onto the main thread.
React Native drives its UI updates on that same thread. If scrolling starts to feel a beat behind your finger, look here first.
Give the sensor its own queue and hop back to main only for work that touches the UI.
private let sensorQueue: OperationQueue = { let queue = OperationQueue() queue.name = "net.rorklab.sensor" queue.qualityOfService = .userInitiated queue.maxConcurrentOperationCount = 1 return queue}()// pass it as startAccelerometerUpdates(to: sensorQueue) { ... }
Combine this with the throttling shown earlier and only the thinned-out events cross the bridge. Because it lowers the emission rate itself, the effect is easy to observe.
Stop the Hardware While Nobody Is Subscribed
Declaring Events("onSensorUpdate", "onError") does not gate anything. sendEvent keeps firing even with zero JavaScript listeners, and the sensor keeps spinning.
expo-modules-core provides hooks for the moment the first listener is added and the moment the last one is removed.
Pass an event name as the first argument to scope the hook to a single event. Kotlin exposes the same function names on ObjectDefinitionBuilder, so the pattern carries over unchanged.
Now the hardware stops the instant a screen unmounts and subscription.remove() runs. Compared with making JavaScript call startTracking and stopTracking explicitly, there is simply no place left to forget.
One caveat: once OnStartObserving is in place, make sure AsyncFunction("startTracking") does not start the sensor a second time. Centralize the start logic. I called it from both paths and ended up with a module where a single stopAccelerometerUpdates() no longer stopped anything.
Summary
Building custom native modules with the Expo Modules API dramatically expands what's possible with Rork Max. Thanks to the declarative API design, you can write Swift and Kotlin implementations using unified patterns, improving maintainability across platforms.
The sensor module pattern demonstrated in this guide applies to any native extension — camera controls, Bluetooth communication, OS-specific UI components, and more. Give it a try in your own projects.
Even after publishing the module, I still go back and check battery usage and profiler numbers on a real device from time to time. Whatever worked on the first build is rarely the shape it should keep — that has been my main takeaway from working with the Expo Modules API.
Start with the smallest possible module: a single Function, built with npx expo run:ios and loaded onto a device. From there it is just a matter of adding one API at a time, as you need it.
Share
Thank You for Reading
Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.