Build and Run Node-API Modules in React Native

Authors
Jamie Birch
Engineer
@
Scoville, NativeScript TSC

Last week, we announced Node-API support for React Native, which brings a consistent, cross-platform, and ABI-stable foundation for building native modules that can interface with JavaScript in a runtime-independent way. This enables you to write native modules not just for React Native, but for other platforms like Node.js, Deno, and Bun, too. In this walkthrough, we will show how to do just that.

Together, we will create an npm package for a simple Node-API module. We'll build and run it in Node.js initially to check that it’s all working, then adapt it for React Native. And after demoing it on both Android and iOS, we'll publish it to npm for others to use!

To learn more about Node-API and all its benefits for React Native ecosystem, read our announcement here.

Creating the npm package

We’ll need a handful of files.

.
├── .gitignore
├── package.json
├── sum.cpp
├── CMakeLists.txt
├── index.js
└── index.d.ts

.gitignore

We’ll exclude any generated files from git version control.

# Standard npm ignore patterns.
.DS_Store
node_modules

# Patterns specific to this project.
build

package.json

This configures our npm package. The package depends on bindings and node-addon-api, which are standard dependencies for any Node-API module, as well as cmake-rn, which is our wrapper around another standard dependency, cmake-js. The latter two packages allow us to build for both React Native and Node.js.

The binary field is documented here.

{
  "name": "sum-lib",
  "version": "0.0.0",
  "scripts": {
    "build:rn": "cmake-rn",
    "build:node": "cmake-js",
    "prepublishOnly": "npm run build:node && cmake-rn --android --apple"
  },
  "files": ["build/Release", "index.d.ts", "index.js"],
  "dependencies": {
    "bindings": "~1.5.0",
    "cmake-rn": "^0.2.2",
    "node-addon-api": "^8.4.0"
  },
  "binary": {
    "napi_versions": [4]
  }
}

sum.cpp

This is our native code for a sum(a, b) function that adds the numbers a and b together and returns the result. Here, we use C++ to call Node-API functions to interact with the given JavaScript environment (as documented in the node-addon-api repo).

#include <napi.h>

// Implement the sum(a, b) function.
Napi::Value Sum(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();

  if (info.Length() < 2 || !info[0].IsNumber() || !info[1].IsNumber()) {
    Napi::TypeError::New(env, "Expected two number arguments").ThrowAsJavaScriptException();
    return env.Null();
  }

  double arg0 = info[0].As<Napi::Number>().DoubleValue();
  double arg1 = info[1].As<Napi::Number>().DoubleValue();
  double sum = arg0 + arg1;

  return Napi::Number::New(env, sum);
}

// Export the sum(a, b) function as a module.
Napi::Object Init(Napi::Env env, Napi::Object exports) {
  exports.Set(Napi::String::New(env, "sum"),
              Napi::Function::New(env, Sum));
  return exports;
}

NODE_API_MODULE(SumAddon, Init)
Do I have to use C++?
Not at all! You can alternatively write Node-API modules in other languages, like C, C#, Swift, Zig, Go, and Rust, too. We’ll explain how in a future article!

CMakeLists.txt

This file configures the native build using CMake.

cmake_minimum_required(VERSION 3.15...3.31)
project(sum)

add_compile_definitions(-DNAPI_VERSION=4)

file(GLOB SOURCE_FILES "sum.cpp")

add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")
target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_JS_INC})
target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_JS_LIB})
target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17)

if(MSVC AND CMAKE_JS_NODELIB_DEF AND CMAKE_JS_NODELIB_TARGET)
  # Generate node.lib
  execute_process(COMMAND ${CMAKE_AR} /def:${CMAKE_JS_NODELIB_DEF} /out:${CMAKE_JS_NODELIB_TARGET} ${CMAKE_STATIC_LINKER_FLAGS})
endif()

index.js

This is your npm package’s JavaScript entry-point, which simply re-exports the native library.

module.exports = require("bindings")("sum");

// The above is essentially equivalent to writing the following:
// if(process.platform === 'darwin'){
//   module.exports = require("./build/Release/sum.node");
// } else {
//   // … handle other platforms, which place sum.node under different paths…
// }

index.d.ts

These are some hand-written typings just to make the module play nicely with TypeScript.

export function sum(a: number, b: number): number;
For a more complicated module, we might want to use an index.ts file instead and transpile that at build-time, but this walkthrough just uses hand-written typings to keep the build step simple.

