HTMX - Server Sent Events(SSE)



Server Sent Events are a way of sending data from a server to a web page, without requiring the page to refresh or make requests. These events are useful for creating real-time applications, such as chat, news feeds, or notifications. Using SSE, we can push DOM events continuously from our web server to the visitor's browser.

The event streaming approach opens a persistent connection to the server, sending data to the client when new information is available, eliminating the need for continuous polling. Server-sent events standardize how we stream data from the server to the client.

Ways to use SSE in Web Application

To use Server-Sent Events in a web application follow the below-mentioned procedure.

  • Add an <eventsource> element to the document. The src attribute of <eventsource> element should point to a URL that provides a persistent HTTP connection that sends a data stream containing the events.
  • URL points to a PHP, PERL, or any Python script that would take care of sending event data consistently.

Instance

Following is a sample HTMX code of a web application that would expect server time.

<div id="sse"
 hx-sse="connect:/cgi-bin/ticker.cgi"
 hx-trigger="sse:message"
 hx-swap="innerHTML">
   <div id="ticker">
 Waiting for updates...
   </div>
</div>

Server Side Script for SSE

A server side script should send a Content-type header specifying the type text/event-stream as follows.

print "Content-Type: text/event-stream\n\n";

After setting Content-Type, server-side script would send an Event: tag followed by the event name. The following code snippet would send Server-Time as an event name terminated by a new line character.

print "Event: server-time\n";

The final step is to send event data using the Data: tag which would be followed by an integer of string value terminated by a new line character as follows.

$time = localtime();
print "Data: $time\n";

Finally, the following is a complete ticker.cgi written in Perl

#!/usr/bin/perl
print "Content-Type: text/event-stream\n\n";
while(true){
 print "Event: server-time\n";
 $time = localtime();
 print "Data: $time\n";
 sleep(5);
}

Handle Server-Sent Events

Let us modify our web application to handle server-sent events. Following is the final example.

<div id="sse"
 hx-sse="connect:/cgi-bin/ticker.cgi"
 hx-trigger="sse:server-time"
 hx-target="#ticker"
 hx-swap="innerHTML">
    <div id="ticker" name="ticker">
 Waiting for updates...
    </div>
</div>
Advertisements