Server-Sent Events

A demo countdown using Server-Sent Events, with htmx and typed-htmx-go.

When you click the button below, that fetches a new element that uses the sse extension to start stream a countdown.

<button
	{ hx.Get("/examples/templ/sse/countdown/")... }
	{ hx.Target(htmx.TargetThis)... }
	{ hx.Swap(swap.OuterHTML)... }
>
	Start Countdown
</button>

The new elements uses the sse.Connect attribute to connect to a server-sent event streaming countdown.

<div
	{ hx.Ext(sse.Extension)... }
	{ sse.Connect(hx, "/examples/templ/sse/countdown/feed/")... }
	{ sse.Swap(hx, shared.ResetEvent)... }
	{ hx.Swap(swap.OuterHTML)... }
>
	<div
		{ sse.Swap(hx, shared.CountdownEvent)... }
		{ hx.Swap(swap.InnerHTML)... }
	></div>
</div>

Each second, the server sends a countdown message that updates the innerHTML of the div.

templ Message(msg string) {
	<p>{ msg }</p>
}

After the countdown is complete, the server will send a ResetEvent, that closes removes the sse connection by replacing the sse.Connect element with the initial button using hx.Swap(swap.OuterHTML).

Demo