Typorithm · hard

Rust Addons (napi-rs)

rust-napiarchitecturerustnapi-rsffi
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Rust Addons (napi-rs)

0%

Native Integrations

napi-rs lets you write a Node addon in Rust: a #[napi] macro generates the N-API glue and TypeScript types so an ordinary Rust function becomes a callable JS export. You get Rust's memory safety and speed without writing C++; neon is an alternative, and the build emits a prebuilt .node per platform. Ideal for parsers, crypto, and heavy compute.

napi-rs is a framework for building Node addons in Rust. You annotate a normal Rust function with the #[napi] attribute macro, and at compile time it generates the entire N-API boundary layer plus matching TypeScript type definitions — no hand-written C++ glue.

The architectural win is that you inherit Rust's guarantees: the borrow checker enforces memory safety at compile time, and you get native speed, while the macro hides the unsafe FFI marshalling. neon is an alternative framework with a similar goal but a different API surface.

The build produces a prebuilt .node binary per target platform, which the JS side imports as plain named exports. This makes napi-rs a strong fit for performance-critical pieces — fast parsers, cryptography, image processing, and other heavy compute — embedded inside a Node app.

01

#[napi] generates N-API glue and TypeScript types.

02

You get Rust safety and speed without writing C++.

03

neon is an alternative; the build emits a prebuilt .node.

// lib.rs (napi-rs)
#[napi]
pub fn add(a: i32, b: i32) -> i32 {
  a + b
}

// index.js
import { add } from "./index.js";
console.log(add(2, 3));

Read the implementation

Connect each part of the code to the concept before you type.

1. The macro

The #[napi] attribute macro generates all the N-API glue and TypeScript types for the function below it.

#[napi]

2. Rust function

An ordinary, type-checked Rust function — napi-rs exposes it to JavaScript with no hand-written C++.

pub fn add(a: i32, b: i32) -> i32 {

3. Import in JS

From JavaScript the Rust function is a normal named import, backed by the generated .node binary.

import { add } from "./index.js";

4. Call from JS

Calling add(2, 3) crosses into compiled Rust and returns the result as a JS number.

console.log(add(2, 3));

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Rust Addons (napi-rs): Lesson & Practice · Typorithm | ApplyDjinn