Primate
Guides Responses

Stream events with SSE

Use Server-Sent Events (SSE) to push updates to the browser over a long-lived HTTP response (text/event-stream). The sse helper handles headers and the connection lifecycle.

This assumes you have installed and loaded @primate/html in your config file.

1) Client — subscribe to events

Create an HTML component that subscribes to SSE via EventSource.

HTMLcomponents/index.html
<script>
  new EventSource("/sse").addEventListener("passed", event => {
    const seconds = Number(event.data);
    console.log(`${seconds} seconds since connection opened`);
  });
</script>

2) Serve a page (route choice is flexible)

You can serve this page from any route. We'll use / for brevity.

TypeScriptroutes/index.ts
import response from "primate/response";
import route from "primate/route";

route.get(() => response.view("index.html"));

3) Server — SSE endpoint

Expose /sse and periodically send events.

TypeScriptroutes/sse.ts
import response from "primate/response";
import route from "primate/route";

route.get(() => {
  let timer: ReturnType<typeof setInterval>;
  const start = Date.now();

  return response.sse({
    open(source) {
      timer = setInterval(() => {
        source.send("passed", Math.floor((Date.now() - start) / 1000));
      }, 5000); // every 5s
    },
    close() {
      clearInterval(timer);
    },
  });
});