Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 13 · Testing, macros & unsafe

    13.4Rust & WebAssembly

    Why Rust is a popular choice for WebAssembly, how to compile a crate for the browser with wasm-bindgen and wasm-pack, what crossing the boundary costs, and when Wasm is worth it.

    About 25 minutesIntermediate

    On this page
    1. Concept map
    2. Write the logic as plain Rust first
    3. Export it with wasm-bindgen
    4. What crossing the boundary costs
    5. Which one should I use?
    6. Under the hood
    7. Common pitfalls
    8. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Running compiled code in the browserLoad a .wasm module built from another languageBlazor WebAssembly: the .NET runtime itself is compiled to Wasm and runs your assembliesCompile your crate to the wasm32-unknown-unknown target; there's no runtime or GC to ship
    Build toolsA bundler such as Vite, which can import the generated moduledotnet publish on a Blazor WebAssembly projectrustup target add wasm32-unknown-unknown, then wasm-pack build
    Exposing a function to the pageexport function[JSExport], or a [JSInvokable] method that the page calls with DotNet.invokeMethodAsync#[wasm_bindgen] pub fn
    Numbers across the boundarynumber, bigintint, double, longu32, f64 and friends: passed directly, nothing copied
    Text across the boundarystring, stored as UTF-16string, stored as UTF-16&str and String are UTF-8, so text is copied and re-encoded on every crossing
    What the browser downloadsYour bundled codeThe runtime, the trimmed framework libraries and your assembliesOne .wasm file plus a small generated glue module

    WebAssembly (Wasm) is a compact bytecode that every modern browser runs at close to native speed. TypeScript developers reach for Rust compiled to Wasm when a page has CPU-heavy work, like image processing, compression or parsing, or when the same logic must run in the browser and on the server.As a C# developer, you may know Wasm from Blazor WebAssembly, which runs C# in the browser by shipping the whole .NET runtime as a Wasm module. Rust compiles your code straight to Wasm instead, with no runtime and no garbage collector, so the download is usually kilobytes, not megabytes. This lesson builds a small Rust library for the browser, shows what happens at the boundary, and helps you decide when it’s worth it.

    Write the logic as plain Rust first

    A Wasm module is just a Rust library compiled for a different target. The logic you export is ordinary Rust, so write and test it natively first. Here’s a CPU-heavy function, a sieve that counts the primes up to a limit:

    TypeScript
    primes.ts
    function countPrimes(limit: number): number {
      const isComposite = new Uint8Array(limit + 1);
      let count = 0;
      for (let n = 2; n <= limit; n++) {
        if (isComposite[n]) continue;
        count++;
        for (let multiple = n * 2; multiple <= limit; multiple += n) {
          isComposite[multiple] = 1;
        }
      }
      return count;
    }
    
    console.log(countPrimes(1_000_000));
    C#
    Primes.cs
    Console.WriteLine(CountPrimes(1_000_000));
    
    static uint CountPrimes(uint limit)
    {
        var isComposite = new bool[limit + 1];
        uint count = 0;
        for (uint n = 2; n <= limit; n++)
        {
            if (isComposite[n]) continue;
            count++;
            for (uint multiple = n * 2; multiple <= limit; multiple += n)
            {
                isComposite[multiple] = true;
            }
        }
        return count;
    }
    Rust
    pub fn count_primes(limit: u32) -> u32 {
        let limit = limit as usize;
        let mut is_composite = vec![false; limit + 1];
        let mut count = 0;
        for n in 2..=limit {
            if is_composite[n] {
                continue;
            }
            count += 1;
            for multiple in (n * 2..=limit).step_by(n) {
                is_composite[multiple] = true;
            }
        }
        count
    }
    
    fn main() {
        println!("{}", count_primes(1_000_000));
    }

    Output

    78498

    Nothing here knows about the browser. That’s the point: you can test count_primes with cargo test on your machine, call it from a native program or a server, and export the same function to the page.

    Here’s a second function, one that takes and returns text:

    pub fn slugify(title: &str) -> String {
        let mut slug = String::new();
        for ch in title.chars().flat_map(char::to_lowercase) {
            if ch.is_alphanumeric() {
                slug.push(ch);
            } else if !slug.is_empty() && !slug.ends_with('-') {
                slug.push('-');
            }
        }
        slug.trim_end_matches('-').to_string()
    }
    
    fn main() {
        println!("{}", slugify("Rust & WebAssembly: Getting Started"));
    }

    Output

    rust-webassembly-getting-started

    Export it with wasm-bindgen

    Raw WebAssembly functions can only take and return numbers. wasm-bindgen fills the gap: you mark functions with #[wasm_bindgen], and it generates glue code that converts strings, arrays and structs, plus a .d.ts file with the types. wasm-pack runs the whole build: it compiles your crate for the Wasm target, runs wasm-bindgen, and writes a ready-to-import package.

    Set up once:

    rustup target add wasm32-unknown-unknown
    cargo install wasm-pack
    

    The crate is a library, built as a cdylib (a library for other languages to load) and also as a normal rlib, so native tests and other Rust crates can still use it:

    [package]
    name = "primes"
    version = "0.1.0"
    edition = "2024"
    
    [lib]
    crate-type = ["cdylib", "rlib"]
    
    [dependencies]
    wasm-bindgen = "0.2"
    

    The exports are a thin layer over the plain functions:

    use wasm_bindgen::prelude::*;
    
    mod logic; // count_primes and slugify from above: plain Rust, no wasm-bindgen
    
    #[wasm_bindgen]
    pub fn count_primes(limit: u32) -> u32 {
        logic::count_primes(limit)
    }
    
    #[wasm_bindgen]
    pub fn slugify(title: &str) -> String {
        logic::slugify(title)
    }

    Build it:

    wasm-pack build --target web
    

    --target web produces a plain ES module that loads in the browser with no bundler plugin. (The default, --target bundler, is for bundlers that understand .wasm imports, and --target nodejs is for server-side code.) The build is optimized by default, and the output goes in pkg/:

    pkg/
    ├── package.json
    ├── primes.js           glue code: loads the .wasm file and converts arguments
    ├── primes.d.ts         types for every export
    ├── primes_bg.wasm      your compiled Rust
    └── primes_bg.wasm.d.ts
    

    The generated types match your Rust signatures. Function names stay exactly as written in Rust (add #[wasm_bindgen(js_name = countPrimes)] if you want camelCase):

    export function count_primes(limit: number): number;
    export function slugify(title: string): string;
    

    Import it like any module. The default export, init, downloads and compiles the .wasm file; call it once before using the other exports:

    main.ts
    import init, { count_primes, slugify } from "./pkg/primes.js";
    
    await init();
    console.log(count_primes(1_000_000));
    console.log(slugify("Rust & WebAssembly: Getting Started"));

    With --target bundler, a bundler with Wasm support (such as Vite with a Wasm plugin, or webpack) handles loading, and you import the functions without calling init.

    The browser loads the package as a JavaScript module. A Blazor WebAssembly app can call it through a small JavaScript file in wwwroot that imports pkg/primes.js, calls its default export init() once, and re-exports the functions (here as countPrimes). From C#, you load that file with IJSRuntime and call it like any other JavaScript interop:

    Primes.razor.cs
    // In a Blazor component, with @inject IJSRuntime JS
    await using var module = await JS.InvokeAsync<IJSObjectReference>("import", "./primes-interop.js");
    uint count = await module.InvokeAsync<uint>("countPrimes", 1_000_000u);

    Every call goes from .NET’s Wasm module, through JavaScript, into Rust’s Wasm module and back, so this pays off only for big pieces of work per call. More often, Rust Wasm shows up in C# shops on the front end of a site that isn’t Blazor, or in an edge or plugin runtime that runs Wasm.

    What crossing the boundary costs

    A Wasm module has its own block of memory, called linear memory: one big byte array. Wasm functions pass numbers directly: 32- and 64-bit integers and floats. (Newer engines can also pass opaque references to objects on the page, which wasm-bindgen uses for handles.) Text, arrays and structs have no Wasm type, so their bytes have to be copied into or out of linear memory.

    Rust type in an exportType on the pageWhat happens on each call
    u32, i32, f64, f32numberPassed directly. No copy, no allocation.
    u64, i64bigintPassed directly.
    boolbooleanPassed as 0 or 1.
    &str, StringstringRe-encoded from UTF-16 to UTF-8 and copied into linear memory (or back out).
    &[u8], Vec<u8>Uint8ArrayCopied into or out of linear memory.
    &[f64], Vec<f64>Float64ArrayCopied into or out of linear memory.

    Strings cost the most, because the two sides don’t even store text the same way. TypeScriptC# strings are UTF-16: most characters take 2 bytes, and characters outside the Basic Multilingual Plane, like emoji, take two 16-bit units. Rust strings are UTF-8: 1 to 4 bytes per character. Count the same text both ways:

    TypeScript
    encodings.ts
    const text = "naïve 👋";
    console.log(`UTF-16 units: ${text.length}`);
    console.log(`UTF-8 bytes: ${new TextEncoder().encode(text).length}`);
    C#
    Encodings.cs
    using System.Text;
    
    var text = "naïve 👋";
    Console.WriteLine($"UTF-16 units: {text.Length}");
    Console.WriteLine($"UTF-8 bytes: {Encoding.UTF8.GetByteCount(text)}");
    Rust
    let text = "naïve 👋";
    println!("UTF-16 units: {}", text.encode_utf16().count());
    println!("UTF-8 bytes: {}", text.len());

    Output

    UTF-16 units: 8
    UTF-8 bytes: 11

    Here’s how the bytes of naïve differ:

    let word = "naïve";
    println!("UTF-16: {} bytes", word.encode_utf16().count() * 2);
    println!("UTF-8: {} bytes", word.len());

    Output

    UTF-16: 10 bytes
    UTF-8: 6 bytes
    The same word in UTF-16 and UTF-8
    The same word in UTF-16 and UTF-8: each row is one value; each cell's width is its size in bytes.
    Value0123456789Size
    UTF-16n2 bytesa2 bytesï2 bytesv2 bytese2 bytes10 bytes
    UTF-8n1 bytea1 byteï2 bytesv1 bytee1 byte6 bytes

    The word naïve stored two ways. In UTF-16, each of the five characters takes 2 bytes, 10 bytes in all. In UTF-8, n, a, v and e take 1 byte each and ï takes 2, 6 bytes in all. Because the bytes differ, text can't be shared between the page and the Wasm module: it has to be re-encoded and copied on every call.

    So one call to slugify("Rust & WebAssembly: Getting Started") does all of this:

    1. The glue code allocates space in linear memory and encodes the string into it as UTF-8.
    2. Rust runs slugify on a &str that points into that space.
    3. Rust returns a String whose bytes are in linear memory.
    4. The glue code decodes those bytes into a new UTF-16 string. Both buffers in linear memory are then freed: the argument’s by the Rust side, the result’s by the glue code.

    For a short title like this one that’s cheap, but it’s more work than the slugify itself. Strings & UTF-8 covers why Rust uses UTF-8 and what .len() really counts.

    The rule that follows: cross the boundary rarely, with a lot of work per crossing. Pass a whole image or document in one call, not one pixel or one word per call. Numbers are cheap to pass; strings and arrays are copied every time.

    Which one should I use?

    WhatWhenWhyHow
    Keep it in TypeScriptthe page's own codeDOM updates, UI logic, network calls, small functions.The browser’s APIs are native to itthe page's JavaScript; Wasm would reach them through glue code.Write it as usual, and measure before porting.
    Rust on wasm32-unknown-unknown with wasm-bindgenCPU-heavy work on numbers or bytes: images, audio, compression, parsing, simulation, crypto.Predictable speed, no GC pauses, a small download.wasm-pack build --target web, then import pkg/.
    The same Rust crate natively and in WasmLogic that must give identical results on the server and in the browser: validation, a parser, a pricing or rules engine.One implementation, tested once with cargo test.Plain functions in the crate; a thin #[wasm_bindgen] layer for the browser build.
    Rust on wasm32-wasip2 (WASI)Wasm outside the browser: plugin systems, edge and serverless runtimes, sandboxed tools.WASI gives Wasm files, clocks and sockets in a standard, sandboxed way.rustup target add wasm32-wasip2, then run in a runtime such as Wasmtime.

    Rule of thumb: use Wasm for heavy computation that runs in a few large calls, or for logic you must share with a Rust back end. Keep UI and DOM work in TypeScriptthe page's own code. And profile first: modern engines run plain TypeScriptJavaScript fast, and a port that crosses the boundary too often can end up slower.

    Should this be Wasm?
    1. Is the work mostly updating the page: the DOM, events, layout?

      Yes

      Keep it out of WasmWasm reaches the DOM only through glue code, so every call adds cost and nothing gets faster.

      No
    2. Is it a small function called many times, each call passing strings or arrays?

      Yes

      Keep it out of Wasm, or batch the callsCopying and re-encoding the arguments can cost more than the work. Pass one big batch per call instead.

      No
    3. Must the browser and a Rust server give identical results: validation, parsing, pricing?

      Yes

      Use WasmCompile the same crate for both, so the rules can't drift apart.

      No
    4. Is it CPU-heavy work on numbers or bytes, such as images, audio, compression or simulation?

      Yes

      Use Wasm, and measurePass large buffers in a few calls. Run it in a Web Worker if it takes long enough to freeze the page.

      No
    5. Otherwise: Keep it in the language the rest of the page uses. Port it only after a profiler shows a CPU-bound hotspot.

    Under the hood

    wasm32-unknown-unknown means: 32-bit WebAssembly, no particular vendor, no operating system. That last part shapes what works:

    • Pointers and usize are 32 bits wide, and linear memory can grow up to 4 GiB.
    • There’s no operating system, so parts of std can’t work. println! output goes nowhere, std::fs returns errors, std::thread::spawn fails, and std::time::Instant::now() panics. Use the browser’s APIs instead, through the web-sys crate (the DOM, console, fetch) and js-sys (built-in objects such as Date and Math).
    • A panic becomes a trap. The call throws a RuntimeError about an unreachable instruction, which doesn’t say what went wrong. Add the console_error_panic_hook crate during development to log the panic message to the browser console.
    • There’s no garbage collector. Rust frees memory as usual, through ownership, inside linear memory. The module ships a small allocator for that, compiled from Rust, with no runtime to download.

    That last point is the main difference from Blazor WebAssembly. Blazor ships the .NET runtime compiled to Wasm, including its garbage collector, plus your assemblies and the trimmed framework libraries, and by default runs your code with an interpreter (AOT compilation is optional and makes the download bigger). Rust compiles your code itself to Wasm instructions ahead of time, so the .wasm file contains only your code, the parts of std it uses, and that allocator.

    You can also skip wasm-bindgen entirely. Build with cargo build --target wasm32-unknown-unknown --release and export functions the C way, with #[unsafe(no_mangle)] pub extern "C" fn from the unsafe & FFI lesson. That works for functions that only take and return numbers, and you load the file with the browser’s WebAssembly.instantiateStreaming. wasm-bindgen is the layer that adds strings, arrays, structs and the generated types.

    Common pitfalls

    Common pitfallWasm isn't automatically faster

    Browser engines compile hot code to fast machine code too. Wasm wins on long-running numeric work with predictable memory use; it loses when calls are small and frequent, because every string or array argument is copied. Measure the whole round trip, boundary included, against the version you have now.

    Common pitfallFree exported structs yourself

    A #[wasm_bindgen] struct shows up on the page as a class instance that holds a pointer into linear memory. The generated code registers each instance with a FinalizationRegistry, so the Rust value is usually freed eventually, but the page’s garbage collector sees only that small object, not the memory the Rust value owns. It may clean up late or never: finalization callbacks aren’t guaranteed to run. Call the generated free() method when you’re done with the instance, or declare it with using, since the generated class also has a [Symbol.dispose]() method. Plain functions that take and return values, like the ones in this lesson, need no cleanup.

    Common pitfallCode that works natively can panic in the browser

    Instant::now(), thread::spawn and file access compile for wasm32-unknown-unknown but fail at run time, because there’s no operating system underneath. Keep that kind of code out of the crate you export, and test the Wasm build in a browser, not just natively: tests marked #[wasm_bindgen_test] (from the wasm-bindgen-test crate) run in a real one with wasm-pack test --headless --firefox.

    Try it yourself

    Exercise: port this to Rust

    Port this function, which turns RGBA pixels (red, green, blue and alpha, one byte each) to grayscale, into a Rust function grayscale(pixels: &[u8]) -> Vec<u8> that you could export to the browser. It uses integer weights for the gray value and keeps each pixel’s alpha.

    Starting code in TypeScript
    grayscale.ts
    function grayscale(pixels: Uint8Array): Uint8Array {
      const result = new Uint8Array(pixels.length);
      for (let i = 0; i + 3 < pixels.length; i += 4) {
        const red = pixels[i] ?? 0;
        const green = pixels[i + 1] ?? 0;
        const blue = pixels[i + 2] ?? 0;
        const gray = (77 * red + 150 * green + 29 * blue) >> 8;
        result.set([gray, gray, gray, pixels[i + 3] ?? 0], i);
      }
      return result;
    }
    
    const pixels = new Uint8Array([255, 0, 0, 255, 0, 255, 0, 128]);
    console.log(grayscale(pixels).join(" "));
    Starting code in C#
    Grayscale.cs
    byte[] pixels = [255, 0, 0, 255, 0, 255, 0, 128];
    Console.WriteLine(string.Join(" ", Grayscale(pixels)));
    
    static byte[] Grayscale(byte[] pixels)
    {
        var result = new byte[pixels.Length];
        for (int i = 0; i + 3 < pixels.Length; i += 4)
        {
            var gray = (byte)((77 * pixels[i] + 150 * pixels[i + 1] + 29 * pixels[i + 2]) >> 8);
            result[i] = gray;
            result[i + 1] = gray;
            result[i + 2] = gray;
            result[i + 3] = pixels[i + 3];
        }
        return result;
    }

    Expected output

    76 76 76 255 149 149 149 128
    Show a hint

    Take pixels as a byte slice and return a Vec of bytes. Walk it four bytes at a time with chunks_exact(4), compute the gray value in u32 so it can't overflow, and push gray three times followed by the original alpha.

    Show a solution
    fn grayscale(pixels: &[u8]) -> Vec<u8> {
        let mut result = Vec::with_capacity(pixels.len());
        for pixel in pixels.chunks_exact(4) {
            let [red, green, blue] = [pixel[0], pixel[1], pixel[2]].map(u32::from);
            let gray = ((77 * red + 150 * green + 29 * blue) >> 8) as u8;
            result.extend_from_slice(&[gray, gray, gray, pixel[3]]);
        }
        result
    }
    
    fn main() {
        let pixels = [255, 0, 0, 255, 0, 255, 0, 128];
        let gray: Vec<String> = grayscale(&pixels).iter().map(u8::to_string).collect();
        println!("{}", gray.join(" "));
    }

    A &[u8] parameter and a Vec<u8> return value are exactly what wasm-bindgen maps to a Uint8Array in and a new Uint8Array out, so this function can be exported unchanged with #[wasm_bindgen]. The whole image crosses the boundary once each way, which is the pattern that makes Wasm worth it. chunks_exact also guarantees every chunk has four bytes, so the indexing can't go out of range.

    Saved in this browser only.