Web UI (WebAssembly) Applications
Rust compiles to WebAssembly (WASM) so you can build browser user interfaces with type safety and shared domain crates. Configure the framework, build toolchain, binary size limits, Content Security Policy (CSP), and browser tests before deployment.
Framework selection
Select a framework that matches your reactivity model, server-side rendering (SSR) needs, and target platforms.
| Framework | Model | Build tool | Best fit |
|---|---|---|---|
| Leptos | Fine-grained reactive signals without a Virtual DOM | cargo-leptos or trunk |
High-performance web applications, SSR with hydration, and full-stack Rust |
| Dioxus | Virtual DOM with rsx! components |
dx (Dioxus CLI) |
Multi-platform products that share UI code across web, desktop, and mobile |
| Yew | Component and hook model | trunk |
Mature single-page applications (SPAs) with stable APIs |
Put shared request types, response types, and validation rules in a separate
workspace crate. Compile that crate for both the browser (wasm32-unknown-unknown)
and the web API server so client and server models stay consistent.
Toolchain and build pipeline
Add the WebAssembly compilation target to your toolchain and to
rust-toolchain.toml.
[toolchain]channel = "1.100.0"components = ["rustfmt", "clippy"]targets = ["wasm32-unknown-unknown"]Use these standard tools to compile and package the frontend:
wasm-bindgen: Generates the JavaScript glue code and bindings to Web APIs (web-sys,js-sys). Pin thewasm-bindgen-cliversion in CI to match thewasm-bindgencrate version inCargo.lock.Trunk: Builds, bundles, hashes, and serves client-side WASM applications from anindex.htmlentry point.wasm-pack: Compiles Rust crates into reusable npm packages for JavaScript or TypeScript projects.cargo-leptos: Compiles both the server binary and the client WASM bundle for full-stack Leptos applications.
Binary size and performance optimization
Large .wasm bundles slow page load times. Configure a dedicated release
profile in Cargo.toml for WASM artifacts.
[profile.wasm-release]inherits = "release"opt-level = "z"lto = truecodegen-units = 1panic = "abort"strip = trueSelect the custom profile explicitly in your build tool so Cargo applies these
settings instead of the default release profile:
cargo-leptos: Setlib-profile-release = "wasm-release"in[package.metadata.leptos](single-package project) or in[[workspace.metadata.leptos]](multi-package workspace with separate frontend and server crates).- Cargo: Pass
--profile wasm-release. Trunk: Passtrunk build --cargo-profile wasm-release, or setdata-cargo-profile="wasm-release"on therust<link>inindex.html.
Apply these additional size controls:
- Post-process release
.wasmfiles withwasm-optfrom Binaryen (-Ozfor smallest size or-O3for speed).Trunkandwasm-packcan invokewasm-optautomatically. - Keep
console_error_panic_hookfor readable browser panic messages during development. Avoid large formatting dependencies where size is critical. - Serve
.wasmassets with theContent-Type: application/wasmheader so browsers can useWebAssembly.instantiateStreaming. - Compress static
.wasm,.js, and.cssfiles with Brotli or gzip on the web server or content delivery network (CDN).
Security controls
Browser code operates in an untrusted environment. Apply browser security headers and keep all secrets on the server.
Content Security Policy (CSP)
Modern browsers support 'wasm-unsafe-eval' in the script-src directive. This
directive permits WebAssembly compilation without permitting JavaScript eval().
Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; object-src 'none'; base-uri 'self'; frame-ancestors 'none';- Do not use
'unsafe-eval'inscript-srcwhen'wasm-unsafe-eval'satisfies your browser support policy. - Do not embed API secrets, private keys, or privileged tokens in a WASM binary.
Any user can inspect or disassemble downloaded
.wasmbytes. - Treat raw HTML injection APIs (such as
inner_html) as high-risk sinks. Sanitize untrusted HTML on the server before rendering. - Use Subresource Integrity (SRI) hashes when you load third-party scripts or stylesheets.
Testing WebAssembly code
Combine native Rust tests with headless browser tests.
- Keep pure state logic, reducers, and validators independent of
web-sys. Check them on the host target withcargo nextest run --locked. Refer to Testing strategy. - Write browser-specific tests with
wasm-bindgen-testfor DOM manipulation, storage APIs, andfetchwrappers. - Start browser tests in CI with a headless browser driver:
wasm-pack test --headless --chrome- Add end-to-end tests with Playwright against the production bundle served with the real CSP headers. Make sure that the page loads without console errors or CSP violations.
Deployment and caching
- Include content hashes in
.wasm,.js, and.cssfilenames.Trunkenables file hashing by default.cargo-leptosdefaultshash-filestofalse; sethash-files = truein[package.metadata.leptos](or[[workspace.metadata.leptos]]for multi-package workspaces), enableLEPTOS_HASH_FILES=true/hash_filesat runtime, and deploy the generatedhash.txtalongside the server executable (or configure its runtime path) before you apply an immutable cache policy. - Set
Cache-Control: public, max-age=31536000, immutableon hashed asset files. - Set
Cache-Control: no-cacheonindex.htmlso browsers get new asset hashes after a release. - Track
.wasmbundle size in CI so unexpected dependency growth fails review.