On your laptop, photolab.wasm runs smoothly. In production, the same file has to reach thousands of guests' phones properly: quick to download, accepted for compiling by the browser, safe, with a fallback when something fails, and with you knowing when something breaks.
It's like Mrs. Sri sending parcels of fruit preserves to customers all over the country. The contents label has to be right, or the courier refuses the parcel. The parcel is packed tight so postage is cheap. Each version of the packaging carries a code, so agents can keep old stock without mixing it up. Before sending, Mrs. Sri checks whether the address can take a chilled parcel; if not, she sends the dry version. The seal protects what is inside, but what goes into the parcel is still Mrs. Sri's responsibility. And the tracking number is written down. The contents label is the Content-Type header, tight packing is compression, the version code is a hashed file name, checking the address is feature detection, the seal is the Wasm sandbox, what goes into the parcel is your imports, and the tracking number is monitoring.
Who already uses Wasm, and when not to
- Figma: its engine is C++, moved from asm.js to Wasm in 2017, and load time got more than 3 times faster.
- Google Earth: from Native Client (Chrome only) to Wasm, then running in Firefox, Edge and Opera since February 2020.
- AutoCAD Web: a 35-year-old C++ codebase compiled with Emscripten, released in March 2018.
- Photoshop on the web: Adobe uses Emscripten and Wasm (2021), generally available since September 2023. Plus many browser games from Unity and Godot.
The pattern is the same: a big existing C++ codebase, and heavy CPU work. On the other hand, don't use Wasm for simple UI logic, DOM manipulation, CRUD forms, or apps that need developer speed more than computing speed. There JavaScript is already fast enough, and Wasm only adds a toolchain, harder debugging and crossing costs.
Content-Type: application/wasm
instantiateStreaming compiles while downloading, but only if the server says the file is application/wasm. Otherwise it refuses. These are the real messages:
| Browser | Content-Type: application/octet-stream |
|---|---|
| Chromium 147 | TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'. |
| WebKit 26.4 | TypeError: Unexpected response MIME type. Expected 'application/wasm' |
| Firefox 146 | TypeError: WebAssembly: Response has unsupported MIME type 'application/octet-stream' expected 'application/wasm' |
With application/octet-stream, instantiateStreaming fails in all three browsers. A case you will meet: an SPA router answering a wrong .wasm path with index.html. Firefox writes unsupported MIME type 'text/html', and if the code uses arrayBuffer() then instantiate, the message is CompileError: WebAssembly.compile(): expected magic word 00 61 73 6d, found 3c 21 64 6f @+0: the bytes 3c 21 64 6f are <!do from <!doctype html>. Check with curl -I that the response is 200 with content-type: application/wasm.
Compression: gzip and brotli
Measured with gzip level 9 and brotli quality 11:
| File | Size | gzip | brotli |
|---|---|---|---|
photolab.wasm |
4,177 bytes | 2,058 | 1,851 |
photolab-simd.wasm |
6,040 bytes | 2,924 | 2,529 |
mist_homestay_bg.wasm (wasm-pack) |
14,896 bytes | 6,764 | 5,797 |
gray-img.wasm (WASI) |
63,172 bytes | 25,721 | 21,674 |
gray-img from Go |
2,677,059 bytes | 770,794 | 578,596 |
- A
.wasmshrinks by 50 to 78%, because its instruction patterns repeat. Brotli is 10 to 25% smaller than gzip. - Store the compressed version at build time (
photolab.wasm.br), then send it withContent-Encoding: br,Content-Type: application/wasmandVary: Accept-Encoding. The browser undoes the compression before compiling, soinstantiateStreamingstill works. - Compression only shrinks the download. The browser still compiles 4,177 bytes. To shrink the module itself: release, wasm-opt, strip (the Profiling lesson).
Caching: hashed file names
import photolabUrl from './photolab.wasm?url'; // Vite gives the URL of the hashed file
WebAssembly.instantiateStreaming(fetch(photolabUrl)).then(({ instance }) => {
// instance.exports.grayscale, blur_h, ...
});
$ vite build
dist/index.html 0.25 kB │ gzip: 0.20 kB
dist/assets/photolab-Cp8ZQMRe.wasm 4.17 kB │ gzip: 2.05 kB
dist/assets/index-CW3UgSLM.js 0.83 kB │ gzip: 0.48 kB
- Vite 8.0.8 puts a hash of the file's contents in its name:
photolab-Cp8ZQMRe.wasm. When the contents change, the name changes. - That makes hashed files safe to cache forever:
Cache-Control: public, max-age=31536000, immutable.index.html, which points to the new name, getsCache-Control: no-cache. - Vite inlines assets under 4 KiB (
build.assetsInlineLimit, 4096 by default).photolab-basic.wasm(3,302 bytes, the version without SIMD from the next section) ends up inside the JS asdata:application/wasm;base64,...: a third bigger, with no cache of its own. Withbuild: { assetsInlineLimit: 0 }invite.config, it becomes a file of its own:photolab-basic-DEnIdDgB.wasm.
Feature checks and fallbacks
// (module (func (result v128) i32.const 0 i8x16.splat i8x16.popcnt)), 31 bytes from wat2wasm
const SIMD_TEST = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11]);
function pickVersion() {
if (typeof WebAssembly !== 'object') return 'js'; // no Wasm: grayscaleJs
if (WebAssembly.validate(SIMD_TEST)) return 'photolab.wasm'; // holds grayscale_simd
return 'photolab-basic.wasm'; // not a single SIMD instruction
}
const canThread = typeof crossOriginIsolated !== 'undefined' && crossOriginIsolated; // the Threading lesson
WebAssembly.validate(bytes)checks without compiling. An engine without SIMD rejects the whole module, not just the function:photolab.wasmholdsgrayscale_simd, andwasm-tools validate --features=-simd photolab.wasmanswersfunc 6 failed to validatebecauseSIMD support is not enabled. The basic version is built without that function: 3,302 bytes.- Threads need
crossOriginIsolated(the COOP and COEP headers). Without it, use the single-threaded version. - Keep the JavaScript version as the last fallback: slower, but guests can still process their photos.
Security: the sandbox, imports and CSP
A Wasm module can only touch its own linear memory and the functions you import. No DOM, network or file access unless through those imports. So your imports are the door: don't import a function that runs text as code or fetches any URL the module hands it. C or C++ code inside Wasm can still overwrite its own data (buffer overflows still happen inside linear memory); bounds are only checked at the edge of the memory. Check input sizes before calling Wasm.
A Content-Security-Policy of script-src 'self' blocks Wasm compiles in all three browsers:
| Browser | Message |
|---|---|
| Chromium 147 | CompileError: WebAssembly.instantiate(): Compiling or instantiating WebAssembly module violates the following Content Security policy directive because 'unsafe-eval' is not an allowed source of script ... |
| WebKit 26.4 | CompileError: Refused to create a WebAssembly object because 'unsafe-eval' or 'wasm-unsafe-eval' is not an allowed source of script ... |
| Firefox 146 | CompileError: call to WebAssembly.instantiate() blocked by CSP |
Add 'wasm-unsafe-eval': script-src 'self' 'wasm-unsafe-eval'. It allows Wasm without allowing eval. Supported since Chrome 97, Firefox 102 and Safari 16. 'unsafe-eval' opens Wasm too, but opens eval at the same time.
Traps and error handling
A trap is an error that stops a Wasm function midway. Its message differs per browser:
| Trap | Chromium 147 | WebKit 26.4 | Firefox 146 |
|---|---|---|---|
| Reading outside memory | RuntimeError: memory access out of bounds |
RuntimeError: Out of bounds memory access |
RuntimeError: index out of bounds |
unreachable |
RuntimeError: unreachable |
RuntimeError: Unreachable code should not be executed |
RuntimeError: unreachable executed |
A Rust panic with panic = "abort" ends as unreachable. For example resize_area with a source width of 0: Rust divides by 0, panics, and JS only sees RuntimeError: unreachable, without the panic message.
function grayscaleSafe(photo) {
try {
return grayscaleWasm(photo);
} catch (e) {
if (e instanceof WebAssembly.RuntimeError) {
report('trap', e);
photolab = null; // don't reuse that instance; make a new one on the next call
return grayscaleJs(photo); // fallback
}
throw e;
}
}
- After a trap, that instance's memory may be half-done (an allocator midway through its work, say). A new instance is safer.
CompileError(a broken file, an unsupported feature) andLinkError(mismatched imports) appear while loading, not while calling.
Monitoring
const start = performance.now();
WebAssembly.instantiateStreaming(fetch(photolabUrl)).then(({ instance }) => {
const download = performance.getEntriesByName(new URL(photolabUrl, location.href).href)[0];
navigator.sendBeacon('/api/metrics', JSON.stringify({
module: photolabUrl, // the hashed name = the version
loadMs: Math.round(performance.now() - start),
transferSize: download?.transferSize, // 0 when served from cache
encodedBodySize: download?.encodedBodySize, // compressed size
decodedBodySize: download?.decodedBodySize, // 4177
simd: WebAssembly.validate(SIMD_TEST),
}));
});
- Record the load time, the download size, the module version, the detected features, and every
CompileError,LinkErrororRuntimeErrorwith its message. sendBeaconstill gets sent when the guest closes the page.
The go-live checklist for Mrs. Sri's photo tool
- Release build, wasm-opt, strip; the size written down (4,177 bytes, 1,851 after brotli).
Content-Type: application/wasmchecked withcurl -I, and a wrong.wasmpath answers 404, notindex.html.- Brotli and gzip on, with
Vary: Accept-Encoding. - Hashed file names with
immutable;index.htmlwithno-cache. - The CSP includes
'wasm-unsafe-eval'. WebAssembly.validatepicks the SIMD or plain version; JS is the last fallback.- Photo sizes checked before going into Wasm; traps caught, the instance replaced, and reported.
- Monitoring sends load time, version and errors; tested in Chrome, Safari, Firefox and on low-end phones.
⚠️ What breaks the photo tool after go-live
- An SPA router answering
.wasmwithindex.html. The result isunsupported MIME type 'text/html'orexpected magic word 00 61 73 6d, found 3c 21 64 6f. - A CSP without
'wasm-unsafe-eval'. Every Wasm compile is blocked, even though the scripts run. - Shipping a SIMD build without checking. An engine without SIMD rejects the whole module.
immutableon a file name without a hash. Guests are stuck on the old version until their cache expires a year later.- Reusing an instance after a trap. Its memory may be half-done. Make a new instance.
TL;DR: Wasm already runs Figma, Google Earth, AutoCAD Web, Photoshop on the web and many browser games; don't use it for simple UI, the DOM, or apps that need developer comfort more. To ship it: Content-Type: application/wasm (without it instantiateStreaming fails in Chromium, WebKit and Firefox), brotli or gzip compression (4,177 down to 1,851 or 2,058 bytes), hashed file names (photolab-Cp8ZQMRe.wasm) with Cache-Control: immutable, and watch out for Vite inlining assets under 4 KiB. Pick the version with WebAssembly.validate (SIMD) and crossOriginIsolated (threads), and keep JS as the fallback. Wasm is sandboxed, but your imports are the door; the CSP needs 'wasm-unsafe-eval' (Chrome 97, Firefox 102, Safari 16). Catch RuntimeError (out of bounds, unreachable from a Rust panic), replace the instance, use the fallback, and report it. Monitoring records load time, size, version, features and errors through sendBeacon.
⚡ Who already uses Wasm
Meaning: Figma, Google Earth, AutoCAD Web, Photoshop on the web, and many browser games from Unity and Godot run on Wasm. The pattern is the same: a big existing C++ codebase, and heavy CPU work. For simple UI logic, DOM manipulation or CRUD forms, JavaScript is enough.
⚡ Content-Type, compression, cache
Guess first: the server sends the .wasm as application/octet-stream. Does instantiateStreaming still work?
It fails in all three browsers: it only compiles if the server says application/wasm. An SPA router answering with index.html shows up as the bytes 3c 21 64 6f, that is <!do.
Meaning: Also send brotli or gzip with Vary: Accept-Encoding (4,177 bytes become 1,851), and a hashed file name like photolab-Cp8ZQMRe.wasm with Cache-Control: immutable.
⚡ Feature checks and fallbacks
Write:
function pickVersion() {
if (typeof WebAssembly !== 'object') return 'js'; // no Wasm: grayscaleJs
if (WebAssembly.validate(SIMD_TEST)) return 'photolab.wasm'; // holds grayscale_simd
return 'photolab-basic.wasm'; // not a single SIMD instruction
}
Meaning: An engine without SIMD rejects the whole module, so check first with WebAssembly.validate. The JavaScript version stays as the last fallback.
⚡ CSP and traps
Meaning: The CSP needs 'wasm-unsafe-eval', or every Wasm compile is blocked. A Rust panic with panic = "abort" becomes RuntimeError: unreachable: catch it, make a new instance, use the JS fallback, and report it.