12k
All articles

How to Call Rust from Node.js with napi-rs

Build Node.js native add-ons with Rust and napi-rs. Export functions, objects, and async tasks, then package prebuilt platform binaries for npm.

OpenReplay Team
OpenReplay Team
How to Call Rust from Node.js with napi-rs

To call Rust from Node.js with napi-rs v3, scaffold a project with npx @napi-rs/cli new, mark Rust functions with #[napi], run the build, and require the generated index.js like any other module.

Maybe a hashing loop is slowing your event loop, or you need a native library and don’t want to go back to fighting binding.gyp. The C++ add-on route through node-gyp works, but every user’s machine ends up needing Python and a compiler. This guide builds a working Rust add-on, adds an object return type and an async function, and shows how prebuilt binaries get to users through npm.

Key Takeaways

  • napi-rs compiles #[napi]-annotated Rust into a .node binary and also generates a JavaScript loader (index.js) and TypeScript declarations (index.d.ts).
  • A napi-rs v3 project needs Rust 1.88+, plus Node.js ^20.17.0, ^22.13.0 or 23.5.0+ for the CLI. That CLI requirement is separate from the Node versions the finished add-on supports.
  • An exported async fn needs the async or tokio_rt feature on the napi crate, and it is typed as returning a Promise.
  • A napi-rs package ships as a root package plus one optional package per platform, so the people who install it never need Rust.

What Is napi-rs?

napi-rs is a framework for building Node.js native add-ons in Rust. You mark Rust functions with #[napi], and the build produces a .node binary, a JavaScript loader, and TypeScript declarations generated from the Rust signatures.

napi-rs sits on top of Node-API, Node’s ABI-stable C interface for add-ons. Because the interface is ABI-stable, a binary compiled against one Node-API level can generally load in later Node.js releases that still provide that level, without a rebuild. Callers import the add-on like a normal module and get typed autocomplete.

napi-rs vs WebAssembly: Which Should You Use?

Choose napi-rs when your code runs on the server and needs the file system, native threads, or an existing native library. Choose Wasm when the same code also has to run in the browser. napi-rs and Wasm aren’t mutually exclusive: napi-rs can produce an optional WASI build, and the generated loader can fall back to it.

napi-rsWebAssemblynode-gyp C++
File system and native threadsYesLimited, depends on hostYes
Links existing native/C librariesYesOnly if compiled to WasmYes
Per-platform builds requiredYes, built in CINoYes, or compiled at install time
Optional WASI build with loader fallbackYesN/ANo
Toolchain the user needs at installNoneNoneOften Python and a C++ compiler
Generated TS typesYesDepends on toolingNo

Which option is faster depends on the workload, so benchmark your own hot path. To go further with Wasm, read about running high-performance code with Wasm and publishing WebAssembly packages for npm.

Create a napi-rs Project

To create a napi-rs project, run napi new through the @napi-rs/cli package. The getting-started docs list the prerequisites: Rust 1.88 or newer, Node.js ^20.17.0, ^22.13.0 or 23.5.0+ for the CLI, Git, and a C linker. The Node versions your finished add-on runs on are a separate question, governed by the Node-API level it compiles against.

With the Yarn template:

yarn dlx @napi-rs/cli new hash-rs
cd hash-rs
yarn install
yarn build

With the pnpm template:

pnpm dlx @napi-rs/cli new hash-rs --package-manager pnpm
cd hash-rs
pnpm install
pnpm build

