Skip to content

Lesson 3 of 9 · 22m

JS/Wasm Interop Without Losing Your Mind

Numeric signatures, exported memory, string marshalling, callbacks into JavaScript, and why every boundary crossing deserves a design decision.

The raw WebAssembly type system is brutally small: numbers go in, numbers come out. Strings, objects, arrays, promises, DOM nodes — none of those exist at the boundary. Everything else is a convention implemented through memory layout and glue code. Once you accept that, interop stops being mysterious and becomes protocol design.

The primitive contract

A raw export often looks like this:

const result = instance.exports.transform(ptr, len, seed);

Those arguments are integers. ptr is an offset into linear memory, len is byte length, and seed is numeric input. Nothing in this signature tells you whether the memory is UTF-8, image pixels, or a serialized struct. The protocol is the documentation.

Strings are bytes plus an encoding decision

The common pattern is copy-in/copy-out:

const memory = instance.exports.memory;
const bytes = new TextEncoder().encode("input payload");

const ptr = instance.exports.alloc(bytes.length);
new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);

const outPtr = instance.exports.process_utf8(ptr, bytes.length);
const outLen = instance.exports.last_output_len();
const output = new TextDecoder().decode(
  new Uint8Array(memory.buffer, outPtr, outLen)
);
instance.exports.dealloc(ptr, bytes.length);

This is correct but verbose, which is why toolchains emit glue. The senior move is not writing this by hand everywhere; it's understanding what the generated glue is doing so you can spot copies, leaks, and encoding mismatches.

Calling back into JavaScript

Wasm can invoke imported host functions, but only with primitive values. If Wasm needs rich host behavior, export a narrow capability interface:

env: {
  emit_metric(namePtr, nameLen, value) {
    const name = readUtf8(namePtr, nameLen);
    metrics.increment(name, value);
  },
}

Resist the urge to expose a generic eval or arbitrary object bridge. Every import enlarges the sandbox's authority and your attack surface.

Use interface layers

Modern tooling increasingly uses the component model and interface types, but browser support and toolchain maturity still vary by ecosystem. For most application teams in 2026, practical interop means stable generated bindings, explicit allocation ownership, and a versioned ABI. Treat the ABI like a public API — changing struct layout without coordination is a breaking change.

Field notes

  • If a binding layer hides allocation, find out who frees memory before shipping.
  • UTF-8 is bytes; UTF-16 is JavaScript strings. Conversion is not free.
  • A boolean is usually i32 at the boundary, not a JS boolean.
  • Design for batch operations. Chatty interop is how a fast kernel becomes a slow application.

Was this lesson helpful?

Sign in to rate