Reference sections
Reference › WebSocket routes
You create a WebSocket route with a .socket.js (or .socket.ts) file. e.g., updates.socket.js serves WebSocket connections at /updates.socket.
A socket route responds only at its own path, so updates.socket.js doesn’t respond at /updates.socket/anything/. For a family of sockets, use a parameter: [room].socket.js responds at /lobby.socket and /kitchen.socket. The wildcard parameter ([any]) in a socket route’s name matches one segment and preserves the .socket suffix, so rooms/[any].socket.js responds at /rooms/lobby.socket and not at /rooms/lobby/.
Only socket routes, page sockets, and Kitten’s development socket respond to WebSocket upgrades. Kitten responds with 404 to any other upgrade and closes the socket. A socket route passes on every request that isn’t an upgrade, and a socket route in a 🔒 folder requires sign-in for upgrades.
A WebSocket message, to a page or to a socket route, may have at most 1 MB. Kitten closes a socket that sends a larger one with code 1009. A live page whose socket Kitten closes with code 1009 reconnects, which reloads it.
Unlike other routes, WebSocket routes keep their extension. Kitten also doesn’t apply URL normalisation to WebSocket clients like it does for all other routes (it doesn’t add a trailing slash to URLs that are missing one).
Your route exports a handler function that Kitten calls once per connection, passing it the following parameter object: { request, socket }:
request: the HTTP request that opened the connection.socket: the ws WebSocket for the connection, with two extra methods:all(message): sends the message to every client connected to the route, including itself.broadcast(message): sends the message to every other client connected to the route.
Both methods return the number of connections they sent the message to. If you pass them a promise, they return a promise of that number.
To open a WebSocket connection from your server to another server, use the kitten.WebSocket class, which is the WebSocket class from ws.
In the following example, the echo.socket.js route responds to messages by adding them to a list on the page:
export default function ({ request, socket }) {
console.info('Echo socket: new client connection.', request.session)
socket.addEventListener('message', event => {
const message = JSON.parse(event.data).message
socket.send(kitten.html`
<ul id='echos' swap-target='beforeend'>
<li><strong>“${message}”</strong> received on server.</li>
</ul>
`)
})
}
You don’t manually author socket routes for live pages. Kitten automatically creates a page socket at <page path>default.socket and routes its messages to your event handlers. (For a wildcard page, the page socket’s path includes the path that the page matched.)
A page socket attaches only to a page that its own page route rendered, for the same session. Kitten treats any other page id as one that doesn’t exist: it sends the page the reload command and closes the socket. A page socket that opens without a session cookie (e.g., in a browser that blocks cookies) is closed without the reload command, so live pages need cookies. Kitten responds with 404 to a GET request to a page socket’s path that isn’t a WebSocket upgrade.
A plain string passed to the page’s send() method, a component’s sendToPage() method, or the this.everyone.send() or this.everyoneElse.send() method is escaped and sent as text, and Kitten logs a warning that mentions the page. Send kitten.html for markup.
The this.everyone.send() and this.everyoneElse.send() methods, and manually-authored socket routes, don’t automatically add the hx-swap-oob attribute for you, so you must add a morph or swap-target (syntactic sugar for hx-swap-oob) attribute manually. Furthermore, if your page connects to a manually-authored socket route, you must manually add the htmx-idiomorph attribute to its <page> tag for the morph attribute to work.
Unlike the page’s send() method, a manually-authored socket route doesn’t escape plain strings. It sends them exactly as they are. So, if htmx swaps your message into the page, build it with kitten.html, not a plain template string. The socket route then sends the HTML that kitten.html renders, with any values you interpolated into it escaped.
If a template contains a promise or an async component, kitten.html returns a promise. You can send that promise without awaiting it, using any of these methods:
the page’s
send()methodthis.everyone.send()andthis.everyoneElse.send()a socket route’s
send(),all(), orbroadcast()methods
Kitten waits for the promise to resolve, then sends the result to everyone who’s connected at that point. (If the promise rejects, Kitten logs a warning and doesn’t send the message.)
The this.everyone.send(), this.everyoneElse.send(), all(), and broadcast() methods return the number of connections they sent the message to. When you pass them a promise, they return a promise of that number instead (and 0 if the promise rejects).
Note that a message sent this way can arrive after a message you send directly after it. To keep your messages in order, await the template before you send it.
See the htmx, the htmx WebSocket extension, and socket routes and two-way WebSocket communication tutorials.
A morph sets each element that it updates to what the server rendered. So it resets the text that a person has typed into an <input> or a <textarea>, and closes an open <details> element.
To leave such an element as it is, give it an id and a preserve attribute in every render. (The preserve attribute is syntactic sugar for htmx’s hx-preserve attribute, as the connect attribute is for ws-send.) A morph then changes neither the element nor anything inside it, so changes that the server renders inside it don’t show either (on a component’s root element, this means that the update() method changes nothing).
Without an
idattribute, thepreserveattribute has no effect. (A component’s root element always has one, as Kitten adds the component’sidto it.)When you send a
connectform, Kitten removes thehx-preserveattribute from its fields in your browser, so the server’s next render sets them.
For example, in this shopping list, what you type into the New item field stays as it is when you press Count, and the field is empty again once you add the item:
/**
A shopping list whose New item field preserves what you type while the page updates.
Each time you press Count, the page renders again and we morph it into the page in your browser. A morph sets every field to what the server rendered, so text that you have typed into a field and not sent yet would be lost. The New item field has `preserve` (which we render as `hx-preserve`), so what you type into it stays as it is when the page updates. (Note that a preserved element must have an `id`, as a morph only preserves elements that have one.)
When you send the form, we remove `hx-preserve` from its fields in your browser, so the page that the server renders next sets them. Here, that empties the field, ready for your next item.
*/
export default class ShoppingListPage extends kitten.Page {
count = 0
items = []
html () {
return kitten.html`
<main>
<h1>Shopping list</h1>
<button name='count' connect>Count: ${this.count}</button>
<ul>${this.items.map(item => kitten.html`<li>${item}</li>`)}</ul>
<form name='add' connect>
<label for='new-item'>New item</label>
<input id='new-item' type='text' name='item' preserve>
<button type='submit'>Add</button>
</form>
</main>
`
}
onCount () {
this.count++
this.update()
}
onAdd ({ item }) {
this.items.push(item)
this.update()
}
}
This is the preserve example in the Kitten source.