Event streams all the way down
SSE is a really great idea. With a single request you can create a server driven stream of events. Using this for driving Datastar’s htmx like fragments plugin is a natural fit. The only problem is that SSE doesn’t support anything but the GET
method. This means that you can’t use SSE to send data to the server. This is a problem for htmx, because htmx uses the POST
method to send data to the server. So, what to do?
The Solution #
text/event-stream
MIME type is the underlying protocol for Server Sent Events. It is a simple protocol that is easy to implement. It is also a simple protocol to extend. So, we can extend it to support POST
,PUT
,PATCH
,DELETE
requests. The majority of the code is in how your read and buffer results from fetch API calls. The rest is just a matter of parsing the request and sending the appropriate response. The great part is the server side still just uses the same libraries or helpers that it would use for SSE.
This means every data fragment is an OOB in htmx terms.
This is easy to debug, easy to create, and still makes use of middlewares like compression. It’s just HTML fragments but wrapped in a protocol that allows for streaming and server driven events.