| 1 | --- |
| 2 | title: "hx-ws" |
| 3 | description: "Enable bidirectional connections over WebSockets (WS)" |
| 4 | category: "Networking" |
| 5 | icon: "icon-[mdi--swap-horizontal]" |
| 6 | keywords: ["websockets", "ws", "real-time", "bidirectional", "socket"] |
| 7 | --- |
| 8 | |
| 9 | The WebSocket extension enables real-time, bidirectional communication with |
| 10 | [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications) |
| 11 | servers directly from HTML. It manages connections with automatic reconnection, |
| 12 | connection sharing, and seamless integration with htmx's swap and event model. |
| 13 | |
| 14 | ## Installing |
| 15 | |
| 16 | ```html |
| 17 | <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.min.js"></script> |
| 18 | <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/ext/hx-ws.js"></script> |
| 19 | ``` |
| 20 | |
| 21 | ## Usage |
| 22 | |
| 23 | Use these attributes to configure WebSocket behavior: |
| 24 | |
| 25 | | Attribute | Description | |
| 26 | |-----------|-------------| |
| 27 | | `hx-ws:connect="<url>"` | Establishes a WebSocket connection to the specified URL | |
| 28 | | `hx-ws:send` | Sends form data or `hx-vals` to the WebSocket on trigger | |
| 29 | | `hx-ws:send="<url>"` | Like `hx-ws:send` but creates its own connection to the URL | |
| 30 | |
| 31 | **JSX-Compatible Variants:** For frameworks that don't support colons in attribute names, use hyphen variants: `hx-ws-connect` and `hx-ws-send`. |
| 32 | |
| 33 | ### Basic Example |
| 34 | |
| 35 | ```html |
| 36 | <div hx-ws:connect="/chatroom" hx-target="#messages" hx-swap="beforeend"> |
| 37 | <div id="messages"></div> |
| 38 | <form hx-ws:send> |
| 39 | <input name="message" placeholder="Type a message..."> |
| 40 | <button type="submit">Send</button> |
| 41 | </form> |
| 42 | </div> |
| 43 | ``` |
| 44 | |
| 45 | This example: |
| 46 | 1. Establishes a WebSocket connection to `/chatroom` when the page loads |
| 47 | 2. Appends incoming HTML messages to `#messages` |
| 48 | 3. Sends form data as JSON when the form is submitted |
| 49 | |
| 50 | ## URL Normalization |
| 51 | |
| 52 | WebSocket URLs are automatically normalized: |
| 53 | |
| 54 | | Input | Output (on HTTPS page) | |
| 55 | |-------|------------------------| |
| 56 | | `/ws/chat` | `wss://example.com/ws/chat` | |
| 57 | | `ws://localhost:8080/ws` | `ws://localhost:8080/ws` | |
| 58 | | `https://api.example.com/ws` | `wss://api.example.com/ws` | |
| 59 | | `//cdn.example.com/ws` | `wss://cdn.example.com/ws` | |
| 60 | |
| 61 | This means you can use simple relative paths in most cases, and the extension will construct the correct WebSocket URL. |
| 62 | |
| 63 | ## Receiving Messages |
| 64 | |
| 65 | ### JSON Message Format |
| 66 | |
| 67 | Messages from the server should be JSON objects with a `content` field: |
| 68 | |
| 69 | ```json |
| 70 | { |
| 71 | "content": "<div class='notification'>New message!</div>", |
| 72 | "target": "#notifications", |
| 73 | "swap": "beforeend", |
| 74 | "HX-Request-ID": "abc-123" |
| 75 | } |
| 76 | ``` |
| 77 | |
| 78 | | Field | Default | Description | |
| 79 | |-------|---------|-------------| |
| 80 | | `content` | | HTML content to swap into the target | |
| 81 | | `target` | Element's `hx-target` | CSS selector for target element | |
| 82 | | `swap` | Element's `hx-swap` | Swap strategy (innerHTML, beforeend, etc.) | |
| 83 | | `HX-Request-ID` | | Matches response to original request | |
| 84 | |
| 85 | **Minimal example:** |
| 86 | ```json |
| 87 | {"content": "<div>Hello World</div>"} |
| 88 | ``` |
| 89 | |
| 90 | ### Data-Only Messages |
| 91 | |
| 92 | JSON messages without a `content` field are not swapped. Use `htmx:before:ws:message` to handle them: |
| 93 | |
| 94 | ```javascript |
| 95 | document.addEventListener('htmx:before:ws:message', (e) => { |
| 96 | if (e.detail.message.json?.type === 'notification') { |
| 97 | showNotification(e.detail.message.json.text); |
| 98 | } |
| 99 | }); |
| 100 | ``` |
| 101 | |
| 102 | ### Raw HTML Messages |
| 103 | |
| 104 | If the server sends a plain string (not JSON), it's treated as raw HTML: |
| 105 | |
| 106 | ``` |
| 107 | <div class="alert">Server restarting in 5 minutes</div> |
| 108 | ``` |
| 109 | |
| 110 | If the connection element has an `hx-target`, the HTML is swapped into that target. Without an `hx-target`, `swap:none` is used - but [`<hx-partial>`](/docs#partials-hx-partial) elements in the message can still target their own destinations: |
| 111 | |
| 112 | ``` |
| 113 | <hx-partial hx-target="#alerts" hx-swap="beforeend"><div class="alert">New alert</div></hx-partial> |
| 114 | ``` |
| 115 | |
| 116 | ### Request-Response Matching |
| 117 | |
| 118 | Each sent message includes a unique `HX-Request-ID` header. When the server echoes it back in the response, the content is routed to the element that sent the request (not the connection element): |
| 119 | |
| 120 | ```html |
| 121 | <form hx-ws:send hx-target="#result"> |
| 122 | <input name="query" value="hello"> |
| 123 | <button>Search</button> |
| 124 | </form> |
| 125 | <div id="result"></div> |
| 126 | ``` |
| 127 | |
| 128 | The form sends `{"headers": {"HX-Request-ID": "abc-123", ...}, "body": {"query": "hello"}}`. The server responds with: |
| 129 | |
| 130 | ```json |
| 131 | {"content": "<p>Results for 'hello'</p>", "HX-Request-ID": "abc-123"} |
| 132 | ``` |
| 133 | |
| 134 | Because `HX-Request-ID` matches, the content is swapped into `#result` (the form's `hx-target`), not the connection element. |
| 135 | |
| 136 | ## Sending Messages |
| 137 | |
| 138 | When an element with `hx-ws:send` is triggered, the extension sends a structured JSON message with separate `headers` and `body`: |
| 139 | |
| 140 | ```json |
| 141 | { |
| 142 | "headers": { |
| 143 | "HX-Request": "true", |
| 144 | "HX-Request-ID": "550e8400-e29b-41d4-a716-446655440000", |
| 145 | "HX-Source": "form#chat-form", |
| 146 | "HX-Target": "div#messages", |
| 147 | "HX-Current-URL": "https://example.com/chat" |
| 148 | }, |
| 149 | "body": { |
| 150 | "message": "Hello!", |
| 151 | "tags": ["urgent", "public"] |
| 152 | } |
| 153 | } |
| 154 | ``` |
| 155 | |
| 156 | **Headers** (from htmx core, same as HTTP requests): |
| 157 | |
| 158 | | Header | Description | |
| 159 | |--------|-------------| |
| 160 | | `HX-Request` | Always `"true"` | |
| 161 | | `HX-Request-ID` | Unique ID for request/response matching | |
| 162 | | `HX-Source` | Source element identifier (`tag#id` format) | |
| 163 | | `HX-Target` | Target element identifier (only if `hx-target` is set) | |
| 164 | | `HX-Current-URL` | Current page URL | |
| 165 | |
| 166 | **Body** contains form data and `hx-vals`. Multi-value fields (like checkboxes or multi-selects) are preserved as arrays. |
| 167 | |
| 168 | ### Forms |
| 169 | |
| 170 | ```html |
| 171 | <form hx-ws:send> |
| 172 | <input name="username"> |
| 173 | <input name="message"> |
| 174 | <button type="submit">Send</button> |
| 175 | </form> |
| 176 | ``` |
| 177 | |
| 178 | ### Buttons with hx-vals |
| 179 | |
| 180 | ```html |
| 181 | <button hx-ws:send hx-vals='{"action": "increment"}'>+1</button> |
| 182 | ``` |
| 183 | |
| 184 | ### Modifying Messages Before Send |
| 185 | |
| 186 | Use the `htmx:before:ws:request` event to modify or cancel messages: |
| 187 | |
| 188 | ```javascript |
| 189 | document.addEventListener('htmx:before:ws:request', (e) => { |
| 190 | e.detail.headers['Authorization'] = 'Bearer ' + getToken(); |
| 191 | |
| 192 | // Or cancel the send |
| 193 | if (!isValid(e.detail.body)) { |
| 194 | e.preventDefault(); |
| 195 | } |
| 196 | }); |
| 197 | ``` |
| 198 | |
| 199 | ## Configuration |
| 200 | |
| 201 | Configure the extension globally via `htmx.config.ws` or per-element via `hx-config` ([HCON](/docs#hx-config) or JSON): |
| 202 | |
| 203 | ```javascript |
| 204 | htmx.config.ws = { |
| 205 | reconnect: true, // Enable auto-reconnect (default: true) |
| 206 | reconnectDelay: 500, // Initial reconnect delay in ms (default: 500) |
| 207 | reconnectMaxDelay: 60000, // Maximum reconnect delay in ms (default: 60000) |
| 208 | reconnectMaxAttempts: Infinity,// Maximum reconnect attempts (default: Infinity) |
| 209 | reconnectJitter: 0.3, // Jitter factor 0-1 for randomizing delays (default: 0.3) |
| 210 | pauseOnBackground: true, // Pause connection when tab is backgrounded (default: true) |
| 211 | pendingRequestTTL: 30000 // TTL for pending requests in ms (default: 30000) |
| 212 | }; |
| 213 | ``` |
| 214 | |
| 215 | ```html |
| 216 | <!-- Per-element override --> |
| 217 | <div hx-ws:connect="/ws" hx-config="ws.reconnectDelay:1s ws.reconnectMaxAttempts:5"> |
| 218 | ``` |
| 219 | |
| 220 | Delay values accept time strings: `"500ms"`, `"1s"`, `"2m"`, or raw milliseconds. |
| 221 | |
| 222 | Per-element config is read from the element that creates the connection and stored on the connection object for its lifetime. |
| 223 | |
| 224 | ### Reconnection Strategy |
| 225 | |
| 226 | The extension uses exponential backoff with optional jitter: |
| 227 | |
| 228 | - **Base formula**: `delay = min(reconnectDelay × 2^(attempts-1), reconnectMaxDelay)` |
| 229 | - **Jitter**: Adds ±30% randomization to avoid thundering herd |
| 230 | - **Reset**: Attempts counter resets to 0 on successful connection |
| 231 | |
| 232 | Example reconnection delays with defaults: |
| 233 | - Attempt 1: ~500ms |
| 234 | - Attempt 2: ~1000ms |
| 235 | - Attempt 3: ~2000ms |
| 236 | - Attempt 4: ~4000ms |
| 237 | - Attempt 5+: ~60000ms (capped) |
| 238 | |
| 239 | ### Connection Triggers |
| 240 | |
| 241 | By default, connections are established immediately when the element is processed: |
| 242 | |
| 243 | ```html |
| 244 | <!-- Connects immediately when element appears (default) --> |
| 245 | <div hx-ws:connect="/ws"> |
| 246 | |
| 247 | <!-- Explicit load trigger - same behavior as no trigger --> |
| 248 | <div hx-ws:connect="/ws" hx-trigger="load"> |
| 249 | |
| 250 | <!-- Deferred connection - only connects when button is clicked --> |
| 251 | <div hx-ws:connect="/ws" hx-trigger="click from:#connect-btn"> |
| 252 | ``` |
| 253 | |
| 254 | Use `hx-trigger` when you want to **delay** connection establishment (e.g., wait for user action). |
| 255 | |
| 256 | All standard `hx-trigger` modifiers are supported (`delay`, `throttle`, `once`, etc.). |
| 257 | |
| 258 | ## Events |
| 259 | |
| 260 | ### Connection Lifecycle |
| 261 | |
| 262 | | Event | Cancelable | Detail | Description | |
| 263 | |-------|------------|--------|-------------| |
| 264 | | `htmx:before:ws:connection` | ✅ | `{connection}` | Before connection attempt (initial or reconnect) | |
| 265 | | `htmx:after:ws:connection` | ❌ | `{connection}` | After successful connection | |
| 266 | | `htmx:ws:close` | ❌ | `{connection, reason, code}` | When connection closes (see below) | |
| 267 | | `htmx:ws:error` | ❌ | `{url, error}` | On connection or send error | |
| 268 | |
| 269 | The `htmx:ws:close` detail includes: |
| 270 | - `connection` - the connection object |
| 271 | - `reason` - why the connection closed: `"closed"` (WebSocket close event), `"removed"` (element removed from DOM), or `"cancelled"` (connection cancelled via `htmx:before:ws:connection` event) |
| 272 | - `code` - the WebSocket close code (e.g. `1000`), or `null` when removed via DOM cleanup |
| 273 | |
| 274 | The `connection` detail is the actual internal connection object, which includes: |
| 275 | - `attempt`: `0` for initial connection, `> 0` for reconnections |
| 276 | - `url`: the WebSocket URL |
| 277 | - `config`: the resolved configuration for this connection |
| 278 | - `socket`: the WebSocket instance (available on `after` events; `null` before initial connection) |
| 279 | - `cancelled`: set to `true` in `before` events to cancel the connection |
| 280 | - `pendingRequests`: Map of in-flight request/response pairs |
| 281 | |
| 282 | ### Request Events |
| 283 | |
| 284 | | Event | Cancelable | Detail | Description | |
| 285 | |-------|------------|--------|-------------| |
| 286 | | `htmx:before:ws:request` | ✅ | `{headers, body}` | Before sending (headers and body are modifiable) | |
| 287 | | `htmx:after:ws:request` | ❌ | `{headers, body}` | After message sent | |
| 288 | |
| 289 | ### Message Events |
| 290 | |
| 291 | | Event | Cancelable | Detail | Description | |
| 292 | |-------|------------|--------|-------------| |
| 293 | | `htmx:before:ws:message` | ✅ | `{message: {text, json, cancelled}}` | Before processing any received message | |
| 294 | | `htmx:after:ws:message` | ❌ | `{message: {text, json}}` | After processing any received message | |
| 295 | |
| 296 | `message.text` is the raw string. `message.json` is the parsed JSON object (or `null` for non-JSON). Set `message.cancelled = true` in the `before` event to prevent processing. |
| 297 | |
| 298 | ### Event Examples |
| 299 | |
| 300 | **Cancel Connection Based on Condition:** |
| 301 | ```javascript |
| 302 | document.addEventListener('htmx:before:ws:connection', (e) => { |
| 303 | if (e.detail.connection.attempt > 10) { |
| 304 | e.detail.connection.cancelled = true; // Stop reconnecting |
| 305 | } |
| 306 | }); |
| 307 | ``` |
| 308 | |
| 309 | **Handle Data-Only Messages:** |
| 310 | ```javascript |
| 311 | document.addEventListener('htmx:before:ws:message', (e) => { |
| 312 | if (e.detail.message.json?.type === 'audio') { |
| 313 | playAudioNotification(e.detail.message.json.url); |
| 314 | } |
| 315 | }); |
| 316 | ``` |
| 317 | |
| 318 | **Log All WebSocket Activity:** |
| 319 | ```javascript |
| 320 | document.addEventListener('htmx:after:ws:connection', (e) => { |
| 321 | console.log('Connected to', e.detail.connection.url); |
| 322 | }); |
| 323 | document.addEventListener('htmx:ws:close', (e) => { |
| 324 | console.log('Disconnected from', e.detail.connection.url, 'reason:', e.detail.reason); |
| 325 | }); |
| 326 | ``` |
| 327 | |
| 328 | ## Connection Management |
| 329 | |
| 330 | ### Connection Sharing |
| 331 | |
| 332 | Multiple elements pointing to the same WebSocket URL share a single connection: |
| 333 | |
| 334 | ```html |
| 335 | <div hx-ws:connect="/notifications" id="notif-1"> |
| 336 | <!-- Uses connection to /notifications --> |
| 337 | </div> |
| 338 | <div hx-ws:connect="/notifications" id="notif-2"> |
| 339 | <!-- Shares the same connection --> |
| 340 | </div> |
| 341 | ``` |
| 342 | |
| 343 | When all elements using a connection are removed from the DOM, the connection is automatically closed. |
| 344 | |
| 345 | ### Element Cleanup |
| 346 | |
| 347 | When elements are removed (e.g., via htmx swap), the extension checks if any other element in the DOM still references the same WebSocket URL. If not, the connection is closed. |
| 348 | |
| 349 | This happens automatically through htmx's element cleanup lifecycle. |
| 350 | |
| 351 | ## HTML Swapping |
| 352 | |
| 353 | When a JSON message with a `content` field arrives, the extension uses htmx's swap API, which provides: |
| 354 | |
| 355 | - All swap styles (`innerHTML`, `outerHTML`, `beforebegin`, `afterend`, `beforeend`, `afterbegin`, `delete`, `none`) |
| 356 | - Preserved elements (`hx-preserve`) |
| 357 | - Auto-focus handling |
| 358 | - Scroll handling |
| 359 | - Proper cleanup of removed elements |
| 360 | - `htmx.process()` called on newly inserted content |
| 361 | |
| 362 | ### Target Resolution |
| 363 | |
| 364 | Target is determined in this order: |
| 365 | 1. `target` field in the message |
| 366 | 2. `hx-target` attribute on the element that sent the request (if `HX-Request-ID` matches) |
| 367 | 3. `hx-target` attribute on the connection element |
| 368 | 4. The connection element itself |
| 369 | |
| 370 | ### Swap Strategy |
| 371 | |
| 372 | Swap strategy is determined in this order: |
| 373 | 1. `swap` field in the message |
| 374 | 2. `hx-swap` attribute on the connection element (or the element that sent the request) |
| 375 | 3. `htmx.config.defaultSwap` (default: `innerHTML`) |
| 376 | |
| 377 | ## Examples |
| 378 | |
| 379 | ### Live Chat |
| 380 | |
| 381 | ```html |
| 382 | <div hx-ws:connect="/chat"> |
| 383 | <div id="messages" hx-target="this" hx-swap="beforeend"></div> |
| 384 | <form hx-ws:send> |
| 385 | <input name="message" placeholder="Message..." autocomplete="off"> |
| 386 | <button type="submit">Send</button> |
| 387 | </form> |
| 388 | </div> |
| 389 | ``` |
| 390 | |
| 391 | Server sends: |
| 392 | ```json |
| 393 | {"content": "<div class='message'><b>User:</b> Hello!</div>"} |
| 394 | ``` |
| 395 | |
| 396 | ### Real-Time Notifications |
| 397 | |
| 398 | ```html |
| 399 | <div hx-ws:connect="/notifications" |
| 400 | hx-target="#notification-list" |
| 401 | hx-swap="afterbegin"> |
| 402 | <div id="notification-list"></div> |
| 403 | </div> |
| 404 | ``` |
| 405 | |
| 406 | ### Interactive Counter |
| 407 | |
| 408 | ```html |
| 409 | <div hx-ws:connect="/counter"> |
| 410 | <div id="count" hx-target="this">0</div> |
| 411 | <button hx-ws:send hx-vals='{"action":"increment"}'>+</button> |
| 412 | <button hx-ws:send hx-vals='{"action":"decrement"}'>-</button> |
| 413 | </div> |
| 414 | ``` |
| 415 | |
| 416 | ### Multiple Widgets Sharing Connection |
| 417 | |
| 418 | ```html |
| 419 | <div hx-ws:connect="/dashboard"> |
| 420 | <div id="cpu-usage">--</div> |
| 421 | <div id="memory-usage">--</div> |
| 422 | <div id="disk-usage">--</div> |
| 423 | </div> |
| 424 | ``` |
| 425 | |
| 426 | Server sends targeted updates: |
| 427 | ```json |
| 428 | {"content": "<span>45%</span>", "target": "#cpu-usage"} |
| 429 | {"content": "<span>2.3 GB</span>", "target": "#memory-usage"} |
| 430 | ``` |
| 431 | |
| 432 | ## Upgrading from htmx 2.x |
| 433 | |
| 434 | ### Attribute Changes |
| 435 | |
| 436 | | Old (htmx 2.x) | New (htmx 4.x) | Notes | |
| 437 | |----------------|----------------|-------| |
| 438 | | `ws-connect="<url>"` | `hx-ws:connect="<url>"` | Or `hx-ws-connect` for JSX | |
| 439 | | `ws-send` | `hx-ws:send` | Or `hx-ws-send` for JSX | |
| 440 | |
| 441 | The old `ws-connect` and `ws-send` attributes still work but emit a deprecation warning. |
| 442 | |
| 443 | ### Event Changes |
| 444 | |
| 445 | | Old Event | New Event | Notes | |
| 446 | |-----------|-----------|-------| |
| 447 | | `htmx:wsConnecting` | (none) | Removed | |
| 448 | | `htmx:wsOpen` | `htmx:after:ws:connection` | Different detail structure | |
| 449 | | `htmx:wsClose` | `htmx:ws:close` | Now includes `code` and `reason` | |
| 450 | | `htmx:wsError` | `htmx:ws:error` | Similar | |
| 451 | | `htmx:wsBeforeMessage` | `htmx:before:ws:message` | Different detail structure | |
| 452 | | `htmx:wsAfterMessage` | `htmx:after:ws:message` | Different detail structure | |
| 453 | | `htmx:wsConfigSend` | `htmx:before:ws:request` | Modify `e.detail.headers` and `e.detail.body` | |
| 454 | | `htmx:wsBeforeSend` | `htmx:before:ws:request` | Combined into one event | |
| 455 | | `htmx:wsAfterSend` | `htmx:after:ws:request` | Similar | |
| 456 | |
| 457 | ### Configuration Changes |
| 458 | |
| 459 | | Old | New | |
| 460 | |-----|-----| |
| 461 | | `htmx.config.wsReconnectDelay` | `htmx.config.ws.reconnectDelay` | |
| 462 | | `createWebSocket` option | Not supported (use events) | |
| 463 | | `wsBinaryType` option | Not supported | |
| 464 | |
| 465 | Note: earlier htmx 4.0 alpha builds used `htmx.config.websockets`. This has been renamed to `htmx.config.ws` for consistency with the extension name and attribute prefix. |
| 466 | |
| 467 | ### Message Format Changes |
| 468 | |
| 469 | **Send payload** is now a structured `{headers, body}` JSON object. Headers contain `HX-Request`, `HX-Request-ID`, `HX-Source`, `HX-Target`, `HX-Current-URL`. Body contains form data and `hx-vals`. |
| 470 | |
| 471 | **Receive format** now expects JSON with `content`, `target`, `swap` fields instead of raw HTML or `hx-swap-oob`. Messages with a `content` field are auto-swapped; messages without `content` are data-only (handle via events). Use `HX-Request-ID` (instead of the old `request_id`) for request-response matching. |
| 472 | |
| 473 | ### Socket Wrapper Removed |
| 474 | |
| 475 | The `socketWrapper` object is no longer exposed in events. Use the standard WebSocket events and the extension's event system instead. |