Rust Recipes is a problem-oriented series of articles that assist developers while learning Rust. Every article solves simple, everyday development tasks using the Rust standard library or leveraging popular and proven crates.

Question: How to compile a Rust program to WebAssembly and run it outside the browser?

Rust can compile to WebAssembly out of the box. For programs that run outside the browser, the target to use is wasm32-wasip2. It builds against WASI 0.2, the WebAssembly System Interface, which gives Wasm access to things like command-line arguments, environment variables, files and clocks. To run the result, we use Wasmtime , the reference runtime from the Bytecode Alliance.

First, let’s install the target and Wasmtime:

BASH
# Add the WASI 0.2 target to your Rust toolchain
rustup target add wasm32-wasip2
# Install Wasmtime (Linux and macOS)
curl https://wasmtime.dev/install.sh -sSf | bash

Write a Regular Rust Program

The nice part: there’s nothing Wasm-specific about the code. This program reads an argument, an environment variable and a file, using nothing but the standard library:

RUST
use std::{env, fs};

fn main() {
    let name = env::args().nth(1).unwrap_or_else(|| "world".to_string());
    println!("Hello, {name}! Running on {}", env::consts::ARCH);

    match env::var("GREETING_MODE") {
        Ok(mode) => println!("mode: {mode}"),
        Err(_) => println!("mode: not set"),
    }

    match fs::read_to_string("data/items.txt") {
        Ok(items) => println!("found {} items", items.lines().count()),
        Err(e) => println!("could not read items: {e}"),
    }
}

Build and Run

To compile for WebAssembly, pass the target to cargo build. The result is a .wasm file in the target-specific output folder:

BASH
cargo build --target wasm32-wasip2 --release
wasmtime run target/wasm32-wasip2/release/wasm-demo.wasm Thorsten

Everything after the .wasm file is passed to the program as arguments. Assuming there’s a data/items.txt file next to Cargo.toml, the output looks like this:

TEXT
Hello, Thorsten! Running on wasm32
mode: not set
could not read items: No such file or directory (os error 44)

The argument arrived, but the environment variable and the file didn’t. That’s not a bug, it’s the most important property of WebAssembly.

Grant Access Explicitly

A Wasm program runs in a sandbox and starts with no access to the host: no environment variables, no files, no network. Everything has to be granted when starting it. With Wasmtime, --env passes an environment variable and --dir makes a host directory available inside the sandbox:

BASH
wasmtime run \
  --env GREETING_MODE=friendly \
  --dir data::data \
  target/wasm32-wasip2/release/wasm-demo.wasm Thorsten

--dir data::data maps the host directory data to the path data inside the sandbox (HOST_DIR::GUEST_DIR). Now the program sees everything it needs:

TEXT
Hello, Thorsten! Running on wasm32
mode: friendly
found 3 items

The program can only reach the directory we handed it. Any file outside of data simply doesn’t exist from its point of view. This capability-based model is why WebAssembly is such a good fit for running untrusted code or plugins.

Make cargo run Work

Typing the full Wasmtime command gets old quickly. Cargo can use Wasmtime as a runner for the Wasm target, so cargo run builds and runs in one step. Create a .cargo/config.toml in the project:

TOML
[build]
target = "wasm32-wasip2"

[target.wasm32-wasip2]
runner = "wasmtime run --dir data"

The [build] section makes wasm32-wasip2 the default target for this project, and runner tells Cargo to start every binary built for it through Wasmtime. Arguments after -- reach the program as usual:

BASH
cargo run -- Thorsten

A Component, Not Just a Module

The wasm32-wasip2 target produces a WebAssembly component rather than a plain core module. Components describe their imports and exports with typed interfaces, which lets them be composed with other components, regardless of the language they were written in. That’s also the foundation Spin builds on, as shown in Component Composition with Spin 4.0 .

Recap

Compiling Rust to WebAssembly takes one extra target: install wasm32-wasip2, build with --target wasm32-wasip2 and run the .wasm file with wasmtime run. Standard library features like arguments, environment variables and files work as usual, but only for what you grant with --env and --dir. A Cargo runner in .cargo/config.toml turns it into a plain cargo run.