Rust-Wasm Outside the Browser
local graph
Chapter 15 — Rust-Wasm Outside the Browser
Section titled “Chapter 15 — Rust-Wasm Outside the Browser”Chapter 15 – Rust-Wasm Outside the Browser
Section titled “Chapter 15 – Rust-Wasm Outside the Browser”WebAssembly isn’t confined to the browser—its portability makes it a natural fit for edge computing, serverless functions, and standalone CLI tools via WASI.
15.1: Edge & Serverless Runtimes
Section titled “15.1: Edge & Serverless Runtimes”Running Rust-Wasm at the network edge or in serverless environments brings your logic closer to users—delivering sub-10 ms latency, automatic scaling, and the same safety sandbox as the browser.
flowchart TD
Section titled “flowchart TD”A[Write core Rust lib] —> B[Compile to Wasm (wasm-pack/cargo)] B —> C[Integrate with Worker adapter] C —> D[Deploy via Wrangler / deno deploy] D —> E[Global edge network serves Wasm on request]
1. Why Edge & Serverless for Wasm?
Section titled “1. Why Edge & Serverless for Wasm?”- Low latency: Code runs in PoPs around the globe—faster than a central server.
- Auto-scaling: No need to manage containers; functions spin up on demand.
- Uniform sandbox: Edge runtimes enforce the same safety guarantees as browsers.
- Cost-effective: You pay only for actual invocations, often in micro-dollar increments.
2. Cloudflare Workers with Rust-Wasm
Section titled “2. Cloudflare Workers with Rust-Wasm”Cloudflare Workers natively support Wasm modules, with a small adapter layer.
A. Prerequisites
Section titled “A. Prerequisites”- wrangler CLI (
npm i -g wrangler) - A Cloudflare account and API token
B. Project Initialization
Section titled “B. Project Initialization”wrangler init my-wasm-worker --template=rustcd my-wasm-workerThis scaffolds:
my-wasm-worker/├── src/lib.rs # your Rust handler├── Cargo.toml└── wrangler.tomlC. Writing Your Handler
Section titled “C. Writing Your Handler”In src/lib.rs:
use worker::*;
#[event(fetch)]pub async fn main(req: Request, _env: Env) -> Result<Response> { // Simple compute in Rust let count = req.headers().get("x-count")? .and_then(|v| v.parse::<u32>().ok()) .unwrap_or(1); let result = (0..count).fold(0, |a, b| a + b);
Response::ok(format!("Sum 0..{} = {}", count, result))}D. Configuration (wrangler.toml)
Section titled “D. Configuration (wrangler.toml)”Ensure wasm_module points to the compiled Wasm:
name = "my-wasm-worker"type = "javascript" # Wrangler will bundle your Wasmaccount_id = “<YOUR_ACCOUNT_ID>” workers_dev = true compatibility_date = “2025-11-07”
E. Build & Deploy
Section titled “E. Build & Deploy”Build the Rust/Wasm
Section titled “Build the Rust/Wasm”wrangler build
Preview locally
Section titled “Preview locally”wrangler dev
Publish globally
Section titled “Publish globally”wrangler publish
Your worker now runs worldwide. Each HTTP request invokes your Rust code with millisecond cold starts.
3. Deno Deploy for Wasm APIs
Section titled “3. Deno Deploy for Wasm APIs”Deno Deploy supports ES-module-style Wasm imports, making it easy to offer Wasm-powered endpoints.
A. Compile to Browser-Target Wasm
Section titled “A. Compile to Browser-Target Wasm”In your Rust crate:
wasm-pack build --target web --release --out-dir pkgB. Write a Deno Server Script (app.ts)
Section titled “B. Write a Deno Server Script (app.ts)”import init, { heavy_compute } from "./pkg/your_crate.js";
await init(); // instantiate Wasm once
Deno.serve((req) => { // Example: compute fib(30) const result = heavy_compute(30); return new Response(`Result: ${result}`, { headers: { "Content-Type": "text/plain" }, });});C. Deploy
Section titled “C. Deploy”deno deploy --project=my-wasm-api app.tsDeno Deploy spins up your script at the edge—each request hits your Wasm-backed heavy_compute function.
4. Case Study: Real-Time Image Resizing
Section titled “4. Case Study: Real-Time Image Resizing”Scenario: A photo-sharing site needed on-the-fly thumbnail generation.
Approach:
- Core Rust lib for image decode/resize in Wasm.
- Cloudflare Worker for browser-triggered small thumbnails (fast, cheap).
- Deno Deploy for larger sizes or batch processing (flexible, logged).
Outcome: Edge resizing cut average request latency from 200 ms to 25 ms, and off-loaded CPU from origin servers.
5. Personal Insights
Section titled “5. Personal Insights”- Warm starts: Cloudflare Workers have extremely low cold-start (~5 ms) for small Wasm modules—ideal for microservices.
- Shared caching: Both Workers and Deno cache your Wasm artifacts globally—subsequent fetches hit in-memory cache.
- Logging & metrics: Use Cloudflare’s built-in logging or Deno’s telemetry to monitor execution durations and error rates.
- Fallbacks: Always provide a minimal JavaScript path if edge runtime fails (e.g., during local dev).
- Edge runtimes like Cloudflare Workers and Deno Deploy let you run Rust–Wasm globally with minimal ops.
- Wrangler and Deno CLI integrate smoothly with your Wasm builds.
- Case studies show dramatic latency improvements for compute-heavy endpoints.
15.2: WASI and Standalone Applications
Section titled “15.2: WASI and Standalone Applications”While WebAssembly first gained fame in the browser, WASI (WebAssembly System Interface) lets you write portable CLI tools and server applications in Rust that run anywhere a WASI runtime exists. You get the safety and sandboxing of Wasm plus controlled access to files, environment, and network. Let’s walk through how to build, run, and package standalone Wasm apps with WASI.
flowchart LR A[Write Rust CLI crate] —> B[Configure Cargo.toml for WASI] B —> C[Build with target wasm32-wasi] C —> D[Run in WASI runtime (Wasmtime/Wasmer)] D —> E[Access FS, env vars, sockets via WASI APIs] E —> F[Distribute .wasm binary as standalone app]
1. Why WASI?
Section titled “1. Why WASI?”- Portability: Single
.wasmruns on Windows, Linux, macOS—no native dependencies. - Sandboxed Safety: Only capabilities you explicitly grant—no arbitrary syscalls.
- Unified Tooling: Use
cargo buildand familiar Rust crates, then execute with any WASI-compatible runtime (Wasmtime, Wasmer, WasmEdge).
Insight: I replaced a native Go CLI with WASI, cutting download size in half and unifying builds for three operating systems in a single artifact.
2. Project Setup
Section titled “2. Project Setup”A. Cargo Configuration
Section titled “A. Cargo Configuration”In your Cargo.toml:
[package]name = "wasi-app"version = "0.1.0"edition = "2021"
[lib]crate-type = ["cdylib"]
[dependencies]# Any crates you need, e.g. serde, anyhow, etc.B. Add WASI Target
Section titled “B. Add WASI Target”rustup target add wasm32-wasi3. Writing a WASI-Aware Main
Section titled “3. Writing a WASI-Aware Main”In src/lib.rs or src/main.rs:
use std::env;use std::fs::File;use std::io::{self, Read, Write};
fn run() -> anyhow::Result<()> { let args: Vec<String> = env::args().collect(); let path = args.get(1) .ok_or_else(|| anyhow::anyhow!("Usage: wasi-app <input-file>"))?; let mut file = File::open(path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let line_count = contents.lines().count(); writeln!(io::stdout(), "Lines in {}: {}", path, line_count)?; Ok(())}
// Export `run` as the entry point#[no_mangle]pub extern “C” fn _start() {
// WASI convention calls _start with no args; handle errors
if let Err(e) = run() {
eprintln!(“Error: {}”, e);
std::process::exit(1);
}
}
_startis the default WASI entrypoint.- Use standard Rust FS and env-var APIs; WASI implements them under the hood.
4. Building and Running
Section titled “4. Building and Running”A. Build
Section titled “A. Build”cargo build --target wasm32-wasi --releaseGenerates: target/wasm32-wasi/release/wasi_app.wasm
B. Execute in a Runtime
Section titled “B. Execute in a Runtime”Using Wasmtime:
Section titled “Using Wasmtime:”wasmtime target/wasm32-wasi/release/wasi_app.wasm --input.txtUsing Wasmer:
Section titled “Using Wasmer:”wasmer run target/wasm32-wasi/release/wasi_app.wasm --input.txtBoth runtimes provide WASI’s host functions for file I/O and environment access.
5. Advanced WASI Capabilities
Section titled “5. Advanced WASI Capabilities”A. Filesystem & Preopens
Section titled “A. Filesystem & Preopens”Control which host directories your Wasm can see:
wasmtime --dir=. wasi_app.wasm -- input.txtThe --dir=. flag “preopens” the current directory, allowing File::open("input.txt") inside Wasm.
B. Environment Variables
Section titled “B. Environment Variables”Pass env vars:
FOO=bar wasmtime wasi_app.wasm -- input.txtInside Rust, env::var("FOO") returns “bar”.
C. Networking (Preview)
Section titled “C. Networking (Preview)”Some runtimes offer WASI preview networking:
use anyhow::Result;use std::net::TcpStream;
fn net_example() -> Result<()> { let mut stream = TcpStream::connect("example.com:80")?; stream.write_all(b"GET / HTTP/1.0\r\n\r\n")?; let mut resp = String::new(); stream.read_to_string(&mut resp)?; println!("{}", resp); Ok(())}Run with Wasmtime’s experimental networking support:
wasmtime --enable-preview --allow-net wasi_app.wasm -- input.txt6. Packaging and Distribution
Section titled “6. Packaging and Distribution”- Single Artifact: Distribute the
.wasmfile—users need only a WASI runtime. - Docker Image: Bundle Wasm + Wasmtime in a lightweight container for CI or server use:
- FROM scratch
- COPY —from=bytecodealliance/wasmtimelatest /usr/local/bin/wasmtim /usr/local/bin/wasmtim
- COPY target/wasm32-wasi/release/wasi_app.wasm /app/
- ENTRYPOINT [“wasmtim”, “/app/wasi_app.wasm”]
- NPM Distribution: Optionally, wrap the Wasm in an npm package with a JS loader using @wasmer/wasi or @wasmer/wasmfs for Node integration.
- Case Study: Cross-Platform Log Analyzer
Scenario: A CLI tool to parse multi-GB log files needed to run on developer machines (macOS, Linux) without native installs.
Solution:
- Built in Rust targeting wasm32-wasi.
- Published log-analyzer.wasm on GitHub Releases.
- Developers installed Wasmtim once, then ran wasmtim log-analyzer.wasm logs/.
Result: Onboarding time dropped to under five minutes—no Rust toolchain or native dependencies required on user machines.
Key Takeaways
- WASI brings file, env, and socket capabilities to Wasm—write portable Rust apps.
- Cargo target wasm32-wasi plus cdylib crate type compiles your CLI to Wasm.
- Runtimes like Wasmtim and Wasmer execute your Wasm with familiar flags for preopens and env.
- Distribution is as simple as shipping one .wasm file plus a runtime; containerization offers production-grade deployment.
15.3: Sharing Logic Across Client and Server
Section titled “15.3: Sharing Logic Across Client and Server”When you centralize business logic—parsing, validation, algorithms—into a single Rust library, you eliminate duplication, reduce bugs, and ensure consistency between your front-end and back-end. By compiling that core crate both to browser Wasm and to a WASI or native server binary, you get the same code running everywhere. Let’s explore how.
flowchart LR A[core-lib/src/lib.rs] —>|wasm-pack build| B[browser-app/pkg/core_lib.js + .wasm] A —>|cargo build wasm32-wasi| C[server-app/core_lib.wasm] B & C —> D[Import in client & server apps]
1. Project Structure
Section titled “1. Project Structure”Use a Cargo workspace:
my-workspace/ ├── core-lib/ # Shared Rust library │ ├── Cargo.toml │ └── src/lib.rs ├── browser-app/ # Front-end web app │ ├── pkg/ # wasm-pack output │ ├── src/index.js │ └── index.html └── server-app/ # Server or CLI ├── Cargo.toml └── src/main.rs
### A. core-lib/Cargo.toml
```toml[package]name = "core_lib"version = "0.1.0"edition = "2021"
[lib]name = "core_lib"path = "src/lib.rs"crate-type = ["cdylib", "rlib"][dependencies] serde = { version = “1.0”, features = [“derive”] }
B. Shared Logic (core-lib/src/lib.rs)
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)] pub struct Record { pub id: u32, pub value: String, }
/// A shared parsing function: CSV -> Vec
- Browser-Side Integration
A. Build Wasm Package
cd browser-app wasm-pack build ../core-lib —target web —out-dir pkg
This produces pkg/core_lib.js, pkg/core_lib_bg.wasm, and pkg/core_lib.d.ts.
B. Front-End Code (browser-app/src/index.js)
import init, { parse_records } from ’../pkg/core_lib.js’;
async function run() {
await init(); // instantiate Wasm
const csv = id,value\n1,foo\n2,bar;
const records = parse_records(csv);
console.table(records);
}
run().catch(console.error);
Embed in index.html:
- Server-Side Integration
A. Build WASI Binary
cd server-app cargo build —release —target wasm32-wasi
B. Server Code (server-app/src/main.rs)
use std::fs; use core_lib::parse_records;
fn main() -> anyhow::Result<()> { let csv = fs::read_to_string(“data.csv”)?; let records = parse_records(&csv)?; for rec in records { println!(“Record {} -> {}”, rec.id, rec.value); } Ok(()) }
Or, for a native server:
Add in server-app/Cargo.toml
Section titled “Add in server-app/Cargo.toml”[dependencies] core_lib = { path = ”../core-lib” }
Then build normally:
cargo run — data.csv
- Consistency and Testing
- Unit-test in core-lib, e.g.:
rust #[cfg(test)] mod tests { use super::*; #[test] fn test_parse() { let csv = “id,value\n1,foo”; let recs = parse_records(csv).unwrap(); assert_eq!(recs[0].id, 1); } }
- Tests run once and guarantee both your front-end and back-end use identical behavior.
---
## 5. Case Study: Shared Validation in E-Commerce
**Scenario:** An order-entry system needed to validate coupon codes and calculate discounts on both client and server to prevent mismatches.
**Approach:**
1. Moved all discount-logic into `core-lib::apply_coupon(code: &str, total: f64) -> f64`.2. Used it in the React WebAssembly UI for live price updates.3. Used the same function in the serverless checkout Lambda (via WASI) to confirm server-side totals.
**Result:** Eliminated pricing inconsistencies, cut bug reports by 80%, and accelerated development since only one logic implementation existed.
---
## 6. Personal Insights
- Avoid platform-specific code in `core-lib`; keep it pure logic so it compiles everywhere.- Use feature flags for minor platform differences (e.g., file-I/O only in server-app).- CI builds should compile both targets and run core-lib tests to catch mismatches early.
<!-- page: 187 -->
- **Documentation**: clearly indicate that consumers can import in JS or link as a WASI library—bridging the gap for less-experienced users.
---
**Recap**
- Structure your workspace with a core-lib shared crate.- Compile to both browser Wasm (via wasm-pack) and WASI/native server binaries.- Import the same functions in client JavaScript and server Rust, ensuring identical behavior.- Test once in core-lib; reap consistency benefits everywhere.
By sharing logic across client and server, you streamline development, reduce duplication, and deliver a cohesive experience end-to-end.
<!-- page: 188 -->
# APPENDICIES
Below are the appendices you can tuck at the back of your book—compact quick references, checklists, and resources to keep at your fingertips as you build Rust→Wasm applications.
---
## A: API Quick Reference
### 1. wasm-bindgen Essentials
- `#[wasm_bindgen]` - Expose Rust functions, structs, enums to JS.- `#[wasm_bindgen(start)]` - Runs once on module instantiation. Great for one-time setup (e.g., thread pool init).- `JsValue` - The universal JS value container; use for passing JSON, strings, objects.- `Closure::wrap / .forget()` - Turn a Rust closure into a JS callback; `.forget()` keeps it alive.- Memory access helpers - `wasm_bindgen::memory()` → access WebAssembly.Memory in JS. - Zero-copy with `[u8]` or `&mut [T]` parameters.
### 2. js-sys Highlights
- `js_sys::Array / Object` - Create and manipulate generic JS arrays/objects from Rust.- `js_sys::Function` - Wrap/inspect JS functions in Rust.- `Promise / Promise::then` - Work with JS promises; convert to Rust futures via `wasm_bindgen_futures`.- `Reflect / JsString` - Low-level property access and string conversions.
---
<!-- page: 189 -->
# 3. web-sys Common Modules
- **DOM** - `window()` → Window; `document()` → Document; `get_element_by_id` → Element. - Element casts: `.dyn_into::<HTMLElement>()`.
- **Canvas** - HtmlCanvasElement + CanvasRenderingContext2d for immediate graphics.
- **Fetch & Streams** - `window().fetch_with_str()` → Promise<Response>; Response::array_buffer() for binary.
- **WebSocket** - WebSocket::new(url); set binary_type; .set_onmessage, .set_onerror.
- **Performance & Timers** - `window().performance()` → high-precision timestamps; request_animation_frame.
---
# B: Troubleshooting Checklist
1. **Compilation Errors** - ✅ Did you add `wasm32-unknown-unknown` via `rustup target add`? - ✅ Is `crate-type = ["cdylib"]` in your `Cargo.toml`?
2. **Missing Functions in JS** - ✅ Have you annotated your functions with `#[wasm_bindgen]`? - ✅ Did you re-run `wasm-pack build` after changes?
3. **Runtime Panics / Traps** - ✅ Check console for “wasm trap” messages. - ✅ Wrap fallible logic in `Result` and convert to `JsValue`.
4. **Closure Lifetimes** - ✅ Did you call `.forget()` on closures you want to persist? - ✅ Remember to remove listeners with `.remove_event_listener` when cleaning up.
<!-- page: 190 -->
5. Threading Not Working - Are COOP/COEP headers on your HTML? - Does navigator.hardwareConcurrency return a number?
6. Canvas Blurry or Wrong Size - Sync canvas.width/height to CSS clientWidth/clientHeight before drawing.
7. WASI File/Env Errors - Pass --dir and --env flags to your WASI runtime (Wasmtime/Wasmer).
8. Bundle Too Large - Enable opt-level = "z", lto = true, codegen-units = 1. - Post-process with wasm-opt -Oz and serve Brotli-compressed.
9. CSP or COEP Blockages - Verify Cross-Origin-Opener-Policy & Embedder-Policy headers in dev tools. - Check window.crossOriginIsolated in console.
---
C: Further Resources & Community Projects
- Official Docs - Rust+Wasm Book: <https://rustwasm.github.io/book/> - wasm-bindgen Guide: <https://rustwasm.github.io/wasm-bindgen/>
- Tooling - wasm-pack (build + publishing): <https://github.com/rustwasm/wasm-pack> - wasm-bindgen-test (testing harness): <https://github.com/rustwasm/wasm-bindgen/tree/main/crates/test>
- Frameworks & Higher-Level - Yew (Rust-native web UI): <https://yew.rs/> - Seed (another Rust frontend framework): <https://seed-rs.org/> - stdweb (alternate JS interop): <https://stdweb.dev/>
- Edge & Serverless
<!-- page: 191 -->
- Cloudflare Workers + Rust: https://developers.cloudflare.com/workers/runtime-apis/wasm/
- Deno Deploy + Wasm: https://deno.com/deploy/docs/getting_started#web-assembly
- **Community** - Rust+Wasm Working Group: https://github.com/rustwasm - Rust Discord “wasm” channel: https://discord.gg/rust-lang - “This Week in Rust” newsletter: https://this-week-in-rust.org/
---
## D: Glossary of Key Terms
<table> <thead> <tr> <th>Term</th> <th>Definition</th> </tr> </thead> <tbody> <tr> <td><strong>WebAssembly (Wasm)</strong></td> <td>A portable, binary-format instruction set for sandboxed execution in browsers and beyond.</td> </tr> <tr> <td><strong>WASI</strong></td> <td>WebAssembly System Interface—APIs for file I/O, environment, networking in Wasm runtimes.</td> </tr> <tr> <td><strong>wasm-bindgen</strong></td> <td>A tool and library that exposes Rust types/functions to JavaScript and vice versa.</td> </tr> <tr> <td><strong>js-sys / web-sys</strong></td> <td>Low-level crates providing raw bindings to JS and Web APIs (DOM, fetch, WebSocket, etc.).</td> </tr> <tr> <td><strong>Zero-Copy</strong></td> <td>Passing typed array views directly into Wasm’s linear memory to avoid redundant memory copies.</td> </tr> <tr> <td><strong>wasm-pack</strong></td> <td>CLI for building, testing, and bundling Rust→Wasm projects for npm and web consumption.</td> </tr> <tr> <td><strong>Link-Time Optimization</strong></td> <td>LLVM optimization that inlines and removes dead code across crate boundaries for size/speed.</td> </tr> <tr> <td><strong>SharedArrayBuffer</strong></td> <td>JS buffer type that enables shared memory, used by threads in Wasm and JS.</td> </tr> </tbody></table>
<!-- page: 192 -->
<table> <thead> <tr> <th>Term</th> <th>Definition</th> </tr> </thead> <tbody> <tr> <td><code>requestAnimationFrame</code></td> <td>Browser API that synchronizes animation callbacks with screen refresh for smooth rendering.</td> </tr> <tr> <td>CSP</td> <td>Content Security Policy—a declarative mechanism to lock down permitted sources for resources.</td> </tr> <tr> <td>COOP/COEP</td> <td>Headers (Cross-Origin-Opener-Policy, Embedder-Policy) required to enable cross-origin isolation and advanced features like threads.</td> </tr> </tbody></table>
Keep this appendix close by as a quick cheat-sheet—whether you’re debugging build issues, hunting down bundle bloat, or discovering new community tools, these references will guide you back on track.