Skip to main content

Overview

Pion WebRTC can be compiled to WebAssembly (WASM) and run in web browsers. This allows you to write both client and server code in Go, using the same API on both sides.
When compiled to WASM, Pion WebRTC acts as a wrapper around the browser’s native WebRTC implementation. Not all features available in the native Go version are available in WASM.

Building for WebAssembly

Basic Build

build.sh

Copy WASM Exec

You need the wasm_exec.js file from your Go installation:
copy-wasm-exec.sh

HTML Setup

Create an HTML file to load your WASM module:
index.html

Basic WASM Example

main.go

Build Tags

When writing code for WebAssembly, use build tags:
build-tags.go
For native Go code:
native-tags.go
From api_js.go:4-5.

API Differences

The WASM API is more limited than the native Go API:

Available in WASM

1

PeerConnection Creation

NewPeerConnection works the same way
2

Basic Configuration

ICE servers and basic configuration options
3

Data Channels

Create and use data channels, including detaching
4

Event Handlers

OnICECandidate, OnConnectionStateChange, etc.

Not Available in WASM

These features are only available in native Go builds:
  • MediaEngine configuration
  • InterceptorRegistry
  • Most SettingEngine options
  • Custom network interfaces
  • UDP/TCP mux
  • Custom logging (browser console is used)

SettingEngine in WASM

The WASM SettingEngine has limited functionality:
wasm-setting-engine.go
From settingengine_js.go:9-24.

Data Channel Example

datachannel.go

Detached Data Channels

Detach data channels for direct I/O access:
detached.go

Interacting with JavaScript

You can interact with JavaScript from your WASM code:
js-interop.go
In your HTML:
call-from-js.html

Serving WASM

You need a web server to serve WASM files:
server.go
Run the server:
serve.sh
Then open http://localhost:8080 in your browser.

Build Script

Create a build script for convenience:
build.sh

Debugging

Browser Console

All fmt.Println calls appear in the browser console:
debug.go

Source Maps

Build with debug information:
debug-build.sh

Check WASM Support

check-wasm.go

Limitations

Be aware of these limitations when using WASM:
  1. No Media Engine: Can’t configure codecs directly
  2. No Interceptors: Can’t intercept RTP/RTCP packets
  3. Limited SettingEngine: Only data channel detaching supported
  4. Browser Restrictions: Subject to browser WebRTC policies
  5. Performance: WASM may be slower than native code
  6. Bundle Size: WASM files can be large (several MB)

Best Practices

1

Use Build Tags

Separate WASM and native code with build tags
2

Minimize WASM Size

Only include necessary code in WASM builds
3

Handle Errors Gracefully

WASM errors appear in browser console - make them informative
4

Test in Multiple Browsers

Different browsers may behave differently

Complete Example

main.go:
index.html:
Build and run:

SettingEngine

Limited settings available in WASM

Data Channels

Data channel usage guide