Stream server-sent events
Stream server-sent events
This tutorial builds a server-sent events (SSE) endpoint on the JavaScript lane
and consumes it from a browser page with EventSource. You will stream a
sequence of events over one long-lived HTTP response and see them arrive
incrementally in the client. It takes about fifteen minutes.
Afterburner streams response bodies natively, so
SSE works without special configuration. Long-lived duplex sockets are not the
model; SSE plus POST covers the push cases. See
Streaming and realtime for the full
picture.
Prerequisites
- The
hyjalCLI installed and logged in. - Node.js installed locally, for the JS lane build.
- A Project. This tutorial uses
acmewith anapiResource.
1. Write the SSE handler
The JavaScript lane contract is a fetch handler:
export default { fetch(request) }. Return a Response whose body is a
ReadableStream and whose Content-Type is text/event-stream. Each SSE
message is a data: line terminated by a blank line.
This handler emits five events, one per second, then closes the stream. Keep
each streamed run within the Resource’s run limit
(runLimitSecs, default 30 seconds).
2. Configure the Resource
Set the api Resource to the JS lane and mark it public so the browser can
reach the endpoint.
3. Test locally with hyjal dev
Run the local dev server. It serves your component under the same wasi:http contract as production, with hot rebuild and request logging in the terminal.
In another terminal, stream the endpoint with curl. The -N flag disables
buffering so events print as they arrive.
The one-second gap between lines confirms the response is streaming, not
buffered and flushed at the end. See hyjal dev for more
on the local server.
4. Consume from a browser page
Add a static web Resource that serves an HTML page. The page opens an
EventSource against the api endpoint and appends each event to the DOM.
Add the front-end Resource to the manifest and mount the API behind it so the page and endpoint share an origin. Same-origin dispatch removes the need for any CORS configuration.
With the mount in place, point EventSource at the same-origin path instead
of the absolute URL:
5. Deploy and verify
Deploy both Resources.
Open https://web--acme.hyjal.cloud. The list fills in one row per second as
events arrive over the streamed response.
What you built
- A JavaScript-lane SSE endpoint that streams events over one HTTP response.
- A browser page that consumes the stream with
EventSource. - A same-origin
mountswiring that removes CORS configuration from the client.
Next steps
- Streaming and realtime: the streaming
model and when to use SSE plus
POST. - Full-stack apps:
mountsand in-process dispatch between Resources. - JavaScript and TypeScript: the JS lane and supported frameworks.