wasm-bindgen & web-sys — WebAssembly

wasm-bindgen generates glue on both sides: &str/String are copied as UTF-8 bytes (passStringToWasm0, getStringFromWasm0, then __wbindgen_free), JS objects…

In the bridge lesson, sending "Renée" to Wasm took a TextEncoder, an address and a byte length you worked out yourself. In Rust, wasm-bindgen does that work. It generates go-between code (glue) on both sides so that Rust functions can take and return strings, JS objects and closures, not just numbers. On top of it sit two crates: js-sys for JavaScript's built-in objects (Array, Date, Math, Promise) and web-sys for Web APIs (console, document, canvas, fetch).

A guest from abroad staying at Mist Homestay usually comes with a guide who translates both ways and carries their luggage. The guide brings a general phrasebook for everyday talk, and maps of the sights that are bought one sheet at a time, by destination. The guest is the Rust code, the homestay is the browser, the guide is wasm-bindgen, the phrasebook is js-sys, and the map sheets are web-sys features: to go to the canvas, buy the canvas sheet.

The project: mist-canvas

The toolchain is the same as in the wasm-pack lesson (rustc 1.99.0, wasm-pack 0.15.0, wasm-bindgen 0.2.129), plus web-sys 0.3.106:

[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console", "CanvasRenderingContext2d"] }
use wasm_bindgen::prelude::*;
use web_sys::{console, CanvasRenderingContext2d};

/// &str in, String out.
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Welcome to Mist Homestay, {name}!")
}

/// console.log from Rust.
#[wasm_bindgen]
pub fn log(message: &str) {
    console::log_1(&JsValue::from_str(message));
}

/// The total price of three rooms for some nights, drawn on a canvas.
#[wasm_bindgen(js_name = drawPrices)]
pub fn draw_prices(ctx: &CanvasRenderingContext2d, nights: i32) {
    let rooms = [("Terrace", 3_500), ("Attic", 2_750), ("Garden", 4_250)]; // cents
    ctx.clear_rect(0.0, 0.0, 300.0, 140.0);
    ctx.set_font("13px sans-serif");
    for (i, (name, price)) in rooms.iter().enumerate() {
        let total = nights * price;
        let y = 12.0 + i as f64 * 42.0;
        ctx.set_fill_style_str("#7aa6d6");
        ctx.fill_rect(0.0, y, total as f64 / 100.0, 28.0); // $1 = 1 pixel
        ctx.set_fill_style_str("#1d2733");
        ctx.fill_text(&format!("{name}: ${}.{:02}", total / 100, total % 100), 6.0, y + 19.0).unwrap();
    }
    console::log_1(&format!("drawPrices: {nights} nights").into());
}

(stayPrice from the wasm-pack lesson is in this crate too.) On the page:

import init, { greet, log, drawPrices } from './pkg/mist_canvas.js';

await init();
console.log(greet('Renée'));  // Welcome to Mist Homestay, Renée!
log('Hello from Rust');       // shows up in the console, sent from Rust
const ctx = document.querySelector('canvas').getContext('2d');
drawPrices(ctx, 2);           // three price bars on the canvas

What wasm-bindgen generates

wasm-pack build --target web writes pkg/mist_canvas.js (11,776 bytes). This is the glue for greet and drawPrices:

export function greet(name) {
    let deferred2_0;
    let deferred2_1;
    try {
        const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.greet(ptr0, len0);
        deferred2_0 = ret[0];
        deferred2_1 = ret[1];
        return getStringFromWasm0(ret[0], ret[1]);
    } finally {
        wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
    }
}

export function drawPrices(ctx, nights) {
    wasm.drawPrices(ctx, nights);
}

And part of the imports that Rust calls:

__wbg_fillRect_0ef59adb9acb7d06: function(arg0, arg1, arg2, arg3, arg4) {
    arg0.fillRect(arg1, arg2, arg3, arg4);
},
__wbg_log_17c30ef363c61cf4: function(arg0) {
    console.log(arg0);
},

js-sys and web-sys

error[E0432]: unresolved import `web_sys::CanvasRenderingContext2d`
 --> src/lib.rs:2:24
  |
2 | use web_sys::{console, CanvasRenderingContext2d};
  |                        ^^^^^^^^^^^^^^^^^^^^^^^^ no `CanvasRenderingContext2d` in the root

The web-sys documentation on docs.rs lists, for every type, which features it needs.

