Realtime channels and WebRTC
Sync transient state across tabs with BroadcastChannel, open peer-to-peer WebRTC data channels, or consume SSE and WebSocket feeds.
@orbixdocs/sdk/realtime provides low-latency messaging primitives for live cursors, multi-tab coordination, peer-to-peer sessions, and streaming feeds.
Choosing the right transport
Pick the primitive that matches who needs to receive updates and whether the data belongs in the saved document:
| API | Scope | Persisted to document? | Typical use |
|---|---|---|---|
useOrbixState | All collaborators viewing the document | Yes (on block props) | Checklists, form state, configuration, saved block data. |
useCollaborative | Tabs and block instances in the same browser (BroadcastChannel) | No (localStorage snapshot per browser) | Multi-tab sync, split-view ↔ inline block cursors, local multi-instance coordination. |
realtimeEngine.connectPeer | Two users across the internet (RTCPeerConnection + Supabase signaling) | No (direct P2P RTCDataChannel) | Ephemeral peer-to-peer cursors, whiteboard strokes, turn-based sessions. |
realtimeEngine.sse / useOrbixWebSocket | Block ↔ external server | No | Live price feeds, CI build logs, telemetry streams. |
Same-browser state and presence (useCollaborative)
Import useCollaborative from @orbixdocs/sdk/realtime to share transient state, peer presence, and one-off action events across tabs or multiple instances of your block on the same origin:
import { defineBlock, type BlockRenderProps } from '@orbixdocs/sdk';
import { useCollaborative } from '@orbixdocs/sdk/realtime';
interface BoardState {
activeNote: string;
}
export default defineBlock({
manifest: {
id: 'acme.collab-board',
name: 'Scratchpad Sync',
version: '1.0.0',
sdk: '^3.0.0',
},
component(props: BlockRenderProps) {
const {
state,
setState,
peers,
updatePresence,
broadcastAction,
} = useCollaborative<BoardState>('scratchpad', { activeNote: '' }, {
persist: true,
onRemoteAction(action) {
if (action === 'clear') {
setState({ activeNote: '' });
}
},
});
return (
<div
onPointerMove={(e) => {
const rect = e.currentTarget.getBoundingClientRect();
updatePresence({
cursor: {
x: Math.round(e.clientX - rect.left),
y: Math.round(e.clientY - rect.top),
},
});
}}
style={{
padding: 14,
borderRadius: 12,
background: 'var(--orbix-card-bg, #16171b)',
border: '1px solid var(--orbix-surface-border, #2a2b32)',
color: 'var(--orbix-text-primary, #f4f4f5)',
}}
>
<div style={{ fontSize: 12, marginBottom: 8, color: 'var(--orbix-text-secondary, #a1a1aa)' }}>
Connected local tabs/instances: {peers.length + 1}
</div>
<textarea
value={state.activeNote}
disabled={props.isReadOnly}
onChange={(e) => setState({ activeNote: e.target.value })}
rows={3}
style={{ width: '100%' }}
/>
<button
type="button"
disabled={props.isReadOnly}
onClick={() => {
setState({ activeNote: '' });
broadcastAction('clear');
}}
style={{ marginTop: 8 }}
>
Clear across tabs
</button>
</div>
);
},
});Cross-user WebRTC data channels (realtimeEngine.connectPeer)
For ephemeral peer-to-peer messages between two different users without writing every frame to document storage, call realtimeEngine.connectPeer. Signaling (SDP offer/answer and ICE candidates) requires an active Supabase Realtime configuration on the host (getHostServices().getSignalingClient(), or explicit supabaseUrl and supabaseKey options permitted by capabilities.network.domains); once connected, payloads travel directly over an RTCDataChannel.
Declare network in manifest.capabilities before calling connectPeer or sse:
import { useEffect, useState } from 'react';
import { useBlockId, useOrbixUser } from '@orbixdocs/sdk';
import { realtimeEngine, type P2PDataChannel } from '@orbixdocs/sdk/realtime';
interface PingPayload {
sentAt: number;
}
export function PeerPing({ remoteUserId }: { remoteUserId: string }) {
const blockId = useBlockId();
const user = useOrbixUser();
const [latencyMs, setLatencyMs] = useState<number | null>(null);
const [channel, setChannel] = useState<P2PDataChannel<PingPayload> | null>(null);
useEffect(() => {
let active = true;
let opened: P2PDataChannel<PingPayload> | null = null;
realtimeEngine
.connectPeer<PingPayload>({
signalingChannel: `ping:${blockId}`,
peerId: user.id,
remotePeerId: remoteUserId,
blockId,
})
.then((dc) => {
if (!active) {
dc.close();
return;
}
opened = dc;
setChannel(dc);
dc.onData((msg) => {
setLatencyMs(Date.now() - msg.sentAt);
});
})
.catch(() => {
setChannel(null);
});
return () => {
active = false;
opened?.close();
};
}, [blockId, remoteUserId, user.id]);
return (
<div>
<button
type="button"
disabled={!channel?.connected}
onClick={() => channel?.send({ sentAt: Date.now() })}
>
Send P2P ping
</button>
{latencyMs !== null && <span> One-way delta: {latencyMs} ms</span>}
</div>
);
}Both peers call connectPeer with the same signalingChannel and swapped peerId / remotePeerId values. The lexicographically lower peerId initiates the WebRTC offer automatically.
Server-Sent Events and WebSockets
realtimeEngine.sse<T>(url, blockId?): Opens anEventSourceagainst an allowlisted domain inmanifest.capabilities.network.domainsand returns{ on(eventType, handler), onAny(handler), close(), status }.useOrbixWebSocket<TIn, TOut>(url, options?, capabilities?): Manages a WebSocket connection with bounded FIFO message buffering (maxMessages, default100) and exponential reconnect backoff (reconnectDelayMs,maxReconnectDelayMs,maxRetries).
WebSockets and SSE across execution runtimes
SDK React blocks run in the host realm where useOrbixWebSocket and realtimeEngine.sse connect directly once the target hostname is listed in manifest.capabilities.network.domains (and network.websocket is not false). Inside cross-site HTML and polyglot frames (rb-<hash>.orbixblocks.com), direct WebSocket, EventSource, and RTCPeerConnection constructors are disabled by CSP (connect-src blob: data:); HTML frames should poll through host-mediated fetch() instead.