Skip to content
jshacks.dev
Fundamentals

Calling WebAssembly From JavaScript With Working Examples

Load a WebAssembly module in Node.js or a browser, pass imports, share memory, handle LinkError and RuntimeError, reuse a compiled module and avoid stale views.

9 min read
Summarize in AI
Flat illustration of an editor window full of code, with the WebAssembly, JavaScript, npm and Node.js logos.

Once you have a .wasm file, the JavaScript side of using it is a small API with a few habits that decide whether your code is correct. You have to load the bytes in the right way for the environment, give the module the functions it imports, call its exports with numbers, move bigger data through its memory, and deal with the three error types the API defines. The overview in WebAssembly for JavaScript developers explained what a module is. This post is about the calls: how to load a module in Node.js and in a browser, how a module calls back into JavaScript through imports, how to read and write strings in its memory, how to reuse one compiled module for many instances, what each error means, and the mistakes that produce stale memory views and missing awaits. The examples run on Node.js 24, using small modules written out as bytes so you can run them without a compiler.

Loading the bytes

In Node.js, read the file and instantiate it. In a browser, stream it from the network, so compilation starts while the file downloads.

JavaScript
// Node.js
import { readFile } from "node:fs/promises";

const bytes = await readFile(new URL("./add.wasm", import.meta.url));
const { instance } = await WebAssembly.instantiate(bytes);

console.log(instance.exports.add(2, 3));
Text
5
JavaScript
// Browser
const { instance } = await WebAssembly.instantiateStreaming(fetch("/add.wasm"), imports);

instantiateStreaming needs the server to send the file with the content type application/wasm, or it rejects with a TypeError. If you cannot control the header, fetch the response, call arrayBuffer() and use WebAssembly.instantiate(bytes), at the cost of waiting for the whole download first. The Node.js example assumes a file add.wasm that holds the 41-byte module from the overview. The remaining examples use inline bytes.

Imports: calling JavaScript from the module

A module can declare imports, which are functions, memories, tables or globals that the host must supply when the instance is created. This module imports a function env.log that takes one integer, and exports run, which calls it with 42.

JavaScript
const importBytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x08, 0x02, 0x60, 0x01, 0x7f, 0x00, 0x60, 0x00, 0x00, // types: (i32) -> (), () -> ()
  0x02, 0x0b, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x03, 0x6c, 0x6f, 0x67, 0x00, 0x00, // import env.log
  0x03, 0x02, 0x01, 0x01, // one function of type () -> ()
  0x07, 0x07, 0x01, 0x03, 0x72, 0x75, 0x6e, 0x00, 0x01, // export "run"
  0x0a, 0x08, 0x01, 0x06, 0x00, 0x41, 0x2a, 0x10, 0x00, 0x0b, // i32.const 42, call 0
]);

const calls = [];
const imports = { env: { log: (value) => calls.push(value) } };

const { instance, module } = await WebAssembly.instantiate(importBytes, imports);

instance.exports.run();
instance.exports.run();

console.log(calls);
console.log(WebAssembly.Module.imports(module));
Text
[ 42, 42 ]
[ { module: 'env', name: 'log', kind: 'function' } ]

The import object is keyed by module name and then by field name, so imports.env.log matches the module's import of env and log. Each call to run() ran the WebAssembly code, which called back into the JavaScript function with the integer 42. The imports are the only way the module reaches the outside world: logging, timers, the DOM and the network are all JavaScript functions you pass in. This is how compiled programs print, and it is how a module is kept in a sandbox.

When an import is missing

The two cases fail differently, and the difference is worth knowing.

JavaScript
for (const badImports of [{}, { env: {} }, { env: { log: 5 } }]) {
  try {
    await WebAssembly.instantiate(importBytes, badImports);
  } catch (error) {
    console.log(error.name);
  }
}
Text
TypeError
LinkError
LinkError

If the import object does not have the module's namespace at all, here env, the engine throws a TypeError. If the namespace exists and the field is missing, or is not a function, the error is a WebAssembly.LinkError. Both mean the host did not provide what the module declared. The error message names the import by its index and its module and field, so it is easy to find the one that is missing.

Strings and memory

A module that exports its memory lets JavaScript read and write bytes directly. This module has one page of memory, exported as mem.

JavaScript
const memoryBytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x05, 0x03, 0x01, 0x00, 0x01, // memory: 1 page minimum
  0x07, 0x07, 0x01, 0x03, 0x6d, 0x65, 0x6d, 0x02, 0x00, // export "mem"
]);

const { instance: withMemory } = await WebAssembly.instantiate(memoryBytes);
const memory = withMemory.exports.mem;

const encoder = new TextEncoder();
const decoder = new TextDecoder();

function writeString(text, offset) {
  const encoded = encoder.encode(text);
  new Uint8Array(memory.buffer, offset, encoded.length).set(encoded);
  return encoded.length;
}

function readString(offset, length) {
  return decoder.decode(new Uint8Array(memory.buffer, offset, length));
}

const length = writeString("héllo 😀", 64);

console.log(length);
console.log(readString(64, length));
console.log(memory instanceof WebAssembly.Memory, memory.buffer.byteLength);
Text
11
héllo 😀
true 65536

The text is encoded as UTF-8, which is 11 bytes for these characters, written at offset 64, and read back from the same offset. A WebAssembly function that processes text would receive the pair (offset, length), as two integers, and read the bytes itself. Create the Uint8Array view from memory.buffer each time you need it, as these helpers do, instead of keeping one, for the reason in the next section. A module compiled from Rust or C also exports allocation functions, so JavaScript can ask the module for space and not guess at an offset.

Memory growth detaches views

