Server Sent Events with Fresh
Hi! I am trying to use Server Sent Events (SSE) with fresh. I understand I should have an island that holds the connection to the server but how can I broadcast the notifications to other islands?
9 Replies
it seems like it is actually not supported on Deno (server-side) https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#browser_compatibility
Using server-sent events - Web APIs | MDN
Developing a web application that uses server-sent events is straightforward. You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to websockets in part of handling incoming events. This is a one-way connection, so you can't send events from a client to a server.
My question was about client-side with Fresh's islands.
On server side you don't need any particular support, as it is plain HTTP. You just have to stream your events with
content-type: text/event-stream
Client side would use an EventSource to subscribe to the stream, and POST to the server to publish messages. When you say other islands, do you mean other islands in the same browser tab, or other instances of the Deploy isolate, or other instances of the same deploy isolate in different browser tab?
If same tab, just us browser BroadcastChannel. If different isolates, use Deno BroadcastChannel on the server.
The following api code uses SSE + BroadcastChannel as a WRTC signalling service to connect two players over a WebRTC-Datachannel.
https://github.com/nhrones/FreshDiceRTC/tree/master/routes/api
Thank you @ndh3193 ! I would never have thought about using
BroadcastChannel
, I will definitely try it.
My use case was different islands in the same tab.there's no standard for a server-side api
There's nothing super special about the SSE api. It looks like skye made a polyfill at https://deno.land/x/eventsource
yep it's just a ReadableStream
i made a stream-like abstraction for it
worth noting this allows deno to read a SSE from another server, like the Web API, rather create and send its own