Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 147 ยท Advanced Go

Go and WebAssembly

Compile Go to WebAssembly for the browser with GOOS=js and for servers with GOOS=wasip1. Learn syscall/js, wasm_exec.js, callbacks, wasmexport, size trade-offs and when it pays off.

WebAssembly (wasm) is a compact binary format that browsers, and a growing number of server runtimes, can execute at near-native speed in a safe sandbox. Go can compile to it with a single environment variable. That means you can take code you already wrote, such as a parser, an image filter, a game engine or a validation library, and run the same code in a web page, without rewriting it in JavaScript.

Go supports two WebAssembly targets. GOOS=js GOARCH=wasm is meant for the browser (and Node.js): your program talks to JavaScript through the syscall/js package. GOOS=wasip1 GOARCH=wasm targets WASI, the WebAssembly System Interface, which lets a program run outside a browser, in runtimes such as wasmtime or wazero, with controlled access to files, clocks and standard streams. This lesson covers both, plus the design habits that make wasm worth the trouble. You should be comfortable with goroutines, packages and unsafe and cgo, where wasm is first mentioned.

What actually happens when you compile

Terminal
GOOS=js GOARCH=wasm go build -o web/main.wasm ./cmd/wasm
cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" web/

The first command is ordinary cross-compilation (see tooling basics); the output is a .wasm file instead of an executable. The second copies a small JavaScript file shipped with the Go toolchain. A Go program needs a runtime: a garbage collector, a goroutine scheduler, timers. A browser provides none of that to wasm, so the Go runtime is compiled into your .wasm, and wasm_exec.js is the glue that lets it call out to the browser for the few things only the host can do (printing, clocks, scheduling a wake-up, and talking to JavaScript values).

flowchart LR
    GO["Go source<br/>//go:build js && wasm"] -->|"GOOS=js GOARCH=wasm<br/>go build"| W["main.wasm<br/>your code + Go runtime"]
    W --> B["Browser"]
    E["wasm_exec.js<br/>from GOROOT/lib/wasm"] --> B
    H["index.html<br/>loads both"] --> B

The browser needs three files: the HTML page, the glue script and the compiled module.

The page that loads it is short:

HTML
<script src="wasm_exec.js"></script>
<script>
  const go = new Go();
  WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject)
    .then(({ instance }) => go.run(instance));
</script>

instantiateStreaming compiles the module while it downloads, but only if the server sends the header Content-Type: application/wasm. Go's http.FileServer does this for .wasm files automatically, so a three-line Go server is enough for local testing; see HTTP servers. (On the browser side, WebAssembly basics explains the module, instance and memory objects that go.run uses behind the scenes.)

Your first browser program with syscall/js

The syscall/js package represents JavaScript values as js.Value. You can read and write properties, call methods and register Go functions that JavaScript can call. It compiles only for js/wasm, so files that use it start with a build constraint:

Go
//go:build js && wasm

package main

import (
	"strings"
	"syscall/js"
)

func main() {
	js.Global().Set("goWordCount", js.FuncOf(func(this js.Value, args []js.Value) any {
		return len(strings.Fields(args[0].String()))
	}))

	select {} // keep the program alive so JavaScript can keep calling it
}

After the page runs this, JavaScript can call goWordCount("one two three") and get 3. The pieces:

  • js.Global() is the browser's window (or globalThis). .Set(name, value) assigns a property, and the matching .Get, .Call, .Invoke and .New read, call and construct things on the JavaScript side.
  • js.FuncOf wraps a Go function as a JavaScript function. Its parameters are this and the argument list, and its result is converted by js.ValueOf, which understands bool, numbers, strings, nil, []any and map[string]any.
  • select {} blocks main forever. If main returned, the Go runtime would stop and every exported function would become useless. A common alternative is <-make(chan struct{}).
  • Arguments arrive as js.Value. You convert with .String(), .Int(), .Float(), .Bool(). Calling the wrong one (for example .Int() on a string) panics, so check Type() first when input comes from users.

The event-loop rule

JavaScript in a page is single-threaded, and Go callbacks run on that same thread. A callback must therefore return quickly. If it blocks, for example by waiting on a channel that only another callback can fill, the whole page freezes and the runtime reports a deadlock. For slow work, start a goroutine inside the callback and return at once:

Go
js.Global().Set("startJob", js.FuncOf(func(this js.Value, args []js.Value) any {
	done := args[0] // a JavaScript callback
	go func() {
		result := expensiveWork()
		done.Invoke(result)
	}()
	return nil
}))
sequenceDiagram
    participant UI as Page JavaScript
    participant G as Go callback
    participant R as Goroutine
    UI->>G: startJob(done)
    G->>R: go func() {...}
    G-->>UI: returns immediately
    Note over UI: page stays responsive
    R->>UI: done.Invoke(result)

The callback returns at once; the goroutine reports back later through a JavaScript function.

Also remember: a js.Func holds a reference that the Go runtime cannot free by itself. Call f.Release() when you no longer need a function (for example, an event listener you removed), or you leak memory. Functions you keep for the whole page life, like goWordCount, need no release.

Moving data across the boundary

Every call between Go and JavaScript copies and converts values, and the boundary is comparatively slow. Converting a map with 10,000 entries into a JavaScript object, call by call, can cost more than the computation you wanted to speed up. Rules of thumb:

  • Make few, coarse calls: send a whole image or a whole text, get the whole answer back, not one pixel or one character at a time.
  • For binary data, use js.CopyBytesToGo(dst, src) and js.CopyBytesToJS(dst, src), which copy between a []byte and a Uint8Array in one operation.
  • Pass simple values (numbers, strings, byte arrays) rather than deeply nested structures. Encode complex results as JSON and parse them in JavaScript once.

