Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Compiling from C, Rust and Others

Compiling Rust to WebAssembly with wasm-bindgen

Learn the Rust to WebAssembly workflow - targets, wasm-pack, wasm-bindgen glue, structs and Result types across the boundary - with runnable stand-ins for generated code.

Rust and WebAssembly fit each other well. Rust has no garbage collector and no heavy runtime, so its programs compile to small modules, and its ownership rules catch the memory mistakes that make C code risky. The Rust compiler has a built-in WebAssembly target, and a companion tool called wasm-bindgen generates the JavaScript glue so you can pass strings, structs and errors across the boundary without writing pointer code by hand.

The Rust toolchain cannot run on this site, so the Rust and cargo snippets are read-only. To keep the lesson hands-on, each idea also has a runnable stand-in: a small hand-assembled module plus a few lines of JavaScript that do what the generated glue does. Once you see the stand-in, the generated code stops being magic.

The compilation targets

Rust names a target by CPU, vendor and system. Three of them matter for WebAssembly:

Target Use it for
wasm32-unknown-unknown The browser (and any host that provides its own imports)
wasm32-wasip1 WASI command-line programs (see What is WASI?)
wasm32-wasip2 WASI with the component model (see The Component Model and WIT)

You add a target once, then build:

Terminal
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown --release
# result: target/wasm32-unknown-unknown/release/my_crate.wasm

That .wasm file only understands numbers. A Rust function fn add(a: i32, b: i32) -> i32 marked #[no_mangle] pub extern "C" works directly, but a function taking a &str or returning a Vec<u8> does not, because those are pointers into Rust's memory with layouts the browser knows nothing about.

wasm-bindgen: the glue generator

wasm-bindgen has two halves. A Rust crate (wasm_bindgen) provides the #[wasm_bindgen] attribute that you put on items. A command-line tool reads the compiled module and writes JavaScript and TypeScript declaration files that convert values in both directions.

TOML
# Cargo.toml
[package]
name = "geometry"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]    # build a dynamic library, which becomes the .wasm

[dependencies]
wasm-bindgen = "0.2"
Rust
// src/lib.rs
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}

#[wasm_bindgen]
pub struct Point {
    x: i32,
    y: i32,
}

#[wasm_bindgen]
impl Point {
    #[wasm_bindgen(constructor)]
    pub fn new(x: i32, y: i32) -> Point {
        Point { x, y }
    }

    pub fn distance_squared(&self) -> i32 {
        self.x * self.x + self.y * self.y
    }

    pub fn translate(&mut self, dx: i32, dy: i32) {
        self.x += dx;
        self.y += dy;
    }
}

Build and package it with wasm-pack, which runs cargo, then wasm-bindgen, then optionally wasm-opt:

Terminal
wasm-pack build --target web      # ES module you can import in a browser
wasm-pack build --target bundler  # for webpack / Vite
wasm-pack build --target nodejs   # CommonJS for Node

The output folder pkg/ contains geometry_bg.wasm, a JavaScript file with the glue, a .d.ts file with TypeScript types, and a package.json. Using it from a page looks like ordinary JavaScript:

JavaScript
import init, { greet, Point } from './pkg/geometry.js';

await init();                 // fetches and instantiates the module
console.log(greet('Ada'));    // "Hello, Ada!"

const p = new Point(3, 4);
console.log(p.distance_squared()); // 25
p.translate(1, 1);
p.free();                     // release the Rust-side memory

The wasm-bindgen pipeline

Rust code Items marked with wasm_bindgen.
cargo build Produces a raw .wasm file.
wasm-bindgen Writes JS glue and .d.ts types.
pkg folder Ready to import or publish.

wasm-pack runs all of these steps for you.

1 / 2

Stand-in 1: Result becomes an exception

A Rust Result<i32, String> cannot cross the boundary as-is. wasm-bindgen's trick for fallible functions is a convention: write the success value to an out-parameter, return a status, and let the glue code throw on failure. You can see the same idea with this module, which has checked_div(a, b, out) and checked_add(a, b, out), each returning 0 on success, 1 for a division by zero and 2 for an overflow:

Node.js Status codes turned into exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real wasm-bindgen glue is more elaborate (it also moves error objects as JsValues) but the shape is the same: a thin wrapper that hides status codes behind normal JavaScript behavior.

Stand-in 2: structs live in wasm, JavaScript holds a handle

When you return Point from Rust, JavaScript does not receive a copy. The struct stays in linear memory; JavaScript receives a small object holding a pointer to it. Method calls pass that pointer back as the first argument, which is why p.free() exists. The module below keeps the struct as two i32 values at an address, with dist2(ptr) and move(ptr, dx, dy) operating on it:

Node.js A struct handle, like wasm-bindgen generates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The "null pointer passed to rust" message is a real wasm-bindgen error text. It appears when you use an object after free(), and it is the most common beginner surprise. Modern wasm-bindgen can also use FinalizationRegistry to free objects automatically when the JavaScript wrapper is garbage-collected, but you should not rely on timing for large objects.

Calling JavaScript and the DOM from Rust

The reverse direction uses extern "C" blocks. The companion crates js-sys (JavaScript built-ins) and web-sys (browser APIs, one cargo feature per API) wrap thousands of these declarations:

Rust
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(message: &str);
}

#[wasm_bindgen]
pub fn announce(n: u32) {
    log(&format!("computing {n}"));
}

Every call into JavaScript has a cost, so keep the hot loop inside Rust and cross the boundary once per task, not once per element. See WebAssembly Performance for numbers.

Tips for small, fast Rust modules

  • Build with --release, and in Cargo.toml set opt-level = "s" (or "z"), lto = true, codegen-units = 1 and panic = "abort" to shrink the file.
  • Avoid pulling in heavy crates for one small job; format! and regex add tens of kilobytes.
  • Run wasm-opt -Oz (wasm-pack does it by default for release builds).
  • Use console_error_panic_hook during development so Rust panics appear as readable messages instead of RuntimeError: unreachable.

More on size in Binary Size and Optimization.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Rust target is used for the browser?

    wasm32-unknown-unknown assumes nothing about the host: imports come from JavaScript. The wasip targets assume WASI imports instead.
  2. 2. What does wasm-bindgen generate?

    The raw module only speaks numbers. wasm-bindgen writes the wrapper code that copies strings, wraps structs and maps Result to exceptions.
  3. 3. When JavaScript holds a wasm-bindgen struct such as Point, what does it really hold?

    The struct stays in linear memory. The wrapper object stores its address and passes it on each call, which is why free() is needed.
  4. 4. Why should the hot loop stay inside the wasm module?

    Crossing the JS and wasm boundary and converting values costs time. Doing a whole job in one call keeps that cost small.

Summary

  • Rust compiles to WebAssembly with the wasm32-unknown-unknown target (browser) or wasm32-wasip1 / wasm32-wasip2 (WASI).
  • wasm-bindgen generates the glue that lets strings, structs and errors cross the boundary; wasm-pack runs the whole build and packaging pipeline.
  • Fallible functions become status codes plus out-parameters under the hood, and the glue throws exceptions.
  • Structs stay in linear memory; JavaScript holds a pointer-carrying handle and should call free().
  • Keep boundary crossings few, and tune Cargo.toml for size with opt-level, lto and panic = "abort".

Next: Other Languages for WebAssembly