Only Yarn and pnpm templates are supported. The napi new prompts ask for the path, package name, Node-API level, targets, license, and whether to generate a CI workflow. The scaffold contains these files:

  • src/lib.rs: your exported Rust functions.
  • Cargo.toml: declares crate-type = ["cdylib"] and the napi-rs v3 crates. Keep the versions it writes, and check it for the Node-API feature level you picked.
  • build.rs: generated and required. It calls napi_build::setup() and must stay at the crate root, so don’t edit it.
  • package.json: the build script runs napi build --platform --release. The napi block holds your config:
{
  "napi": {
    "binaryName": "hash-rs",
    "targets": ["x86_64-apple-darwin", "aarch64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
  }
}

Copy the field values from your generated file. Each build writes hash-rs.<platform>.node (for example hash-rs.darwin-arm64.node), along with index.js and index.d.ts.

Code written for napi-rs v2 won’t work unchanged. If you copied from an older tutorial, check it against the v2 to v3 migration guide:

v2v3
napi.namenapi.binaryName
napi.triplesflat napi.targets array
napi.package.namenapi.packageName
napi create-npm-dirnapi create-npm-dirs
JsObject, JsFunctiontyped v3 APIs; old types are behind the unsafe compat-mode feature

Write a CPU-Heavy napi-rs Function

Export a Rust function by adding #[napi] to a pub fn. Add a hashing crate first:

cargo add sha2

Then replace src/lib.rs with this napi-rs v3 code:

use napi_derive::napi;
use sha2::{Digest, Sha256};

/// Hash `input` with SHA-256, `rounds` times.
#[napi]
pub fn sha256_rounds(input: String, rounds: u32) -> String {
  let mut data = input.into_bytes();
  for _ in 0..rounds.max(1) {
    data = Sha256::digest(&data).to_vec();
  }
  data.iter().map(|b| format!("{:02x}", b)).collect()
}

The function rehashes its own output rounds times, which is the kind of tight loop that blocks a JavaScript thread. Rust String maps to a JS string and u32 maps to a JS number. The hex encoding is a manual loop, so it doesn’t rely on version-specific formatting in sha2. Rebuild with yarn build. The function appears in index.d.ts under the camelCase name sha256Rounds.

Call it from a CommonJS file such as try.cjs:

const { sha256Rounds } = require('./index.js')
console.log(sha256Rounds('hello', 1))
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

The simple-package walkthrough uses the same build-then-require loop.

Return Objects and Promises

In napi-rs, use #[napi(object)] to return plain JS objects, and async fn to return Promises. According to the Object concept page, every field of a #[napi(object)] struct must be pub. The struct can then serve as an argument or a return type, and its value is copied when it crosses the boundary.

For async functions, turn on the async feature (or tokio_rt) on napi, and add Tokio for file I/O:

[dependencies]
# keep the features the scaffold wrote, and append "async"
napi = { version = "3", features = ["async"] }
cargo add tokio --features fs

Append the following to the existing src/lib.rs, which already imports the napi macro and Sha256. The ? after fs::read works because napi converts std::io::Error into its own Error type.

use napi::bindgen_prelude::*;
use tokio::fs;

#[napi(object)]
pub struct FileHash {
  pub path: String,
  pub bytes: u32,
  pub sha256: String,
}

#[napi]
pub async fn hash_file(path: String) -> Result<FileHash> {
  let content = fs::read(&path).await?;
  let sha256: String = Sha256::digest(&content)
    .iter()
    .map(|b| format!("{:02x}", b))
    .collect();
  Ok(FileHash { bytes: content.len() as u32, path, sha256 })
}

An exported napi-rs async fn runs on a Tokio runtime that napi-rs manages. In the generated types, hashFile returns a Promise that resolves to a FileHash object, and a Rust Err becomes a rejected Promise. async fn fits I/O work like this. For long pure-CPU jobs, napi-rs provides AsyncTask, which runs work off the main thread.

How Do You Publish a napi-rs Package to npm?

People who install a napi-rs package don’t need Rust. A napi-rs package ships as a small root package plus one optional package per platform, and the package manager installs only the binary whose os, cpu, and (where relevant) libc package.json fields match the machine.

Here is what happens at install time:

  1. The user installs the root package.
  2. The package manager skips optional packages whose os, cpu, or libc fields don’t match.
  3. The matching platform package installs a prebuilt .node file.
  4. index.js finds that binary and loads it.

napi.targets lists every platform you ship. A local napi build compiles only one target, though: your host, unless you pass --target. The other binaries come from the generated GitHub Actions workflow. Its publish job runs napi create-npm-dirs to create one npm package directory per target, then moves each built artifact into the matching directory before publishing.

Each target needs its own package name, so use an npm scope:

{
  "name": "@yourscope/hash-rs",
  "optionalDependencies": {
    "@yourscope/hash-rs-darwin-arm64": "1.0.0",
    "@yourscope/hash-rs-linux-x64-gnu": "1.0.0",
    "@yourscope/hash-rs-win32-x64-msvc": "1.0.0"
  }
}

Conclusion

You now have a Rust add-on that Node loads like any other module, with generated types and prebuilt per-platform binaries, so your users never install a Rust toolchain. Next, move your slowest CPU-bound function into src/lib.rs, measure it against the JavaScript version on real inputs, and push a tag to let the generated CI build every target.

For more Rust reading, see Getting Started with Loco, Rust’s Answer to Rails.

FAQs

What is the difference between async fn and AsyncTask in napi-rs?

An async fn runs on the Tokio runtime that napi-rs manages and suits async I/O. AsyncTask runs Task::compute on Node's libuv thread pool and suits bounded blocking or CPU-bound work. Both return a Promise to JavaScript. The libuv pool is shared with Node's file system, DNS, and crypto work, and an AbortSignal can cancel an AsyncTask only before its compute step starts.

What happens when Rust code panics inside a napi-rs function?

Without the catch_unwind option, a Rust panic that reaches the Node-API boundary aborts the whole Node.js process instead of throwing. Mark the function with #[napi(catch_unwind)] to turn the panic into a JavaScript Error built from the panic payload. This needs the default unwind panic strategy, and it can't catch an aborting panic. For expected failures, return Result instead: an Err from a synchronous function is thrown as a JavaScript Error.

Do napi-rs add-ons work in Bun and Deno?

Bun support is best effort. The napi-rs repository runs a latest-Bun CI job, but Bun failures do not block napi-rs releases, so test your own add-on in Bun. Deno native add-ons are not in the napi-rs source CI matrix, and the napi-rs docs warn against assuming Deno support from Node-API compatibility alone. The optional WASI fallback also has known gaps in both runtimes.

Which Node-API level should a napi-rs add-on target?

The Node-API level sets the oldest runtime your add-on can load on. A binary built against Node-API level N can generally load on later Node.js releases that still provide level N, with no rebuild for each Node major. A higher level gives access to newer Node-API functions but raises that floor. Functions added after your chosen level are not available.

DevTools for the frontend

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.