Keep the logic portable

The most valuable design habit is to separate your logic from the glue. Put the real work in ordinary packages with no syscall/js imports, and write a thin main.go (guarded by //go:build js && wasm) that registers the functions. The core then runs everywhere: you test it with plain go test, call it from a CLI or server, and compile it to wasm unchanged.

The program below imitates this structure on this page, where syscall/js does not exist. The "core" is plain Go. The "binding" layer mimics what js.FuncOf does, including a detail that surprises beginners: JavaScript numbers always arrive as float64.

Go A portable core and a thin binding layer

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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

Here the output starts with compiled for: linux/amd64 on a typical server, and the analysis finds 8 words, 26 letters and the top word the. In a real build, Analyze lives in its own package and both main.go files (the wasm one and, say, a CLI one) import it.

Compute-heavy work: a worked example

Wasm shines for CPU-bound loops over bytes or numbers: image filters, physics, compression, parsers, cryptography. The pattern is "bytes in, bytes out". The next program is a Game of Life step function that takes a grid as a flat []byte and returns the next generation, the exact shape you would expose with js.CopyBytesToGo from a canvas or typed array.

Go A byte-grid kernel suited to wasm

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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

In a browser build you would call Step from a callback, copy the result into a Uint8Array, and paint it on a <canvas> in requestAnimationFrame. One call per frame crosses the boundary; the 36 (or 360,000) cell updates stay inside wasm.

WASI: Go outside the browser

With GOOS=wasip1 GOARCH=wasm (available since Go 1.21) you compile an ordinary command-line program, with os.Args, os.Stdout, files and clocks, into a module that any WASI runtime can execute:

Terminal
GOOS=wasip1 GOARCH=wasm go build -o tool.wasm ./cmd/tool
wasmtime run tool.wasm -- --name world

The host decides what the program may touch. A directory must be explicitly "preopened" for the program to read it, and there is no network access in the base specification. That makes WASI attractive for plugin systems (run untrusted extensions with strict limits), serverless platforms and portable tools. The reverse direction also exists: your Go program can host wasm modules written in other languages, using a runtime library such as wazero, which is written in pure Go and needs no cgo.

Since Go 1.24 a WASI build can also export functions, not only run main. Mark a function with //go:wasmexport name and build with -buildmode=c-shared, and the host can call it repeatedly like a library; //go:wasmimport declares functions the host provides. Both directives are low-level and accept only simple types (integers and floats), which suits plugin boundaries.

Limits and trade-offs

  • File size. Because the runtime is included, even a small Go program produces a module of a couple of megabytes. Serve it with gzip or Brotli compression (typically a large reduction), cache it aggressively and show a loading indicator. If size is critical, TinyGo, an alternative compiler, produces modules in the tens to hundreds of kilobytes, at the price of an incomplete standard library and different runtime behavior.
  • Single thread. Goroutines work and are scheduled cooperatively, but they all run on one thread, so there is no parallel speed-up. Use Web Workers (several module instances) for real parallelism.
  • No raw sockets. The browser sandbox forbids them. net/http clients work in js/wasm by delegating to fetch, subject to CORS rules.
  • No direct DOM speed. Touching the DOM through syscall/js is slow compared with JavaScript. Let JavaScript own the UI and give Go the computation.
  • Garbage collection and memory. Linear memory only grows during a page's life; see garbage collection.
  • Debugging. Panics print to the browser console, and GOOS=js GOARCH=wasm go test -exec="$(go env GOROOT)/lib/wasm/go_js_wasm_exec" runs tests under Node.js.

When is it worth it?

Choose wasm when you already have substantial Go logic that must also run client-side (an offline-capable validator, a markdown or diff engine, a game or simulation), when you need predictable performance on heavy computation, or when you want a sandboxed plugin mechanism. Choose plain JavaScript or a server endpoint when the work is small, mostly DOM manipulation or network I/O. Often the right answer is the boring one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which environment variables compile a Go program for the browser?

    The operating system is js and the architecture is wasm. GOOS=wasip1 GOARCH=wasm is the separate WASI target for running outside the browser.
  2. 2. Why does main end with select {} in a syscall/js program?

    When main returns, the Go program exits and its exported functions stop working. Blocking forever keeps the runtime and its callbacks available.
  3. 3. A js.FuncOf callback waits on a channel that only another JavaScript callback will fill. What happens?

    Callbacks run on the browser's event loop. Blocking there stops the loop that would deliver the second callback. Return quickly and do slow work in a goroutine.
  4. 4. What type does a JavaScript number have when it reaches Go through js.Value or an any binding?

    JavaScript has a single number type, a double-precision float. Use .Int() or a conversion such as int(f) if you need an integer, and be careful with values that are not whole numbers.
  5. 5. Which design makes Go code most reusable between wasm, a CLI and a server?

    A portable core can be tested with go test and imported by every target. Only the small binding file needs syscall/js.

Summary

  • GOOS=js GOARCH=wasm go build produces a module for the browser; you also need wasm_exec.js from $(go env GOROOT)/lib/wasm and a page that loads both.
  • syscall/js exposes js.Global, js.FuncOf and js.Value; block main with select {}, keep callbacks short and release functions you stop using.
  • Cross the Go/JavaScript boundary rarely, with bytes or simple values; numbers from JavaScript arrive as float64.
  • Keep logic in portable packages and bind it with a tiny //go:build js && wasm file.
  • GOOS=wasip1 GOARCH=wasm targets WASI runtimes; since Go 1.24 //go:wasmexport lets a module export functions.
  • Expect multi-megabyte modules and a single thread; use wasm for computation, not for UI work.

Next: Project: Command-Line To-Do Manager.