The JavaScript API
Browsers, Node.js, Deno and Bun all expose WebAssembly through the global WebAssembly object. Its two central
classes mirror the two stages you met in How WebAssembly Runs:
| Object | What it is | Created by |
|---|---|---|
WebAssembly.Module |
compiled, stateless code; can be cached, sent to workers, instantiated many times | compile, compileStreaming, new Module(bytes) |
WebAssembly.Instance |
a module linked with its imports, with its own memory, tables and globals | instantiate, instantiateStreaming, new Instance(module, imports) |
The functions
| Function | Returns |
|---|---|
WebAssembly.validate(bytes) |
true/false |
WebAssembly.compile(bytes) |
Promise<Module> |
WebAssembly.instantiate(bytes, imports) |
Promise<{ module, instance }> |
WebAssembly.instantiate(module, imports) |
Promise<Instance> (note: just the instance) |
WebAssembly.compileStreaming(response) |
Promise<Module>, compiles while downloading |
WebAssembly.instantiateStreaming(response, imports) |
Promise<{ module, instance }> |
The synchronous constructors new WebAssembly.Module(bytes) and new WebAssembly.Instance(module, imports) also
exist, but browsers limit them to small modules on the main thread because they block. Prefer the async forms.
Loading a module in a web page
In a real page you fetch the .wasm file and use the streaming API. The server must send it with the MIME type
application/wasm:
const { instance } = await WebAssembly.instantiateStreaming(
fetch('/math.wasm'),
{ env: { log: (n) => console.log(n) } },
);
console.log(instance.exports.add(2, 3));In Node.js you read the file instead: const bytes = await fs.promises.readFile('math.wasm'). In this course's
playground we write the bytes inline, which works everywhere.
Bytes → module → instance
The module below exports add(a, b) and square(x) (both i32):
const bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
0x01, 0x0c, 0x02, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x60, 0x01, 0x7f, 0x01, 0x7f, // 2 types
0x03, 0x03, 0x02, 0x00, 0x01, // 2 functions
0x07, 0x10, 0x02, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, // export "add"
0x06, 0x73, 0x71, 0x75, 0x61, 0x72, 0x65, 0x00, 0x01, // export "square"
0x0a, 0x11, 0x02,
0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, // a + b
0x07, 0x00, 0x20, 0x00, 0x20, 0x00, 0x6c, 0x0b, // x * x
]);
console.log('valid:', WebAssembly.validate(bytes));
const module = await WebAssembly.compile(bytes);
console.log(module instanceof WebAssembly.Module);
console.log(WebAssembly.Module.exports(module));
// the same module, instantiated twice
const a = await WebAssembly.instantiate(module, {});
const b = await WebAssembly.instantiate(module, {});
console.log(a instanceof WebAssembly.Instance, a === b);
console.log(a.exports.add(2, 3), b.exports.square(12));valid: true
true
[
{ name: 'add', kind: 'function' },
{ name: 'square', kind: 'function' }
]
true false
5 144
Exported functions are JavaScript functions
Exports are real JS functions (with a length, the parameter count, and a name, which the JS API defines as the function's index as a string), so you can pass them around, use them as callbacks,
or bind them. Arguments and results are converted according to the Wasm types:
const bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
0x01, 0x0c, 0x02, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x60, 0x01, 0x7f, 0x01, 0x7f,
0x03, 0x03, 0x02, 0x00, 0x01,
0x07, 0x10, 0x02, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x06, 0x73, 0x71, 0x75, 0x61, 0x72, 0x65, 0x00, 0x01,
0x0a, 0x11, 0x02, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, 0x07, 0x00, 0x20, 0x00, 0x20, 0x00, 0x6c, 0x0b,
]);
const { instance } = await WebAssembly.instantiate(bytes);
const { add, square } = instance.exports;
console.log(typeof add, add.length, add.name);
console.log([1, 2, 3, 4].map((n) => square(n)));
console.log(add(2.9, 3.9)); // ToInt32 truncates: 2 + 3
console.log(add('40', true)); // '40' -> 40, true -> 1
console.log(add(2147483647, 1)); // i32 wraps
console.log(add()); // missing arguments become 0 (undefined -> 0)
console.log(Object.isFrozen(instance.exports));function 2 0
[ 1, 4, 9, 16 ]
5
41
-2147483648
0
true
The conversions are forgiving: wrong argument types are converted (ToInt32, ToNumber), not rejected. If you want
strict checks, write them in JavaScript before calling into Wasm.
Calling JavaScript from Wasm
Imported JS functions receive converted arguments and their return values are converted to the declared Wasm result
type. Here the module imports env.clamp(i32) -> i32 and exports run(x) which returns clamp(x) * 2:
const bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f, // type 0: (i32) -> i32
0x02, 0x0d, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x05, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x00, 0x00, // import env.clamp
0x03, 0x02, 0x01, 0x00, // run: type 0
0x07, 0x07, 0x01, 0x03, 0x72, 0x75, 0x6e, 0x00, 0x01, // export "run" = func 1
0x0a, 0x0b, 0x01, 0x09, 0x00, 0x20, 0x00, 0x10, 0x00, 0x41, 0x02, 0x6c, 0x0b, // clamp(x) * 2
]);
const calls = [];
const env = {
clamp(x) {
calls.push(x);
return Math.min(Math.max(x, 0), 100);
},
};
const { instance } = await WebAssembly.instantiate(bytes, { env });
console.log(instance.exports.run(42), instance.exports.run(-5), instance.exports.run(1000));
console.log(calls);84 0 200
[ 42, -5, 1000 ]
Sharing a Module with Workers
A Module can be sent to a Web Worker with postMessage (it's structured-cloneable), so you compile once and
instantiate in each worker. With WebAssembly.Memory({ shared: true, … }) and the threads feature, workers can even
share one memory, which is how multithreaded C++ and Rust run on the web (this needs the page to be
cross-origin isolated).
// main thread
const module = await WebAssembly.compileStreaming(fetch('/worker-code.wasm'));
worker.postMessage(module);
// worker.js
onmessage = async ({ data: module }) => {
const instance = await WebAssembly.instantiate(module, imports);
postMessage(instance.exports.compute());
};Errors you'll meet
| Error | When |
|---|---|
WebAssembly.CompileError |
the bytes are invalid (decoding or validation) |
WebAssembly.LinkError |
an import is missing or has the wrong type/kind |
WebAssembly.RuntimeError |
a trap while running |
TypeError |
e.g. passing a Number for an i64, a missing import namespace, v128 at the boundary |
Test yourself
What does WebAssembly.instantiate(bytes, imports) resolve to?
- An Instance
- A Module
- An object
{ module, instance } - The exports object
Why prefer instantiateStreaming(fetch(url)) in browsers?
- It is the only API that works
- It compiles while the file downloads, so startup is faster
- It skips validation
- It caches the instance
What happens when JS calls an exported (param i32) function with 2.9?
- TypeError
- The value is truncated to 2
- It is rounded to 3
- The call traps