htmx: Server Sent Event (SSE) Extension
6 days ago
- #real-time
- #htmx
- #Server Sent Events
- Server Sent Events (SSE) extension connects to an EventSource directly from HTML, managing connections and swapping contents into htmx webpages in real-time.
- SSE is a lightweight alternative to WebSockets, working over existing HTTP connections, making it easy to use through proxies and firewalls, but it's uni-directional.
- For bi-directional communication, WebSockets should be considered instead of SSE.
- SSE replaces the experimental hx-sse attribute from previous htmx versions, with migration guidelines provided.
- Key attributes for configuring SSE connections include sse-connect, sse-swap, hx-trigger, and sse-close.
- Installation options include CDN, direct download, npm, and bundlers like Webpack or Rollup.
- SSE messages consist of an event name and data packet, with specific listening requirements for named and unnamed events.
- Multiple events can be listened to from a single EventSource, either in the same element or child elements.
- SSE supports triggering HTTP callbacks via hx-trigger attributes and includes automatic reconnection logic with exponential backoff.
- Migration from hx-sse to the new SSE extension involves attribute changes and includes event listeners for connection and message handling.