Growing memory replaces the underlying buffer.

JavaScript
const stale = new Uint8Array(memory.buffer);
stale[0] = 7;

const before = memory.grow(1);

console.log(before, memory.buffer.byteLength);
console.log(stale.byteLength, stale[0]);

const fresh = new Uint8Array(memory.buffer);
console.log(fresh.byteLength, fresh[0]);
Text
1 131072
0 undefined
131072 7

grow(1) added one page and returned the previous size in pages. The old view stale now has length 0 and reads undefined, because its buffer was detached. The data is not lost: a new view of memory.buffer sees the byte at position 0 as before. A module can also grow its own memory during a call, for example when its allocator needs more space, so any call into the module can invalidate every view you hold. The safe pattern is to take a fresh view after every call, or only inside helpers that call memory.buffer each time.

One module, many instances

Compiling is the expensive step, and instances are cheap. Compile once and instantiate as often as you need.

JavaScript
const addBytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
  0x03, 0x02, 0x01, 0x00,
  0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00,
  0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
]);

const compiled = await WebAssembly.compile(addBytes);

const first = new WebAssembly.Instance(compiled);
const second = new WebAssembly.Instance(compiled);

console.log(compiled instanceof WebAssembly.Module);
console.log(first.exports.add === second.exports.add);
console.log(first.exports.add(1, 2), second.exports.add(10, 20));

const instantiated = await WebAssembly.instantiate(compiled);
console.log(instantiated instanceof WebAssembly.Instance);
Text
true
false
3 30
true

WebAssembly.compile(bytes) returns a Module. The synchronous constructor new WebAssembly.Instance(module, imports) builds an instance from it, and each instance has its own exported functions, memory and globals, so state in one does not affect the other. When you pass a Module to WebAssembly.instantiate(), the result is a bare Instance and not the { instance, module } pair that you get from bytes. Browsers also let you send a compiled module to a Web Worker with postMessage, so several workers can run the same code without compiling it again.

Calling costs and batching

Every call across the boundary converts arguments and results. A call that adds two numbers costs more than the addition, and calling it a million times from a loop is slower than writing the loop in JavaScript. The pattern that works is to make the module do a lot per call: copy the input into its memory once, call a function that processes the whole block, and read the result out once. Chatty interfaces, where JavaScript and the module go back and forth for each item, give up the benefit. We do not quote numbers, since they depend on the engine and the data, so measure with your real workload.

Handling errors from exports

JavaScript
const boomBytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
  0x03, 0x02, 0x01, 0x00,
  0x07, 0x08, 0x01, 0x04, 0x62, 0x6f, 0x6f, 0x6d, 0x00, 0x00,
  0x0a, 0x05, 0x01, 0x03, 0x00, 0x00, 0x0b,
]);

function safeCall(exports, name, ...args) {
  try {
    return { ok: true, value: exports[name](...args) };
  } catch (error) {
    if (error instanceof WebAssembly.RuntimeError) {
      return { ok: false, reason: `trap: ${error.message}` };
    }
    throw error;
  }
}

const { instance: trapping } = await WebAssembly.instantiate(boomBytes);

console.log(safeCall(trapping.exports, "boom"));
console.log(safeCall(first.exports, "add", 4, 5));
Text
{ ok: false, reason: 'trap: unreachable' }
{ ok: true, value: 9 }

A trap is a RuntimeError: the module hit an instruction it cannot continue from. Catch it at the boundary and convert it to the result your program uses. After a trap, treat the instance as damaged, since its memory may be half updated, and create a fresh one if you need to continue. Rethrow any other error, as the helper does, since a TypeError from a wrong call is a bug in your own code.

A mistake we hit: forgetting await

JavaScript
const wrong = WebAssembly.instantiate(addBytes);

try {
  const { instance } = wrong;
  instance.exports.add(1, 2);
} catch (error) {
  console.log(error.name);
}

console.log(wrong instanceof Promise);
const { instance: right } = await wrong;
console.log(right.exports.add(1, 2));
Text
TypeError
true
3

WebAssembly.instantiate returns a promise, and destructuring a promise gives undefined for instance, so the next line throws a TypeError that talks about reading exports of undefined. The error message does not mention WebAssembly or the missing await, which is why this takes longer to find than it should. We keep module loading in one function that is the only caller, and we await it at start-up. Linting rules for floating and misused promises catch it when TypeScript is used.

Choosing between the loading options

You wantUse
Load in a browser, with the best start-upWebAssembly.instantiateStreaming(fetch(url), imports)
Load in Node.jsreadFile then WebAssembly.instantiate(bytes, imports)
Many instances from one moduleWebAssembly.compile(bytes) then new WebAssembly.Instance(module, imports)
Check a file without running itWebAssembly.validate(bytes)
See what a module needsWebAssembly.Module.imports(module) and exports(module)
Move strings and arraysThe exported memory, with TextEncoder and typed arrays

Practical rules we follow

Load once, at start-up, and keep the instance. Await everything. Supply every import, and check the list with Module.imports() in tests. Take fresh memory views after any call. Pass offsets and lengths, not copies. Convert numbers explicitly, since the conversion wraps silently. Wrap export calls so that traps become results. And keep the boundary narrow and the calls large.

Where this guide stops

The API also covers tables, which hold references to functions for indirect calls, globals shared between modules, shared memory with threads and Atomics, and the JavaScript String Builtins and reference types that make strings and objects easier to pass. Toolchains such as wasm-bindgen and Emscripten generate the glue for strings and structures so you rarely write it by hand. The reference is in the MDN WebAssembly JavaScript API page and the WebAssembly JavaScript interface specification.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.