Building and running on Node.js

Rather than immediately trying to use the module in React Native, it’s worth taking a moment to build and run it on Node.js first, just to check that we set everything up correctly.

Building

We’ll start by building the Node-API module.

# Install the npm dependencies.
npm install

# Build the native code for Node.js.
npm run build:node

Building the native code generates a Node-API binary inside the build folder for your host platform (e.g., ARM macOS):

  .
  ├── .gitignore
+ ├── build
+ │   ├── …
+ │   └── Release
+ │       └── sum.node
  ├── node_modules
  ├── package-lock.json
  ├── package.json
  ├── sum.cpp
  ├── CMakeLists.txt
  ├── index.js
  └── index.d.ts

Running

Let’s try to call the Node-API module we’ve just built. Just make a test.js file:

  .
  ├── .gitignore
  ├── build
  │   ├── …
  │   └── Release
  │       ├── …
  │       └── sum.node
  ├── node_modules
  ├── package-lock.json
  ├── package.json
  ├── sum.cpp
  ├── CMakeLists.txt
+ ├── test.js
  ├── index.js
  └── index.d.ts

Testing

In test.js, we’ll import the sum(a, b) function from the Node-API module we’ve just built.

// Import from index.js, which re-exports sum.node.
const { sum } = require(".");

console.log(sum(1, 2));
// Should log 3

We can then run it using Node.js:

node test.js
# Logs 3

Congratulations, you’ve just made your first Node-API module! 🥳 The setup looks good, so let’s try adapting it for React Native next.

Building for React Native

In this section, we’ll build the Node-API module for React Native, then run it on both Android and iOS in an Expo app.

npm run build:rn

This will generate Node-API binaries inside the build folder for all the React Native platforms that your development environment supports:

  .
  ├── .gitignore
  ├── build
  │   ├── …
  │   └── Release
+ │       ├── sum.android.node
+ │       ├── sum.apple.node
  │       └── sum.node
  ├── node_modules
  ├── package-lock.json
  ├── package.json
  ├── sum.cpp
  ├── CMakeLists.txt
  ├── index.js
  └── index.d.ts
The “build:rn” run script calls cmake-rn without any flags, which just performs a minimal build, only targeting simulators. To target real devices as well, you will need to call cmake-rn --android --apple instead, which is exactly what our “prepublishOnly” script does.

Consuming the module in React Native

Creating an example app

To demonstrate how to run our Node-API module in React Native, first we’ll need an example app. Let’s create one in a separate folder alongside the npm package we just created.

# Move out of the sum-lib directory.
cd ..

# Create an Expo app named "sum-app" alongside it.
npx create-expo-app@latest --template blank-typescript sum-app
cd sum-app

# Turn it into a "development build".
npx expo prebuild

# Expose the Babel and Metro configs.
npx expo customize babel.config.js metro.config.js

Adding our Node-API module

Now that we have a simple app set up, let’s install the bits specific to our Node-API module:

cd ../sum-app
npm install ../sum-lib react-native-node-api

And let’s reference the module in the app by using the following App.tsx:

import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, TextInput, View } from "react-native";
import { useState } from "react";
import { sum } from "sum-lib";

export default function App() {
  const [a, setA] = useState("");
  const [b, setB] = useState("");

  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <TextInput
        style={styles.input}
        value={a}
        onChangeText={setA}
        selectTextOnFocus
      />
      <Text style={styles.text}>+</Text>
      <TextInput
        style={styles.input}
        value={b}
        onChangeText={setB}
        selectTextOnFocus
      />
      <Text style={styles.text}>
        = {sum(parseFloat(a), parseFloat(b)) || "?"}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: "row",
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  text: {
    fontSize: 20,
    textAlign: "center",
  },
  input: {
    fontSize: 20,
    textAlign: "center",
    minWidth: 100,
    borderBottomWidth: 1,
    borderColor: "#aaa",
    margin: 10,
  },
});

Configuring the example app

React Native apps can’t use Node-API libraries out of the box, so we need to do a bit of configuration first.

Configuring Babel

Add the react-native-node-api Babel plugin to babel.config.js. This is needed to rewrite any imports of .node files so that they’re handled correctly by Metro.

  module.exports = function (api) {
    api.cache(true);
    return {
      presets: ['babel-preset-expo'],
+     plugins: ['module:react-native-node-api/babel-plugin'],
    };
  };

