Server-Sent Events (SSE)

SSE provides unidirectional server-to-client push over HTTP. Simpler than WebSocket — no custom protocol, works through proxies.

Enabling SSE

In your .radiant file, you can enable SSE for a collection. The runtime will automatically broadcast CRUD events to connected clients.

collection todos {
  realtime: {
    sse: ["create", "update", "delete"] // true = all events
  }
  fields: {
    title: text
  }
}

When enabled, the runtime mounts GET /api/sse as the Server-Sent Events endpoint.

Connecting

const es = new EventSource("http://localhost:3000/api/sse?channel=todos");

es.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data);
};

On connect, the server sends:

event: connected
data: {"id":"conn-uuid","channels":["todos"],"authenticated":false}

Subscribing to Channels

Pass channel names via query parameters:

# Single channel
GET /api/sse?channel=todos

# Multiple channels
GET /api/sse?channel=todos&channel=posts

# Or comma-separated
GET /api/sse?channels=todos,posts

Receiving Change Events

When a CRUD operation occurs on a collection you've subscribed to, you receive an event containing the action data:

data: {"event":"todos:created","data":{"id":"abc-123","title":"Buy groceries"}}

SSE Manager API

You can programmatically broadcast SSE from anywhere in your TypeScript code:

import { RadiantSSE } from "@codesordinatestudio/radiant-bun";

// Broadcast to a channel
RadiantSSE.broadcastToChannel("todos", {
  event: "todos:created",
  data: { id: "abc-123", title: "New todo" }
});

// Broadcast to all connections
RadiantSSE.broadcastAll({ type: "announcement", data: "Hello everyone" });

// Send to a specific connection
RadiantSSE.sendTo(connectionId, { event: "custom", data: "private message" });

// Stats
const stats = RadiantSSE.getStats();
// { connections: 8, channels: { todos: 5, posts: 3 } }