Wasm in Production — WebAssembly

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…

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

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

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

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

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;
  }
}

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),
  }));
});

The go-live checklist for Mrs. Sri's photo tool

⚠️ What breaks the photo tool after go-live

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.

What you will learn