Configuring Metro

This isn’t specific to working with Node-API modules, but because we’ve installed sum-lib locally via symlink, we need to help Metro find it.

  // Learn more https://docs.expo.io/guides/customizing-metro
  const { getDefaultConfig } = require('expo/metro-config');
+ const path = require('node:path');

  /** @type {import('expo/metro-config').MetroConfig} */
  const config = getDefaultConfig(__dirname);
  
+ config.watchFolders = [__dirname, path.resolve(__dirname, '../sum-lib')];

  module.exports = config;
If you’re following this walkthrough in a monorepo, you may have to modify the config differently. Follow Expo’s documentation here.

Configuring Android

Until Node-API is upstreamed into Hermes, we need to switch to the react-native-node-api fork of Hermes to consume Node-API modules. This part will get simpler in the future, sorry!

First, we need to download the source code for the Hermes fork into our project:

npx react-native-node-api vendor-hermes --silent

It’ll print out a line like /Users/jamie/git/sum-app/node_modules/react-native-node-api/hermes.

Add that line into the .env.local file at the root of your project (create it if it’s missing), like so:

export REACT_NATIVE_OVERRIDE_HERMES_DIR=/Users/jamie/git/sum-app/node_modules/react-native-node-api/hermes

Finally, enable building React Native from source, by editing android/settings.gradle:

  // …
  include ':app'
  includeBuild(expoAutolinking.reactNativeGradlePlugin)

+ includeBuild('../node_modules/react-native') {
+     dependencySubstitution {
+         substitute(module("com.facebook.react:react-android")).using(project(":packages:react-native:ReactAndroid"))
+         substitute(module("com.facebook.react:react-native")).using(project(":packages:react-native:ReactAndroid"))
+         substitute(module("com.facebook.react:hermes-android")).using(project(":packages:react-native:ReactAndroid:hermes-engine"))
+         substitute(module("com.facebook.react:hermes-engine")).using(project(":packages:react-native:ReactAndroid:hermes-engine"))
+     }
+ }
If you’re following this walkthrough in a monorepo, you may need to adjust the path to React Native. Very often it’s a case of moving up by two directories, i.e. changing ../node_modules/react-native to ../../../node_modules/react-native.

Configuring iOS

There’s no further configuration necessary on the iOS side – the Hermes fork is set up automatically upon pod install (which the Expo CLI will run for you as part of npm run ios).

Running our Node-API module in React Native

Now we’re ready to run our Node-API module in the example app via the simulator! Remember that in the earlier Building for React Native step, we only built our Node-API module for the simulator.

If you want to run the following steps on a real device instead:

cd ../sum-lib
npm run prepublishOnly

Running on Android

Before running on Android, make sure to delete any previous builds of React Native so that the app will be recompiled with our patched Hermes.

rm -rf ./node_modules/react-native/ReactAndroid/build

npm run android

Running on iOS

Similarly on iOS, delete the CocoaPods lockfile so that the app will be recompiled with our patched Hermes.

rm -f ios/Podfile.lock

npm run ios

The result

We should now be able to see our app running on React Native!

Publishing your Node-API module

After all that, we’ll find the publishing step is surprisingly simple. Our package.json is already set up correctly for it, so we simply have to publish our Node-API module like any other npm package!

cd ../sum-lib
npm publish 

Now others can install it with npm install sum-lib!

Conclusion

Congratulations! You’ve now written a Node-API module in C++, tested it out in both Node.js and React Native, and finally published it to npm for others to use! And more importantly, you’ve become a pioneer breaking down the boundaries between JavaScript ecosystems.

Some of the steps along the way may have been a bit fiddly, but we’re actively working to reduce them so that the process will get simpler. Contributors are always welcome, so do please get involved in react-native-node-api if you’re interested!

Insights

Learn more about React Native

cover

Aug 4Podcast

VisionCamera V5 With Marc Rousavy

Marc Rousavy joins Mike Grabowski to unpack VisionCamera v5, Nitro Modules, the constraints API, migration work, and what changed for React Native camera apps.

cover

Jul 1Podcast

Redraw for Effects Beyond Skia

William Candillon talks about where Redraw fits next to Skia, from physics-based rendering to camera effects, AR, and new UI patterns.

cover

Jun 29Article

