About

How Does WebAssembly (WASM) Work?

Run C++/Rust/Zig Code at Native Speed in the Browser

WebAssembly (WASM) is a bytecode format that runs code written in statically-typed languages like C++, Rust, and Zig at near-native speed in the browser.

Architecture Diagram

📝
Source Code
C / C++ Rust Zig Go (tinygo)
① Compile → Emscripten / wasm-pack / zig build
📦
npm Package
.wasm (bytecode) JS/TS wrapper (glue) TypeScript types
② Bundle → Vite / webpack
🌐
Browser
WASM Runtime
WebAssembly.compile() WebAssembly.instantiate() JS ↔ WASM calls
WASM Delivery Methods:
A Separate .wasm file → load via fetch() → cacheable
B base64 inline → embedded in JS bundle → no extra request (ghostty-web style)
Key Points
  • JavaScript cannot compile to WASM — WASM is a compile target for statically typed languages only
  • WASM cannot access the DOM directly — JS wrapper (glue code) acts as a bridge
  • Runs inside the browser sandbox — same security as native apps
  • Real examples: Figma(C++), FFmpeg.wasm(C), Ghostty Web(Zig), Photoshop(C++)

How It Works

1

Write source code (C++, Rust, Zig, or other statically-typed languages)

2

Generate .wasm bytecode with language-specific compilers (Emscripten, wasm-pack, zig build, etc.)

3

Write JS/TS wrapper (glue code) — expose WASM functions as JS API, bridge to Web APIs

4

Distribute as npm package (e.g., npm install ghostty-web). WASM bundled as base64 inline or separate .wasm file

5

Frontend build tools (Vite, webpack) bundle the package. Load WASM module via dynamic import()

6

Browser compiles bytecode via WebAssembly.compile() → instantiate() to create instance

7

Call WASM functions from JS ↔ Call JS callbacks from WASM — bidirectional communication

Pros

  • ✓ Near-native execution speed (10-100x faster computation vs JS)
  • ✓ Reuse existing C++/Rust codebases (even 30-year-old C++ code runs on the web)
  • ✓ Sandboxed execution (browser security model applies as-is)
  • ✓ Language-independent (any language that compiles works)
  • ✓ Reduced server load (heavy computation runs on the client)

Cons

  • ✗ No direct DOM/Web API access — must go through JS glue code
  • ✗ Complex build environment (Emscripten/wasm-pack setup, cross-compilation)
  • ✗ Initial load time (.wasm download + compilation overhead)
  • ✗ Difficult debugging (immature source maps, no console.log)
  • ✗ Manual memory management (no GC), serialization cost for JS↔WASM data exchange

Use Cases

Figma (C++ 2D rendering engine at native speed on the web) FFmpeg.wasm (video conversion in browser without server) Ghostty Web (Zig terminal parser for web terminal) Google Earth Web (C++ 3D map rendering) AutoCAD Web (reusing 30-year-old C++ CAD engine) Photoshop Web (C++ image processing engine)
← How to Buy a Domain: From Choosing a TLD to Renewals Making WASM a First-Class Language on the Web →