Skip to content

Zig & WebAssembly

WebAssembly (wasm) is a small, portable instruction format that browsers, Node.js and many other hosts can run safely. Zig can build .wasm files out of the box: no extra toolchain, no plugin, just a different -target. That makes it a nice fit for speeding up one hot function in a web app, or for shipping one program that runs anywhere there’s a wasm runtime. This page builds both kinds of wasm module and runs them with Node.js, with real output and real file sizes.

Zig offers two wasm targets you’ll actually use:

Target What it is Has main? Runs in
wasm32-freestanding A library of functions, nothing else. No files, no stdout, no clock. No Browsers, Node.js, anything that loads wasm
wasm32-wasi A normal program. WASI gives it files, stdout, args and a clock. Yes wasmtime, wasmer, Node.js’s WASI support

Use freestanding when JavaScript is in charge and calls your Zig functions. Use WASI when you want a command-line program that runs in a wasm runtime instead of natively. The language reference on WebAssembly shows both.

Start with plain Zig functions marked export, exactly like when you export to C:

export fn add(a: i32, b: i32) i32 {
return a + b;
}
export fn fib(n: u32) u64 {
var a: u64 = 0;
var b: u64 = 1;
for (0..n) |_| {
const next = a + b;
a = b;
b = next;
}
return a;
}

Save it as math.zig and build it:

Terminal window
zig build-exe math.zig -target wasm32-freestanding -fno-entry -rdynamic -O small
  • -target wasm32-freestanding: 32-bit WebAssembly with no operating system.
  • -fno-entry: there’s no main. JavaScript decides what to call.
  • -rdynamic: keep every export fn visible to the host. (You can also name them one by one with --export=add.)
  • -O small: optimize for size, which is usually what you want on the web.

You get math.wasm. Now a small Node.js script to load it and call the functions. Save it as run.mjs next to the .wasm file:

import { readFile } from "node:fs/promises";
const bytes = await readFile("math.wasm");
const { instance } = await WebAssembly.instantiate(bytes);
const { add, fib } = instance.exports;
console.log("add(2, 3) =", add(2, 3));
console.log("fib(50) =", fib(50));
Terminal window
node run.mjs

You’ll see:

add(2, 3) = 5
fib(50) = 12586269025n

(We ran this with Node.js 22.) The n after the second number isn’t a typo: fib returns a u64, and JavaScript numbers can’t hold every 64-bit integer exactly, so wasm 64-bit integers arrive as BigInt values. i32, u32, f32 and f64 arrive as normal numbers. In a browser, it’s the same code with fetch("math.wasm") and WebAssembly.instantiateStreaming instead of readFile.

wasm files travel over the network, so size matters. Here’s math.wasm in each build mode, as we built it with Zig 0.17.1:

Build Size
debug (the default) 618,528 bytes
debug with -fstrip 447 bytes
safe 7,003 bytes
fast 6,109 bytes
fast with -fstrip 260 bytes
small 153 bytes

Almost all of the big numbers are debug information, not code. small strips it by default; for the other modes, add -fstrip when you ship. 153 bytes for two working functions is about as small as wasm gets.

Two things you’ll want soon: calling back into JavaScript (to log, or to touch the page), and passing strings. wasm functions can only take and return numbers, so strings travel as “a pointer and a length” into the module’s memory, which JavaScript can read and write as a big byte array.

