Realtime channels: broadcast and subscribe
Push live updates to browsers and apps over named channels, and test them from the Console.
Realtime lets your app push updates to everyone who is listening, instantly, with no polling. Typical uses are live order or driver tracking, chat messages, notifications, and a dashboard number that updates by itself.
It works with channels. A channel is just a name you choose, such as orders. A client subscribes to the channel, and whenever your backend broadcasts an event to it, every subscriber receives it.
Try it in the Console
- In your project's sidebar, choose Realtime Channels.
- Under Broadcast Event, set the Target Channel, an Event Name and a JSON Payload.
- Choose Broadcast to Channel.
- Watch the Live Channel Stream Terminal on the right: your event arrives there instantly. Choose Clear to empty it.
The page also shows ready-to-copy code for both sides.
Subscribe from a browser
Subscribers connect with Server-Sent Events, a long-lived web connection that works in any browser with no extra library:
const es = new EventSource("https://api.pgbhub.app/api/v1/realtime/stream?channel=orders&project=my-project");
es.addEventListener("order_dispatched", (e) => console.log(JSON.parse(e.data)));
With the TypeScript SDK:
const stop = pgb.realtime.subscribe("orders", (evt) => console.log(evt.event, evt.data));
// call stop() to unsubscribe
Broadcast from your server
curl -X POST "https://api.pgbhub.app/api/v1/realtime/channels/orders/broadcast?project=my-project" \
-H "Authorization: Bearer pgb_sec_..." -H "Content-Type: application/json" \
-d '{"event": "order_dispatched", "payload": {"order_id": 4821, "eta_min": 12}}'
Or await admin.realtime.broadcast("orders", { order_id: 4821 }, { event: "order_dispatched" }).
Who can publish
- A secret key from your server.
- A publishable key, but only together with a signed-in user's access token in the
X-PGB-User-Tokenheader. This lets a browser app publish as that user. - You, from the Console.
The sender shown to listeners (sender_id) is set by PGB from the credential, not from the request body, so a client cannot pretend to be someone else. A publishable key with no user token is refused.
Good to know
- Channels belong to your project. Two projects can both use a channel called
generalwithout ever seeing each other's events. - Subscribing needs your project identifier. Treat channel contents as visible to anyone who knows the channel name, so do not broadcast private data. Send an id or a "something changed" signal and let the app fetch the details through your normal, protected data calls.
- Realtime delivers events you broadcast. It does not stream changes from your database tables by itself. To broadcast when data changes, add a
realtimeeffect to an action or call broadcast from your function. - Delivery is to whoever is connected at that moment. A reconnecting client can resume from the last event it saw.