Getting Started
The Orchestra Analogy
Imagine you're at a symphony concert. The conductor raises their baton, and suddenly:
- The violins know exactly when to play
- The drums don't overpower the flutes
- Each section responds to cues without shouting across the room
- If a musician misses their cue, they catch up gracefully
Now imagine the alternative: a room full of musicians shouting instructions to each other. Chaos, right?
Most event buses are the "shouting room." Nexus is the conductor.
The Problem with Traditional Event Buses
Standard event libraries (like Node's EventEmitter or custom implementations) suffer from:
- No priority system: Everything runs at the same urgency, blocking critical UI updates
- No failure recovery: One error crashes your listener chain
- No request/reply: You have to manually implement correlation IDs
- No cross-context communication: Client and server are isolated islands
- No learning: The same mistakes happen repeatedly
Nexus was designed from the ground up to solve these real-world production issues.
Installation
npm install @caeligo/nexus-orchestratorOr with other package managers:
# Yarn
yarn add @caeligo/nexus-orchestrator
# pnpm
pnpm add @caeligo/nexus-orchestratorYour First Nexus Instance
import { Nexus } from '@caeligo/nexus-orchestrator';
// Create a bus instance
const bus = new Nexus();
// Subscribe to an event
bus.on('user:login', (payload) => {
console.log(`Welcome, ${payload.username}!`);
});
// Emit an event
bus.emit('user:login', { username: 'Alice', timestamp: Date.now() });Output:
Welcome, Alice!Simple, right? But this is just scratching the surface.
Basic Example: Real-World Dashboard
Let's build a simple analytics dashboard that updates in real-time:
import { Nexus } from '@caeligo/nexus-orchestrator';
// Define your event types for type safety
interface DashboardEvents {
'metrics:cpu': { usage: number };
'metrics:memory': { used: number; total: number };
'alert:critical': { message: string; severity: 'high' | 'medium' | 'low' };
}
const bus = new Nexus<DashboardEvents>({
debug: true, // Enable DevTools
replayMemory: 10 // Keep last 10 events
});
// Setup listeners
bus.on('metrics:cpu', (data) => {
document.getElementById('cpu')!.innerText = `${data.usage}%`;
});
bus.on('metrics:memory', (data) => {
const percent = ((data.used / data.total) * 100).toFixed(1);
document.getElementById('memory')!.innerText = `${percent}%`;
});
bus.on('alert:critical', (alert) => {
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${alert.severity}`;
alertDiv.innerText = alert.message;
document.getElementById('alerts')!.appendChild(alertDiv);
});
// Simulate data updates (in real app, this would come from WebSocket)
setInterval(() => {
bus.emit('metrics:cpu', { usage: Math.random() * 100 });
bus.emit('metrics:memory', {
used: Math.random() * 8000,
total: 8000
});
}, 1000);Edge Case: Handling Late Subscribers
What if a component subscribes after data has already been emitted? With replay memory, late arrivals catch up automatically:
const bus = new Nexus({
replayMemory: 50 // Keep last 50 events per channel
});
// Emit data early
bus.emit('config:loaded', { theme: 'dark', language: 'en' });
// Component mounts 5 seconds later and needs the config
setTimeout(() => {
bus.on('config:loaded', (config) => {
console.log('Late subscriber got:', config);
// Output: { theme: 'dark', language: 'en' }
}, { replay: true }); // 👈 The magic happens here
}, 5000);Configuration Options
Here's the complete configuration interface:
const bus = new Nexus({
// Replay System: Store past events for late subscribers
replayMemory: 50, // Keep last 50 events per channel
// Cross-Tab Sync: Share events across browser tabs
crossTabName: 'my-app', // BroadcastChannel name
// Debugging: Redux DevTools integration
debug: true, // Enable logging and DevTools
// AI Prediction: Learn user patterns (more in AI chapter)
predictionThreshold: 0.7, // Emit predictions at 70% confidence
// Teleportation: Send events to server (more in Networking chapter)
teleport: (event, payload) => {
websocket.send(JSON.stringify({ event, payload }));
},
// Chaos Monkey: Test resilience (more in Testing chapter)
chaos: {
dropRate: 0.1, // Drop 10% of events
maxDelay: 2000, // Add up to 2s latency
exclude: ['app:init'] // Never chaos-test critical events
}
});Architecture Diagram
Next Steps
Now that you understand the basics, let's explore the architecture in depth:
- Architecture Overview - Understand how Nexus works internally
- RPC Pattern - Master request/reply communication
- Priority Lanes - Optimize performance with execution scheduling
Quick Reference
Import:
import { Nexus } from '@caeligo/nexus-orchestrator';Create instance:
const bus = new Nexus(options);Core methods:
bus.on(event, listener, options)- Subscribe to eventsbus.emit(event, payload, options)- Publish eventsbus.once(event, listener)- Subscribe for single executionbus.request(event, payload, timeout)- Request/Reply patternbus.cursor(event, initialValue)- Get reactive state cursor
Advanced:
bus.pipe(event, ...operators, listener)- Middleware pipelinebus.feed(event, payload)- Ingest external eventsbus.scenario()- Fluent workflow builderbus.generateGraph()- Export Mermaid diagram
