Realtime
ZendBX Realtime delivers live database changes over WebSocket. Subscribe to any table and receive INSERT, UPDATE, and DELETE events in real time.
How It Works
PostgreSQL LISTEN/NOTIFY triggers fire on table changes. The ZendBX realtime listener receives these events and broadcasts them to connected WebSocket clients that have subscribed to the relevant table.
Subscribing
typescript
import { createClient } from '@zendbx/sdk';
const db = createClient({ apiUrl, anonKey, projectSlug });
// Subscribe to all changes on a table
const sub = db.realtime
.from('messages')
.on('*', (payload) => {
console.log('Event:', payload.event); // INSERT | UPDATE | DELETE
console.log('New:', payload.new);
console.log('Old:', payload.old);
})
.subscribe();
// Clean up
sub.unsubscribe();Specific Events
typescript
// Listen only to inserts
const sub = db.realtime
.from('orders')
.on('INSERT', (payload) => {
console.log('New order:', payload.new);
})
.subscribe();
// Listen only to updates
const sub2 = db.realtime
.from('orders')
.on('UPDATE', (payload) => {
console.log('Order updated:', payload.new.status);
})
.subscribe();React Example
typescript
'use client';
import { useEffect, useState } from 'react';
import { db } from '@/lib/zendbx';
export default function LiveFeed() {
const [messages, setMessages] = useState([]);
useEffect(() => {
const sub = db.realtime
.from('messages')
.on('INSERT', (payload) => {
setMessages((prev) => [payload.new, ...prev]);
})
.subscribe();
return () => sub.unsubscribe();
}, []);
return (
<ul>
{messages.map((m) => (
<li key={m.id}>{m.text}</li>
))}
</ul>
);
}💡Always call
sub.unsubscribe() when the component unmounts to avoid memory leaks. In React, return it from the useEffect cleanup function.Payload Structure
typescript
{
event: 'INSERT' | 'UPDATE' | 'DELETE',
table: 'messages',
schema: 'my_project',
new: { id: '...', text: 'Hello', ... }, // new row (null for DELETE)
old: { id: '...', text: 'Hi', ... } // old row (null for INSERT)
}Authentication
The WebSocket connection sends the user's JWT token as a URL parameter during the initial handshake. Server-side RLS policies apply to realtime events — users only receive events for rows they're allowed to see.
Auto-Reconnection
The SDK automatically reconnects on network interruptions with exponential backoff. Subscriptions are re-established after reconnect.