Less Boilerplate, More Type Safety: React Navigation 8's Typed Hooks

React Navigation 8 improves typed hooks with screen-aware types, less boilerplate, and fewer unsafe casts in shared UI and nested navigators.

cover

Apr 30Live Stream

Build a React Native App With the TanStack Stack

Join Callstack’s live stream on building a React Native app from the ground up using the TanStack toolbelt.

cover

Apr 28Article

React Native production lessons from React Universe Meetup x Zalando

Lessons from React Universe Meetup x Zalando on React Native in production, covering brownfield performance, feed video, native API access, and on-device AI.

cover

Apr 23Talk

Shipping iOS Live Activities with React: The Voltra Story

How Voltra enables Live Activities and Dynamic Island views using React without writing Swift. A deep dive into iOS constraints and architecture.

cover

Apr 16Live Stream

React Native 0.85: Animation Backend and Key Updates

A recap of React Native 0.85, covering the new animation backend, DevTools improvements, and ecosystem takeaways.

cover

Mar 5Article

Keeping Screens Visible With <Activity mode="hidden">

A cross‑platform workaround to keep screens visible while <Activity mode="hidden"> unmounts effects on inactive screens by setting mode="hidden".

cover

Feb 25Article

React Native Monorepo With pnpm Workspaces

Set up a React Native monorepo with pnpm workspaces for mobile and Next.js web, including Metro fixes, hoisted node-linker, and shared packages.

cover

Feb 18Article

A Practical Guide to React Native Monorepo With Yarn Workspaces

Learn how to set up a React Native monorepo with Yarn workspaces for mobile and web, including Metro, Gradle, and shared packages.

cover

Feb 17Podcast

From Teddy Bears to Voice Agents: Kraen Hansen on Voice AI, Local-First & App Security

What happens when you combine voice agents and teddy bears? A hands-on look at local-first systems, voice AI, and security lessons from poking real apps.

cover

Jan 28Article

Bringing CSS Clipping to React Native

A deep look at how a single CSS feature moves through React Native’s New Architecture, from JavaScript styles to native rendering on iOS and Android.

cover

Mar 19Tutorial

The Hard Way vs. The React Native AI SDK Way: Stop Writing Custom Modules for Every Model

Learn how React Native AI uses a unified provider model to switch between cloud and on-device LLMs without rewriting application logic, enabling reliable AI experiences online and offline.

cover

Mar 12Tutorial

Build Smarter Apps: Tool Calling & AI Orchestration Explained

Learn how on-device models in React Native can call tools, interact with external APIs, and return structured outputs you can use directly in application logic.

cover

Mar 5Tutorial

MLC LLM + React Native: On-Device AI Without the Pain

Learn how to run third-party on-device LLMs in React Native using MLC LLM. Choose your models, run them efficiently across platforms, and keep a unified JavaScript API with React Native AI.

cover

Feb 24Tutorial

Intelligent Fallbacks with Apple Intelligence in React Native

Learn how to use Apple’s built-in Foundation Models in React Native apps, reduce memory usage, and enable fast, fully on-device AI with React Native AI Apple.

cover

Feb 10Tutorial

What Is the React Native AI SDK? A Complete Intro & Quickstart

Learn why on-device AI matters for React Native apps, how local LLMs behave offline, and what problems React Native AI is designed to solve from day one.

cover

Jan 29Tutorial

Implementing an Android TurboModule with Kotlin

Learn how to implement a React Native TurboModule on Android, from the TypeScript spec and Codegen to the Kotlin implementation and package registration.

cover

Jan 19Tutorial

Working with Different Threads in Swift TurboModules

Learn how JavaScript, native module, background, and main threads interact in React Native TurboModules, and how to use GCD queues to run async work safely in Swift.

cover

Jan 9Tutorial

How to Add Type-Safe Constants to Swift TurboModules

Learn how to expose typed, immutable constants from a Swift TurboModule using Codegen, and get full end-to-end type safety between native and JavaScript.

cover

Dec 30Tutorial

Adding Event Emitters to Your TurboModule in Swift

Learn how to emit native events from a Swift TurboModule and subscribe to them in JavaScript, including proper memory management and Codegen integration.

cover

Dec 22Tutorial

Writing Your First TurboModule in Swift

Learn how to build a fully working TurboModule in Swift, integrate it with Codegen, and bridge it through Objective‑C inside an Expo app.