@enclave-vm/browser integrates naturally with React applications. This guide covers hook patterns for lifecycle management, console capture, tool handler wiring, and a complete playground example.
Basic Hook Pattern
TheuseEnclave hook manages the enclave lifecycle — dynamic import, initialization, re-creation on config changes, and cleanup on unmount:
- Dynamic import keeps
@enclave-vm/browserout of the initial bundle - Ref for toolHandler avoids re-creating the enclave when the handler identity changes
- Cleanup on unmount calls
dispose()to remove sandbox iframes - Re-creates on
securityLevelchange to apply new security configuration
Using the Hook
Console Capture
Sandbox console output is relayed to the host’sconsole with an [Enclave] prefix. The useConsoleCapture hook intercepts these messages:
With Tool Handlers
Wire up tool handlers that connect sandbox code to your application:Security Level Picker
A small component for switching security levels:Bundling Considerations
- ESM only:
@enclave-vm/browseris distributed as ESM. Ensure your bundler supportsimport(). - Dynamic import: Use
import('@enclave-vm/browser')for code splitting. The library includes@enclave-vm/astwhich adds to bundle size — dynamic import keeps it off the critical path. - No Node.js dependencies: The browser package has no
vm,worker_threads, or other Node.js module dependencies. - Dependencies: Requires
@enclave-vm/ast(for AST validation and code transformation) andzod(for message schema validation).
Browser Compatibility
| Feature Required | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
iframe srcdoc | 20+ | 25+ | 6+ | 79+ |
iframe sandbox | 4+ | 17+ | 5+ | 79+ |
postMessage | 1+ | 6+ | 4+ | 79+ |
Proxy | 49+ | 18+ | 10+ | 79+ |
TextEncoder | 38+ | 18+ | 10.1+ | 79+ |
crypto.randomUUID | 92+ | 95+ | 15.4+ | 92+ |
crypto.randomUUID has a built-in fallback using Date.now() for older browsers, so it is not a hard requirement.Complete Example: Code Playground
A full working example combining all patterns:Related
- Overview - Getting started with browser enclave
- Configuration - All configuration options
- EnclaveJS React - React bindings for streaming