🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly: The MIME Type Problem

A Wasm file must arrive as application/wasm. The MIME type is the label the server puts on a file.

Stream a module in

This loads and compiles in one step.

const { instance } = await WebAssembly.instantiateStreaming(
  fetch("add.wasm"),
  {}
);
console.log(instance.exports.add(2, 3));

Fix the type on Apache

One line labels .wasm files correctly.

AddType application/wasm .wasm

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  console.log("2 + 3 =", instance.exports.add(2, 3));
})();

Key points

  • A MIME type is the label a server puts on a file.
  • Serve .wasm as exactly application/wasm.
  • Use instantiateStreaming to compile a module while it downloads.
  • A wrong MIME type makes streaming compile fail with a TypeError.
  • Inline bytes skip the server, so this demo loads anyway.
  • Fix the server config, not the module, for MIME errors.
  • The right label lets the browser trust the bytes.

In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 2 and 3 and logs the sum. Inline bytes skip the server, so no MIME label is needed here.

Note

the exact browser wording for this error is not quoted here.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What MIME type must a .wasm file use?