const std = @import("std");
// Provided by JavaScript when it loads the module.
extern "env" fn consoleLog(ptr: [*]const u8, len: usize) void;
fn log(comptime fmt: []const u8, args: anytype) void {
var buf: [256]u8 = undefined;
const msg = std.mem.print(&buf, fmt, args) catch return;
consoleLog(msg.ptr, msg.len);
}
const gpa = std.heap.wasm_allocator;
export fn alloc(len: usize) ?[*]u8 {
const bytes = gpa.alloc(u8, len) catch return null;
return bytes.ptr;
}
export fn free(ptr: [*]u8, len: usize) void {
gpa.free(ptr[0..len]);
}
export fn countVowels(ptr: [*]const u8, len: usize) u32 {
const text = ptr[0..len];
var n: u32 = 0;
for (text) |c| {
switch (std.ascii.toLower(c)) {
'a', 'e', 'i', 'o', 'u' => n += 1,
else => {},
}
}
log("Zig got \"{s}\" ({d} bytes)", .{ text, len });
return n;
}
  • extern "env" fn consoleLog(...) declares a function that the host provides, under the module name "env". Zig doesn’t know what it does; JavaScript fills it in.
  • std.heap.wasm_allocator is an allocator made for wasm. It grows the module’s memory when it needs more.
  • alloc and free are exported so JavaScript can ask Zig for space to put a string in. Whoever allocates must also free, same rule as in Zig.

And the JavaScript side, text.mjs:

import { readFile } from "node:fs/promises";
let memory; // filled in once the module is loaded
const imports = {
env: {
consoleLog(ptr, len) {
const bytes = new Uint8Array(memory.buffer, ptr, len);
console.log(new TextDecoder().decode(bytes));
},
},
};
const { instance } = await WebAssembly.instantiate(await readFile("text.wasm"), imports);
const { alloc, free, countVowels } = instance.exports;
memory = instance.exports.memory;
const input = new TextEncoder().encode("Hello from JavaScript");
const ptr = alloc(input.length);
new Uint8Array(memory.buffer, ptr, input.length).set(input);
console.log("vowels:", countVowels(ptr, input.length));
free(ptr, input.length);
Terminal window
zig build-exe text.zig -target wasm32-freestanding -fno-entry -rdynamic -O small
node text.mjs

You’ll see:

Zig got "Hello from JavaScript" (21 bytes)
vowels: 6

The round trip: JavaScript encodes the string to UTF-8 bytes, asks Zig for 21 bytes with alloc, copies the bytes into wasm memory at that address, and calls countVowels with the pointer and length. Zig formats a message into a stack buffer and hands its pointer and length to consoleLog, which reads the bytes back out of the same memory. This build came out at 2,142 bytes.

With wasm32-wasi, you write a regular Zig program with main, args and stdout. Nothing about it is wasm-specific:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
var buf: [256]u8 = undefined;
var stdout = std.Io.File.stdout().writer(init.io, &buf);
const out = &stdout.interface;
try out.print("Hello from WASI! I got {d} arguments:\n", .{args.len});
for (args, 0..) |arg, i| try out.print(" {d}: {s}\n", .{ i, arg });
try out.flush();
}
Terminal window
zig build-exe hello.zig -target wasm32-wasi -O small

That made a 46,582-byte hello.wasm here (it carries the parts of the standard library that talk to WASI; the debug build was 1.4 MB). The reference runs WASI programs with wasmtime (wasmtime hello.wasm one two). Node.js has WASI support built in too, so here’s a runner with nothing to install, wasi.mjs:

import { readFile } from "node:fs/promises";
import { WASI } from "node:wasi";
const wasi = new WASI({ version: "preview1", args: ["hello.wasm", "one", "two"] });
const module = await WebAssembly.compile(await readFile("hello.wasm"));
const instance = await WebAssembly.instantiate(module, wasi.getImportObject());
wasi.start(instance);

You’ll see:

(node:19732) ExperimentalWarning: WASI is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Hello from WASI! I got 3 arguments:
0: hello.wasm
1: one
2: two

Node.js still marks WASI as experimental, hence the warning (the number in it is a process id and changes). The same .wasm file runs unchanged in wasmtime, wasmer, or any other WASI runtime, on any operating system. That’s the appeal: build once, run anywhere there’s a runtime.

In a project, put the target and flags in build.zig instead of typing them each time:

