Documentation menu
Getting Started
Core Concepts
Control
Interactivity
Pushing Data
HTMX Extensions
Miscellaneous
Configuration
Server-Sent Events (SSE)
Use SSE to push updates from a server to the browser over an open HTTP connection. The bundled htmgo extension uses EventSource to receive messages and applies out-of-band swaps from their HTML payloads.
The chat example uses SSE to deliver new messages to other participants.
Connect to the stream
Add sse-connect to an element and point it to a GET endpoint that streams text/event-stream responses. To update the page, send HTML elements with hx-swap-oob and IDs matching their targets.
1func MessageFeed(streamURL string) *h.Element {
2 return h.Div(
3 h.Attribute("sse-connect", streamURL),
4 h.Div(h.Id("messages")),
5 )
6}Handle connection errors and closure
Attach handlers to the connecting element. h.HxOnSseError receives the native EventSource error event in event.detail.event. The browser may reconnect after an error. An explicit event: close frame ends the stream and can include a reason in event.detail.event.data when handled by h.HxOnSseClose.
1func MessageFeed(streamURL string) *h.Element {
2 return h.Div(
3 h.Attribute("sse-connect", streamURL),
4 h.HxOnSseError(
5 js.EvalJs("console.error('SSE connection error', event.detail.event);"),
6 ),
7 h.HxOnSseClose(
8 js.EvalJs("console.info('SSE connection closed', event.detail.event.data);"),
9 ),
10 h.Div(h.Id("messages")),
11 )
12}Use h.HxOnSseConnecting and h.HxOnSseOpen for connection setup. Use h.HxBeforeSseMessage and h.HxAfterSseMessage to react before or after the browser applies an update.
Send a message
Clients send messages through ordinary HTTP requests, such as a form POST. Clear the input after that request succeeds so incoming messages leave your draft intact.
1func MessageForm(sendMessage h.PartialFunc) *h.Element {
2 return h.Form(
3 h.PostPartial(sendMessage),
4 h.NoSwap(),
5 h.HxAfterRequest(
6 js.EvalJs("if (event.detail.ctx.response?.ok) self.reset();"),
7 ),
8 h.Input("text", h.Name("message"), h.Required()),
9 h.Button(h.Type("submit"), h.Text("Send")),
10 )
11}