HTMX - WebSockets



WebSockets are defined as a two-way communication between the servers and clients, which means both the parties, communicate and exchange data at the same time. This protocol defines a full-duplex communication from the ground up. Web sockets take a step forward in bringing desktop-rich functionalities to web browsers. It represents an evolution, which was awaited for a long time in client/server web technology.

To know more in detail about the WebSockets please go through our WebSockets Tutorial.

WebSockets with HTMX

Here's a brief overview of some key points.

  • HTMX simplifies WebSocket usage by allowing you to establish connections and handle events directly in your HTML using attributes like hx-ws and hx-trigger.
  • HTMX provides several WebSocket-specific events like ws:open, ws:close, and ws:error that you can use to manage the connection lifecycle.
  • WebSockets with HTMX are great for building real-time features like chat applications, live dashboards, and collaborative tools.
  • Sending messages to the server can be done with hx-ws="send" on elements that trigger the send action.
  • Receiving messages is handled by setting up elements with hx-trigger="ws:message", which will update when a message is received.
  • Security and performance considerations are crucial when implementing WebSocket-based features.

Establish WebSocket Connection

To establish a WebSocket connection, you typically use hx-ws="connect:{url}" on a container element.

Step 1: We need to include the HTMX library in the <head> section.

<script src="https://cdnjs.cloudflare.com/ajax/libs/htmx/1.9.6/htmx.min.js"></script>

Step 2: Main container for our chat application has the WebSocket connection attribute.

<div id="chat-container" hx-ws="connect:wss://echo.websocket.org">

Step 3: Establishes a WebSocket connection to the echo.websocket.org service, which simply echoes back any message it receives. Inside the container, we have a chat box to display messages and a form to send messages.

<div id="chat-box"></div>
<form hx-ws="send" hx-target="#chat-box" hx-swap="beforeend">
   <input type="text" name="message" placeholder="Type a message...">
   <button type="submit">Send</button>
</form>

Step 4: The form has hx-ws="send" to send the message via WebSocket when submitted. The hx-target and hx-swap attributes ensure that the response (echoed message) is appended to the chat box.
We use some JavaScript to handle WebSocket events.

  • htmx:wsOpen: Triggered when the WebSocket connection is established.
  • htmx:wsClose: Triggered when the WebSocket connection is closed.
  • htmx:wsAfterMessage: Triggered after a message is received and processed. We use this to scroll the chat box to the bottom after each message.
Advertisements