JavaScript-Wasm Bridge — WebAssembly

JS calls Wasm exports (instance.exports.stayPrice), Wasm calls JS imports ({ display: { showTotal } }, checked at instantiate time: a LinkError when missing)…

stayPrice(2, 3500) is easy: two numbers go in, one number comes out. But what if Wasm needs the guest's name, or wants to show the total on the page? JavaScript and Wasm talk across one bridge: exports (Wasm functions that JS calls), imports (JS functions that Wasm calls), and linear memory, which both sides can read and write.

The reception desk of Mist Homestay sits behind glass with a narrow slot. Only slips of paper with numbers fit through the slot: the number of nights, the price per night. A guest's suitcase does not fit, so it goes into a shared storeroom, and what passes through the slot is just the shelf number and how many items there are. A guest may leave a room key at the desk, but the receptionist may not open what it locks. The slot is the border between JS and Wasm, the number slips are i32/i64/f32/f64, the storeroom is linear memory, the shelf number and count are a pointer and a length, and the key left at the desk is an externref.

Exports and imports

Every example in this lesson uses one module, bridge.wat (270 bytes after wat2wasm 1.0.42). These are the parts used here:

(module
  ;; import: a JS function Wasm may call
  (import "display" "showTotal" (func $showTotal (param i32)))
  (memory (export "memory") 1)

  (func $stayPrice (export "stayPrice") (param $nights i32) (param $pricePerNight i32) (result i32)
    local.get $nights
    local.get $pricePerNight
    i32.mul)

  ;; Wasm computes, then calls back into JS
  (func (export "order") (param $nights i32) (param $pricePerNight i32)
    local.get $nights
    local.get $pricePerNight
    call $stayPrice
    call $showTotal))
const imports = {
  display: { showTotal: (total) => console.log('Total: $' + total / 100) },
};
WebAssembly.instantiate(bytes, imports).then(({ instance }) => {
  const { stayPrice, order } = instance.exports;
  console.log(stayPrice(2, 3500)); // 7000 (cents)
  order(2, 3500);                  // Total: $70
});

Values that can cross

What really passes through the slot is only numbers of the four Wasm types, plus references:

Wasm type In JS Example in bridge.wasm
i32 Number, cut down to a 32-bit integer stayPrice(700000, 3500) gives -1844967296; stayPrice(2.9, "3500") gives 7000
i64 BigInt stayPrice64(700000n, 3500n) gives 2450000000n
f32, f64 Number fractions, a price per metre for instance
externref any JS value, intact but unreadable to Wasm storeGuest(guest) then getGuest() === guest is true

Wasm cannot wait for a Promise either. Say the import getPrice is declared (result i32) and returns a Promise from fetch. The Promise goes into an i32 through ToInt32 and becomes 0. So the function total(2), which multiplies 2 nights by the result of getPrice(), returns 0 with no error. Other options for waiting for data:

Way When to pick it
await in JS first, then send the number to Wasm The default, and the simplest: the data is there before Wasm is called.
JSPI: wrap the import in new WebAssembly.Suspending(fn) and the export in WebAssembly.promising(fn) Existing C or Rust code that has to wait halfway through. Available in Chrome 137, Firefox 153, Safari 27 and Node 26. In Chromium 156, total(2) through JSPI gives 7000.
Emscripten -sASYNCIFY Browsers or runtimes without JSPI. The Emscripten documentation says the size and running time grow, usually by about 50%.

Strings: write the bytes, send a pointer and a length

bridge.wat has toUpper(ptr, len): it turns the letters a to z into capitals, byte by byte, in memory. JS writes and reads the text. Before you read the code, guess: the guest name "Renée" has 5 letters. To send it to Wasm, how many bytes does JS have to write into memory: 5, 6 or 10?

const { memory, toUpper } = instance.exports;
const name = 'Renée';
const nameBytes = new TextEncoder().encode(name); // 6 bytes: 52 65 6e c3 a9 65 (hex)
const ptr = 0;                                    // an address in Wasm memory
new Uint8Array(memory.buffer).set(nameBytes, ptr);
toUpper(ptr, nameBytes.length);                   // what crosses: two i32s, 0 and 6
const result = new Uint8Array(memory.buffer, ptr, nameBytes.length);
console.log(new TextDecoder().decode(result));    // RENéE
R e n é (byte 1) é (byte 2) e
Before 52 65 6e c3 a9 65
After toUpper(0, 6) 52 45 4e c3 a9 45

