```
Use `hx-trigger` when you want to **delay** connection establishment (e.g., wait for user action).
All standard `hx-trigger` modifiers are supported (`delay`, `throttle`, `once`, etc.).
## Events
### Connection Lifecycle
| Event | Cancelable | Detail | Description |
|-------|------------|--------|-------------|
| `htmx:before:ws:connection` | ✅ | `{connection}` | Before connection attempt (initial or reconnect) |
| `htmx:after:ws:connection` | ❌ | `{connection}` | After successful connection |
| `htmx:ws:close` | ❌ | `{connection, reason, code}` | When connection closes (see below) |
| `htmx:ws:error` | ❌ | `{url, error}` | On connection or send error |
The `htmx:ws:close` detail includes:
- `connection` - the connection object
- `reason` - why the connection closed: `"closed"` (WebSocket close event), `"removed"` (element removed from DOM), or `"cancelled"` (connection cancelled via `htmx:before:ws:connection` event)
- `code` - the WebSocket close code (e.g. `1000`), or `null` when removed via DOM cleanup
The `connection` detail is the actual internal connection object, which includes:
- `attempt`: `0` for initial connection, `> 0` for reconnections
- `url`: the WebSocket URL
- `config`: the resolved configuration for this connection
- `socket`: the WebSocket instance (available on `after` events; `null` before initial connection)
- `cancelled`: set to `true` in `before` events to cancel the connection
- `pendingRequests`: Map of in-flight request/response pairs
### Request Events
| Event | Cancelable | Detail | Description |
|-------|------------|--------|-------------|
| `htmx:before:ws:request` | ✅ | `{headers, body}` | Before sending (headers and body are modifiable) |
| `htmx:after:ws:request` | ❌ | `{headers, body}` | After message sent |
### Message Events
| Event | Cancelable | Detail | Description |
|-------|------------|--------|-------------|
| `htmx:before:ws:message` | ✅ | `{message: {text, json, cancelled}}` | Before processing any received message |
| `htmx:after:ws:message` | ❌ | `{message: {text, json}}` | After processing any received message |
`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.
### Event Examples
**Cancel Connection Based on Condition:**
```javascript
document.addEventListener('htmx:before:ws:connection', (e) => {
if (e.detail.connection.attempt > 10) {
e.detail.connection.cancelled = true; // Stop reconnecting
}
});
```
**Handle Data-Only Messages:**
```javascript
document.addEventListener('htmx:before:ws:message', (e) => {
if (e.detail.message.json?.type === 'audio') {
playAudioNotification(e.detail.message.json.url);
}
});
```
**Log All WebSocket Activity:**
```javascript
document.addEventListener('htmx:after:ws:connection', (e) => {
console.log('Connected to', e.detail.connection.url);
});
document.addEventListener('htmx:ws:close', (e) => {
console.log('Disconnected from', e.detail.connection.url, 'reason:', e.detail.reason);
});
```
## Connection Management
### Connection Sharing
Multiple elements pointing to the same WebSocket URL share a single connection:
```html
```
When all elements using a connection are removed from the DOM, the connection is automatically closed.
### Element Cleanup
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.
This happens automatically through htmx's element cleanup lifecycle.
## HTML Swapping
When a JSON message with a `content` field arrives, the extension uses htmx's swap API, which provides:
- All swap styles (`innerHTML`, `outerHTML`, `beforebegin`, `afterend`, `beforeend`, `afterbegin`, `delete`, `none`)
- Preserved elements (`hx-preserve`)
- Auto-focus handling
- Scroll handling
- Proper cleanup of removed elements
- `htmx.process()` called on newly inserted content
### Target Resolution
Target is determined in this order:
1. `target` field in the message
2. `hx-target` attribute on the element that sent the request (if `HX-Request-ID` matches)
3. `hx-target` attribute on the connection element
4. The connection element itself
### Swap Strategy
Swap strategy is determined in this order:
1. `swap` field in the message
2. `hx-swap` attribute on the connection element (or the element that sent the request)
3. `htmx.config.defaultSwap` (default: `innerHTML`)
## Examples
### Live Chat
```html
```
Server sends:
```json
{"content": "
User: Hello!
"}
```
### Real-Time Notifications
```html
```
### Interactive Counter
```html
```
### Multiple Widgets Sharing Connection
```html
```
Server sends targeted updates:
```json
{"content": "
45%", "target": "#cpu-usage"}
{"content": "
2.3 GB", "target": "#memory-usage"}
```
## Upgrading from htmx 2.x
### Attribute Changes
| Old (htmx 2.x) | New (htmx 4.x) | Notes |
|----------------|----------------|-------|
| `ws-connect="
"` | `hx-ws:connect=""` | Or `hx-ws-connect` for JSX |
| `ws-send` | `hx-ws:send` | Or `hx-ws-send` for JSX |
The old `ws-connect` and `ws-send` attributes still work but emit a deprecation warning.
### Event Changes
| Old Event | New Event | Notes |
|-----------|-----------|-------|
| `htmx:wsConnecting` | (none) | Removed |
| `htmx:wsOpen` | `htmx:after:ws:connection` | Different detail structure |
| `htmx:wsClose` | `htmx:ws:close` | Now includes `code` and `reason` |
| `htmx:wsError` | `htmx:ws:error` | Similar |
| `htmx:wsBeforeMessage` | `htmx:before:ws:message` | Different detail structure |
| `htmx:wsAfterMessage` | `htmx:after:ws:message` | Different detail structure |
| `htmx:wsConfigSend` | `htmx:before:ws:request` | Modify `e.detail.headers` and `e.detail.body` |
| `htmx:wsBeforeSend` | `htmx:before:ws:request` | Combined into one event |
| `htmx:wsAfterSend` | `htmx:after:ws:request` | Similar |
### Configuration Changes
| Old | New |
|-----|-----|
| `htmx.config.wsReconnectDelay` | `htmx.config.ws.reconnectDelay` |
| `createWebSocket` option | Not supported (use events) |
| `wsBinaryType` option | Not supported |
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.
### Message Format Changes
**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`.
**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.
### Socket Wrapper Removed
The `socketWrapper` object is no longer exposed in events. Use the standard WebSocket events and the extension's event system instead.