🔌 Unified messaging for browser applications
Zero dependencies. Fast. Secure by default.
📚 Documentation · 🎮 Playground · 📖 Advanced Patterns
Stop wrestling with postMessage. CrossBus gives you a simple RPC layer for iframes, workers, tabs, and AI agents—with security defaults you can't forget to configure.
// That's it. Two lines to connect an iframe.
const hub = CrossBus.createSecure({ isHub: true, allowedOrigins: ['https://app.com'] });
hub.handle('getData', async (p) => ({ users: await db.query(p.filter) }));
// In your iframe - instant RPC
const data = await agent.request('hub', 'getData', { filter: 'active' });|
🔒 Secure by Default
|
⚡ Fast
|
🤖 Browser-First Design
|
| Feature | CrossBus | Comlink | Penpal | Post-Robot |
|---|---|---|---|---|
| llms.txt + agent.json | ✅ | ❌ | ❌ | ❌ |
| createSecure() factory | ✅ | ❌ | ❌ | ❌ |
| Handler rate limiting | ✅ | ❌ | ❌ | ❌ |
| Schema validation | ✅ | ❌ | ❌ | ❌ |
| healthCheck() + diagnose() | ✅ | ❌ | ❌ | ❌ |
| Causal ordering | ✅ | ❌ | ❌ | ❌ |
| 7 transport types | ✅ | ❌ | ❌ | ❌ |
| WebSocket reconnection | ✅ | ❌ | ❌ | ❌ |
npm install crossbusimport { CrossBus, PostMessageTransport } from 'crossbus';
// 1. Create secure hub (enforces security best practices)
const hub = CrossBus.createSecure({
peerId: 'hub',
isHub: true,
allowedOrigins: ['https://yourdomain.com']
});
// 2. Register handlers
hub.handle('getData', async ({ userId }) => {
return await fetchUserData(userId);
});
// 3. Connect iframe
const iframe = document.getElementById('agent-frame');
hub.addTransport(new PostMessageTransport(iframe.contentWindow), { peerId: 'agent' });import { CrossBus, PostMessageTransport } from 'crossbus';
const agent = new CrossBus({ peerId: 'agent', allowedOrigins: ['*'] });
agent.addTransport(new PostMessageTransport(window.parent), { peerId: 'hub' });
// That's it! RPC to parent is now trivial
const user = await agent.request('hub', 'getData', { userId: 123 });| Benchmark | CrossBus | nanoevents | EventEmitter3 | mitt |
|---|---|---|---|---|
| emit (1 listener) | 172M ops/s 🏆 | 170M | 131M | 21M |
| emit (10 listeners) | 57M | 73M 🏆 | 31M | 22M |
| Large payloads (10KB) | 111M | 116M 🏆 | 40M | 19M |
Benchmarked with
bun run bench:compareon Apple Silicon. Results vary by run.
| Use Case | Transport | Why CrossBus |
|---|---|---|
| Micro-frontends | PostMessageTransport | Orchestrate cross-domain iframes with type-safe RPC |
| Hybrid apps | NativeBridgeTransport | Bridge web ↔ native (iOS/Android) |
| Web workers | MessageChannelTransport | Parallel processing with clean async APIs |
| Multi-tab sync | BroadcastChannelTransport | Share state across browser tabs |
| Service workers | ServiceWorkerTransport | Runtime network behavior modification |
| Real-time collab | WebSocketTransport | Auto-reconnect, backpressure, streaming |
// Security is NOT optional—createSecure() enforces it
const hub = CrossBus.createSecure({
allowedOrigins: ['https://trusted.com'] // ✅ No wildcards allowed
});
// Per-handler security controls
hub.handle('admin:delete', handler, {
allowedPeers: ['admin-agent'], // Only admin can call
rateLimit: 10, // 10 calls/sec max
validatePayload: (p) => p.id != null // Custom validation
});
// Schema validation plugin
import { withSchemaValidation } from 'crossbus/plugins/schema-validation';
hub.handle('createUser', withSchemaValidation({
type: 'object',
required: ['name', 'email'],
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', pattern: '^[^@]+@[^@]+$' }
}
}, async (user) => createUser(user)));Dev mode warnings alert you to insecure configurations before they reach production.
CrossBus excels at coordinating complex browser applications:
| File | Purpose |
|---|---|
| llms.txt | AI-optimized quick reference |
| agent.json | A2A Agent Card manifest |
| GEMINI.md | Google/Gemini instructions |
| CLAUDE.md | Anthropic/Claude instructions |
| docs/AGENTS.md | 1200+ lines multi-agent guide |
| Transport | Use Case | Example |
|---|---|---|
| PostMessage | iframe ↔ parent | Chat widgets, embedded apps |
| BroadcastChannel | Tab ↔ tab | Cart sync, notifications |
| MessageChannel | Main ↔ worker | Heavy computation offload |
| SharedWorker | Cross-tab state | Shared connection pool |
| ServiceWorker | Offline-first | PWA sync |
| NativeBridge | WebView ↔ Native | Mobile apps |
| WebSocket | Browser ↔ Server | Real-time backend |
// Encryption (AES-256-GCM)
import { withEncryption } from 'crossbus/plugins/encryption';
withEncryption(bus, await Encryption.deriveKey('password', 'salt'));
// Retry with exponential backoff
import { withRetry } from 'crossbus/plugins/retry';
withRetry(bus, { maxRetries: 3, baseDelay: 100 });
// Circuit breaker
import { createPeerCircuitBreaker } from 'crossbus/plugins/circuit-breaker';
const breaker = createPeerCircuitBreaker(bus, { failureThreshold: 5 });
// Compression for large payloads
import { withCompression } from 'crossbus/plugins/compression';
withCompression(bus, { threshold: 1024 });
// Rate limiting
import { withRateLimiter } from 'crossbus/plugins/rate-limiter';
withRateLimiter(bus, { maxRequests: 100, windowMs: 1000 });
// Batching for high-frequency updates
import { withBatching } from 'crossbus/plugins/batch';
withBatching(bus, { windowMs: 50, maxBatchSize: 100 });// Distributed tracing (OpenTelemetry-compatible)
import { Tracer, tracingPlugin } from 'crossbus/enterprise';
const tracer = new Tracer({ serviceName: 'hub' });
bus.addOutboundHook(tracingPlugin(tracer));
// Prometheus-compatible metrics
import { globalMetrics } from 'crossbus/enterprise';
console.log(globalMetrics.toPrometheus());
// Backpressure control
import { BackpressureController } from 'crossbus/enterprise';
const bp = new BackpressureController(bus, { highWaterMark: 1000 });
// Message versioning / migration
import { MessageVersioning } from 'crossbus/enterprise';
const versioning = new MessageVersioning();
versioning.registerMigration('user', 1, 2, (data) => ({ ...data, v2Field: true }));| Export | Size (gzip) |
|---|---|
| Full bundle | ~15 KB |
| Core only | ~10 KB |
| Nano emitter | 295 bytes |
1074 tests passing
98.41% line coverage on core
0 dependencies
- AGENTS.md — Complete multi-agent infrastructure guide
- API.md — Full API reference
- SECURITY.md — Security features and best practices
- examples/ — Machine-readable patterns
npm install crossbusimport { CrossBus } from 'crossbus';
const bus = CrossBus.createSecure({
peerId: 'my-app',
allowedOrigins: ['https://myapp.com']
});
// You're ready to build something amazing.⭐ Star us on GitHub · 📖 Documentation
License: Apache 2.0 © 2026
