I am playing with KTor Server SSE (and HTMX). Anyo...
# ktor
a
I am playing with KTor Server SSE (and HTMX). Anyone have any info about how to handle re-connects? So far I am handling disconnects with catching the exception when sending events, and then sending a "update-all" event on first connect. But someone mentioned that with an id attribute I could get automatic replays and dedupe. Anyone know what is the right way to handle and what is supported now? ๐Ÿ™‚
m
Hey, I can say nothing about HTMX, but the server plugin SSE itself doesn't support automatic replays and dedupe, there is no reconnection support at the moment Maybe @Bruce Hamilton can say smth about htmx part?
a
Yeah, not absultely sure HTMX supports it either, but I do think it might be a browser thing? The most detailed info I have found about replay is here: https://eclipse-ee4j.github.io/jersey.github.io/documentation/2.29/sse.html#d0e11149:~:text=15.5.1.%C2%A0%20SseEventSource%20reconnect%20support
b
yeah, looks like you'd need some logic in the event handler in the client, and some custom implementation on the SSE endpoint to handle sessions to keep track of the last sent event
a
Isn't it implemented in the browser? I see something in the spec here also about headers to re-establish connection: https://html.spec.whatwg.org/multipage/server-sent-events.html#last-event-id
b
oh, I didn't know about that, curious to see if it works out of the box ๐Ÿ˜„
a
To my understanding it should be implemented in the EventSource interface in the browser. ๐Ÿ™‚ https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface I will try and check for the header to see if it's sent. At the very least I will know if it's a new connection or reconnect. ๐Ÿ™‚ Currently I just send a update all event on new connect. Like this: https://github.com/anderssv/kotlin-htmx/blob/main/src/main/kotlin/no/mikill/kotlin_htmx/Routes.kt#L123
( https://kotlin-htmx.fly.dev/demo/htmx/checkboxes is a live running implementation)
Bingo. It is sent. Not absolutely sure about the conditions yet, but seems it doesn't sent it if you publish any events without an ID.
kodee happy 2
Seems the logic goes something like: If received at least one event with an id, send the last one in Last-Event-ID in the header. ๐Ÿ™‚ Not handling replay, but issuing special event when re-connecting here: https://github.com/anderssv/kotlin-htmx/blob/main/src/main/kotlin/no/mikill/kotlin_htmx/Routes.kt#L122
Here's a blog article I wrote about using SSE with KTor. ๐Ÿ™‚ https://blog.f12.no/wp/2024/11/11/htmx-sse-easy-updates-of-html-state-with-no-javascript/
๐Ÿ”ฅ 2