Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 38 ยท Getting Started

The WebAssembly JavaScript API

A tour of the WebAssembly JavaScript API. Use validate, compile, instantiate, Module, Instance and streaming loading in browsers and Node.js, with runnable examples.

The WebAssembly JavaScript API is a small global namespace. It is the only door between your JavaScript and a module, so it is worth knowing completely. The whole API fits on one screen: a few functions to turn bytes into modules and instances, a handful of classes for the things a module can own, and three error types.

This lesson covers loading. Memory, tables and globals get their own lessons in the next chapter.

The namespace at a glance

Member Kind Purpose
WebAssembly.validate(bytes) function Returns true or false, never throws for bad modules
WebAssembly.compile(bytes) function Promise of a Module
WebAssembly.instantiate(...) function Promise of an instance (and the module, if you gave bytes)
WebAssembly.compileStreaming, instantiateStreaming function Same, straight from a fetch response (browsers, Node 18+, Deno, Bun)
WebAssembly.Module class Compiled, stateless code
WebAssembly.Instance class A running module
WebAssembly.Memory, Table, Global class Things a module can own, import or export
WebAssembly.Tag, Exception class Exception handling support
CompileError, LinkError, RuntimeError class The three error types

Two styles: asynchronous and synchronous

The promise functions are the normal choice because they let the engine compile in the background:

JavaScript
const module = await WebAssembly.compile(bytes);
const instance = await WebAssembly.instantiate(module, imports);
// or in one step, which returns { module, instance }:
const result = await WebAssembly.instantiate(bytes, imports);

The constructors do the same work synchronously:

JavaScript
const module = new WebAssembly.Module(bytes);
const instance = new WebAssembly.Instance(module, imports);

Use the constructors in Node.js scripts, tests and small tools. Avoid them for big modules on a browser's main thread: some browsers refuse to compile modules over a few kilobytes synchronously there, and a long compile would freeze the page anyway.

The return type depends on what you pass instantiate. This trips up many newcomers, so run it and watch.

Node.js What does instantiate return?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details to remember: the exports object is frozen (you cannot add or replace properties), and its prototype is null, so it has no toString or hasOwnProperty.

Loading a .wasm file

In real projects the bytes come from a file.

In a browser, use streaming instantiation. The engine compiles while the file downloads:

JavaScript
const { instance } = await WebAssembly.instantiateStreaming(
  fetch('/assets/calc.wasm'),
  { env: { log: console.log } },
);
instance.exports.run();

The response must have Content-Type: application/wasm; otherwise the call rejects with a TypeError. If you cannot fix the server, fall back to fetch(url).then(r => r.arrayBuffer()).then(buf => WebAssembly.instantiate(buf, imports)).

In Node.js, read the file with fs. The same code works in the run below, which first writes the module to a temporary file so that the example is self-contained.

Node.js Load a .wasm file with fs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Inspecting a module without running it

The Module class has three static helpers that read what a module declares. They are how tools list the imports a module needs before you provide them.

Node.js Module.exports, imports and customSections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the imported function takes function index 0, so the module's own function is index 1. Imports are always numbered first.

Errors you will see

Error When
WebAssembly.CompileError Bytes are not a valid module
WebAssembly.LinkError The imports you gave do not match what the module declared
WebAssembly.RuntimeError A trap while running (division by zero, out-of-bounds access, unreachable)
TypeError Wrong argument types to the API itself, such as a missing import object

Traps and Errors covers them in depth. For now, if instantiate complains, call WebAssembly.Module.imports(module) and compare it with the object you passed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does WebAssembly.instantiate(bytes) resolve to?

    With raw bytes you get { module, instance }. With a Module you get just the Instance.
  2. 2. Why does instantiateStreaming reject some servers' responses?

    Streaming compilation requires the application/wasm MIME type. Otherwise use arrayBuffer() and the normal instantiate.
  3. 3. Which call tells you what a module needs from the host without running it?

    Module.imports lists each import's module name, field name and kind; Module.exports does the same for exports.
  4. 4. What is true about instance.exports?

    The exports object is created by the engine, frozen, and has no prototype.

Summary

  • validate answers true or false; compile and instantiate return promises; Module and Instance constructors are synchronous.
  • Bytes to instantiate give { module, instance }; a Module gives an Instance.
  • Browsers should use instantiateStreaming with the application/wasm MIME type; Node.js reads the file with fs.
  • Module.imports, Module.exports and Module.customSections inspect a module without running it.
  • Errors are CompileError, LinkError and RuntimeError.

Next: Value Types and Numbers