const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.resolveTargetQuery(.{
.cpu_arch = .wasm32,
.os_tag = .freestanding,
});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "math",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
}),
});
exe.entry = .disabled; // no main function
exe.rdynamic = true; // keep every `export fn`
b.installArtifact(exe);
}
Terminal window
zig build -Doptimize=small

That puts zig-out/bin/math.wasm in place, 153 bytes again. resolveTargetQuery fixes the target to wasm no matter which machine builds it, and exe.entry = .disabled and exe.rdynamic = true are the build.zig spellings of -fno-entry and -rdynamic. For WASI, use .os_tag = .wasi and leave the entry alone. Zig Build System explains the rest of the file.

Write circleArea(radius: f64) f64 and isEven(n: i32) bool as exports, build them for wasm32-freestanding, and call circleArea(2), isEven(7) and isEven(10) from Node.js.

Hint: use @rem(n, 2) == 0 for isEven, since % on signed numbers needs @rem or @mod. Watch what JavaScript gets for a bool.

Show solution

shapes.zig:

export fn circleArea(radius: f64) f64 {
return 3.141592653589793 * radius * radius;
}
export fn isEven(n: i32) bool {
return @rem(n, 2) == 0;
}

shapes.mjs:

import { readFile } from "node:fs/promises";
const { instance } = await WebAssembly.instantiate(await readFile("shapes.wasm"));
const { circleArea, isEven } = instance.exports;
console.log("circleArea(2) =", circleArea(2));
console.log("isEven(7) =", isEven(7), " isEven(10) =", isEven(10));
Terminal window
zig build-exe shapes.zig -target wasm32-freestanding -fno-entry -rdynamic -O small
node shapes.mjs

You’ll see:

circleArea(2) = 12.566370614359172
isEven(7) = 0 isEven(10) = 1

wasm has no boolean type, so a Zig bool arrives in JavaScript as 0 or 1. Wrap it with Boolean(...) on the JavaScript side if you need true and false.

Write an exported countDown(from: u32) that calls a JavaScript function logNumber(n) for each number from from down to 1. Provide logNumber from Node.js.

Hint: declare it as extern "env" fn logNumber(n: u32) void; and pass { env: { logNumber: ... } } as the second argument to WebAssembly.instantiate.

Show solution

count.zig:

extern "env" fn logNumber(n: u32) void;
export fn countDown(from: u32) void {
var n = from;
while (n > 0) : (n -= 1) {
logNumber(n);
}
}

count.mjs:

import { readFile } from "node:fs/promises";
const imports = {
env: {
logNumber: (n) => console.log("Zig says:", n),
},
};
const { instance } = await WebAssembly.instantiate(await readFile("count.wasm"), imports);
instance.exports.countDown(3);

You’ll see:

Zig says: 3
Zig says: 2
Zig says: 1

If you forget the env object, loading fails before any code runs, with TypeError: WebAssembly.instantiate(): Import #0 module="env": module is not an object or function. Every extern the module declares must be provided.

  • wasm32-freestanding builds a library of exported functions for JavaScript; wasm32-wasi builds a normal program with main for a WASI runtime.
  • Build freestanding modules with -fno-entry -rdynamic (or --export=name), or your exports disappear.
  • -O small gives tiny files; most of a debug .wasm is debug info. Use -fstrip in other modes.
  • 64-bit integers arrive in JavaScript as BigInt, and a bool arrives as 0 or 1.
  • Call JavaScript with extern "env" fn. Pass strings as a pointer and length into the module’s memory, with exported alloc/free using std.heap.wasm_allocator.
  • In build.zig, use resolveTargetQuery, exe.entry = .disabled and exe.rdynamic = true.

Next up: Zig Embedded, running Zig on microcontrollers, with no operating system at all.

Quick check

1. You want JavaScript in a browser to call a fast Zig function. Which target fits?
2. You built a module and JavaScript says add is not a function. What is the most likely cause?
3. How does a string get from JavaScript into a Zig wasm function?
4. Why is a debug build of a tiny module hundreds of kilobytes, but the small build only 153 bytes?