Realtime

Subscribe to database changes over WebSocket. Get live INSERT, UPDATE, and DELETE events with presence tracking and client-to-client broadcast.

WebSocket Connection

const ws = new WebSocket(
  "wss://api.zmesh.in/projects/{project_id}/realtime/ws?token=YOUR_JWT"
);

ws.onopen = () => {
  console.log("Connected to zMesh Realtime");

  // Subscribe to table changes
  ws.send(JSON.stringify({
    type: "subscribe",
    channel: "table:users"
  }));

  // Subscribe to specific events
  ws.send(JSON.stringify({
    type: "subscribe",
    channel: "table:orders:INSERT"
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);

  if (msg.type === "realtime") {
    console.log(msg.table, msg.event, msg.data);
    // "users", "INSERT", { id: "...", name: "Rahul", ... }
  }
};

Message Types

TypeDirectionDescription
subscribeClient → ServerSubscribe to a channel
unsubscribeClient → ServerUnsubscribe from a channel
broadcastClient → ServerSend to all channel subscribers
presenceClient → ServerTrack user presence state
pingClient → ServerHeartbeat (returns pong)
connectedServer → ClientConnection established
subscribedServer → ClientSubscription confirmed
realtimeServer → ClientDatabase change event

Channel Formats

// All changes on a table
"table:users"

// Specific event type only
"table:users:INSERT"
"table:orders:UPDATE"
"table:sessions:DELETE"

// Custom broadcast channels
"room:lobby"
"chat:room-123"

Presence Tracking

// Track presence
ws.send(JSON.stringify({
  type: "presence",
  state: { status: "online", cursor: { x: 100, y: 200 } }
}));

// Get presence info (REST)
GET /projects/{project_id}/realtime/presence

Broadcast

// Client-to-client messaging
ws.send(JSON.stringify({
  type: "broadcast",
  channel: "room:lobby",
  payload: { user: "Rahul", message: "Hello everyone!" }
}));

Enable / Disable on Tables

Use the REST API or Dashboard to enable realtime triggers on specific tables:

// Enable realtime on a table
POST /projects/{project_id}/realtime/enable
{ "table_name": "orders", "events": ["INSERT", "UPDATE", "DELETE"] }

// Disable realtime
POST /projects/{project_id}/realtime/disable
{ "table_name": "orders" }

// Get realtime status
GET /projects/{project_id}/realtime/status

// List available tables
GET /projects/{project_id}/realtime/tables

Connection History

GET /projects/{project_id}/realtime/connections

View recent WebSocket connection and disconnection logs.