📌 Closures: Rust as an event listener

A Rust function can become a JS callback through Closure. This needs the HtmlElement and EventTarget features:

#[wasm_bindgen(js_name = attachButton)]
pub fn attach_button(button: &web_sys::HtmlElement) -> Result<(), JsValue> {
    let click = Closure::<dyn FnMut()>::new(|| console::log_1(&"Book button clicked".into()));
    button.add_event_listener_with_callback("click", click.as_ref().unchecked_ref())?;
    click.forget(); // let the closure live as long as the page
    Ok(())
}

The size cost of the glue

Measured on one build of this crate with wasm-pack build --target web (release), adding one function per row. With other text or prices in the code, your build can differ by a few bytes:

What the crate holds .wasm .js glue
stayPrice only 13,590 bytes 4,122 bytes
+ greet (a String in and out) 15,497 bytes 6,994 bytes
+ log (web-sys console) 19,022 bytes 7,701 bytes
+ drawPrices (web-sys canvas) 22,102 bytes 11,776 bytes
+ attachButton (Closure) 23,049 bytes 14,091 bytes

From 13,590 bytes, those three extra functions take the .wasm to about 22 KB (22,102 bytes, 9,894 bytes gzipped). The base is already 13 KB for one multiplication: the allocator, the externref table and panic handling. format! for the text adds Rust's formatting machinery. web-sys itself holds thousands of APIs, but only the ones you call come along. With opt-level = "z", lto = true and codegen-units = 1 in [profile.release], the drawPrices version drops to 20,569 bytes. The Lab on this page runs that build.

📌 Who maintains it

The rustwasm GitHub organisation was archived in 2025. wasm-bindgen, js-sys and web-sys are now maintained in the wasm-bindgen organisation and keep shipping releases; the story is in the lesson "Wasm from Rust (wasm-pack)".

⚠️ Errors and costs that catch people out

TL;DR: wasm-bindgen generates glue on both sides: &str/String are copied as UTF-8 bytes (passStringToWasm0, getStringFromWasm0, then __wbindgen_free), JS objects such as ctx cross as they are, as an externref, and every Web API method Rust calls becomes a JS import (__wbg_fillRect_...). js-sys is for JS built-ins (Array, Date, Math, Promise) with no features; web-sys is for Web APIs (console, document, canvas, fetch), one Cargo feature per type, and a missing feature means error[E0432]. console::log_1 for console.log, CanvasRenderingContext2d with fill_rect and set_fill_style_str to draw. Closure::new makes a JS callback; dropping it too early means closure invoked recursively or after being dropped, so forget() it or keep it. The cost: stayPrice alone is 13,590 bytes, with strings, console and canvas 22,102 bytes (20,569 with opt-level = "z" and LTO). wasm-bindgen is maintained by the wasm-bindgen organisation since 2025.

⚡ A string in, a String out

Write:

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

Meaning: &str and String in Rust become string in JS. The glue wasm-bindgen generates copies the UTF-8 bytes: in through passStringToWasm0, out through getStringFromWasm0, and then the space is released with __wbindgen_free.

⚡ js-sys and web-sys

Write:

[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console", "CanvasRenderingContext2d"] }

Meaning: js-sys holds bindings to JavaScript's built-in objects (Array, Date, Math, Promise), with no features. web-sys holds bindings to Web APIs (console, document, canvas, fetch), one Cargo feature per type. Forget the feature and rustc refuses with error[E0432]: unresolved import.

⚡ JS objects cross as they are

Guess first: when drawPrices(ctx, 2) is called, is ctx copied into Wasm memory?

No. ctx is sent as it is, as an externref. Every time Rust calls fill_rect, Wasm calls the __wbg_fillRect_... import, and that import runs arg0.fillRect(...).

Meaning: In Rust, Web API methods are written Rust-style: fillRect becomes fill_rect, and fillStyle is set with set_fill_style_str. One drawPrices(ctx, 2) = 16 calls from Wasm to JS.

⚡ Don't drop the closure

Write:

let click = Closure::<dyn FnMut()>::new(|| console::log_1(&"Book button clicked".into()));
button.add_event_listener_with_callback("click", click.as_ref().unchecked_ref())?;
click.forget(); // let the closure live as long as the page

Meaning: Closure::new wraps a Rust closure as a JS function. If click is dropped when the function ends, the next click fails with Error: closure invoked recursively or after being dropped.

What you will learn