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
native-tags.go
API Differences
The WASM API is more limited than the native Go API:Available in WASM
1
PeerConnection Creation
NewPeerConnection works the same way2
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
- 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
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
call-from-js.html
Serving WASM
You need a web server to serve WASM files:server.go
serve.sh
Build Script
Create a build script for convenience:build.sh
Debugging
Browser Console
Allfmt.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
- No Media Engine: Can’t configure codecs directly
- No Interceptors: Can’t intercept RTP/RTCP packets
- Limited SettingEngine: Only data channel detaching supported
- Browser Restrictions: Subject to browser WebRTC policies
- Performance: WASM may be slower than native code
- 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
Full WASM Application
Full WASM Application
main.go:index.html:Build and run:
Related Resources
SettingEngine
Limited settings available in WASM
Data Channels
Data channel usage guide