The cost of crossing

Every crossing converts the arguments to Wasm types and the result back. One crossing is a few nanoseconds, but the numbers add up (measured in an earlier lesson, Chromium 147):

How it is called Time
grayscale(ptr, 3840000), once for a 1200 × 800 photo 0.7 ms + 0.6 ms copying in and out
Plain JavaScript 1.8 ms
grayPixel(r, g, b), 960,000 times 8 ms
a Go function through js.FuncOf (Node 22) about 7.8 µs per call

The rule: gather the data, write it to memory once, call once, and let the loop run inside Wasm. The same goes the other way: a JS import called once per pixel is just as expensive.

📌 JS String Builtins

Languages that use linear memory (C, C++, Rust, Go) keep using a pointer and a length. But there is now another road: JS String Builtins (Chrome 130, Firefox 134, Safari 26.2). A module can hold a JS string as an externref and call string operations (length, slice, concatenate) through the special wasm:js-string imports, with no bytes copied. Compilers that target Wasm GC use this, not code you write by hand.

⚠️ Values that cross in the wrong shape

TL;DR: JS calls Wasm exports (instance.exports.stayPrice), Wasm calls JS imports ({ display: { showTotal } }, checked at instantiate time: a LinkError when missing), and both share linear memory. Only numbers cross directly: i32 (ToInt32: 2.9 becomes 2, a non-numeric string silently becomes 0), i64 as a BigInt (Chrome 85, Firefox 78, Safari 14.1; a Number is refused with a TypeError), f32/f64, plus externref to hold a JS object without reading it. Strings travel as bytes: TextEncoder into memory, then a pointer and a length ("Renée" is 5 letters but 6 bytes), and TextDecoder to read back. Every crossing has a cost (960,000 calls to grayPixel take 8 ms, against 1.8 ms of JavaScript), so send the data at once and call once.

⚡ Exports to JS, imports to Wasm

Write:

const imports = {
  display: { showTotal: (total) => console.log('Total: $' + total / 100) },
};
WebAssembly.instantiate(bytes, imports).then(({ instance }) => {
  const { stayPrice, order } = instance.exports;
  console.log(stayPrice(2, 3500)); // 7000 (cents)
  order(2, 3500);                  // Total: $70
});

Meaning: JS calls Wasm exports, Wasm calls JS imports, and both share linear memory. The import object must have the same shape as (import "display" "showTotal" ...). It is checked at instantiate time: if showTotal is missing, you get a LinkError.

⚡ Only numbers cross directly

Guess first: what does stayPrice(2.9, "3500") give?

7000, with no error. An i32 parameter goes through ToInt32: 2.9 becomes 2, the string "3500" becomes 3500.

Meaning: An i32 is a Number cut down to 32 bits, an i64 crosses as a BigInt, and an externref holds a JS object whole without being able to read it. Strings and the contents of objects have to become bytes in memory.

⚡ Strings travel as bytes

Write:

const nameBytes = new TextEncoder().encode(name); // 6 bytes: 52 65 6e c3 a9 65 (hex)
new Uint8Array(memory.buffer).set(nameBytes, ptr);
toUpper(ptr, nameBytes.length);                   // what crosses: two i32s, 0 and 6
Guess first: the guest name "Renée" has 5 letters. How many bytes have to be written into memory?

6 bytes. In UTF-8, é takes 2 bytes (c3 a9). That is why the length you send must be nameBytes.length, not name.length.

Meaning: TextEncoder turns a string into UTF-8 bytes, and then only a pointer and a length cross. TextDecoder reads the bytes back into a string.

⚡ Every crossing has a cost

Meaning: One crossing is only a few nanoseconds, but 960,000 calls to grayPixel take 8 ms, against 1.8 ms of plain JavaScript. Gather the data, write it to memory once, then call once.

What you will learn