Chat with HTMX, WebSockets and Hono
Last week, I wrote about tweaking htmx to display instant messages. A week into using HTMX, I needed more. I wanted a better way to stream HTML from the server, using JSX components instead of plain HTML strings for better code usability.
? Quick reminder: if you find this useful, please give it a thumbs up! Your support helps me create more content.
Tools I Used:
- HTMX
- HTMX Websockets Extension
- Hono for the backend
- Websockets - client-side
The idea is simple. My Conversation component is wrapped in a div with hx-ext="ws", which connects to my backend when rendered.
export const Conversation = (props: { messages: Message[] }) => ( <div hx-ext="ws" ws-connect="/chatroom-ws"> <div id="conversation"> {props.messages.reverse().map((message) => ( <div> <UserMessage message={message} /> <AssistantMessage message={message} /> </div> ))} </div> <InputMessageForm /> </div> );
Next important thing is the InputMessageForm. Just add ws-send to the form, and it will send a message where the key is the textarea’s ID (messageInput) with its value.
export const InputMessageForm = () => ( <form id="query-submit-form" ws-send className="relative"> <textarea id="messageInput" name="userMessage" placeholder="Type your message here..." rows={4} ></textarea> <button type="submit">Send</button> </form> );
Websockets - Server
Here’s the full code block for the Hono server. Some console logs for opening and closing connection. onMessage is where the magic happens.
get( '/chatroom-ws', upgradeWebSocket((c) => { return { onOpen: () => { console.log('WS Connection open'); }, onClose: () => { console.log('WS Connection closed'); }, onMessage: async (event, ws) => { const { userMessage } = JSON.parse(event.data.toString()); console.log('Got user message', userMessage); const inputArea = await c.html( <div id="query-submit-form"> <InputMessageForm /> </div>, ); ws.send(await inputArea.text()); const htmlUser = await c.html( <div id="conversation" hx-swap-oob="beforeend"> <UserMessage message={{ id: v4(), // some random ids used here for placeholder query: userMessage, completion: '', conversationId: v4(), toolsResponse: null, createdAt: new Date(), updatedAt: new Date(), }} /> </div>, ); ws.send(await htmlUser.text()); const response = await talk(userMessage); const htmlAgent = await c.html( <div id="conversation" hx-swap-oob="beforeend"> <AssistantMessage message={response} /> </div>, ); ws.send(await htmlAgent.text()); }, }; }), );
So the flow is:
- Receive the query
- Send back empty just to make it clean. There is no hx-swap-oob specified so its True by default. That means that it will find the element with id=query-submit-form and swap it.
- Send back the component with the user message. Here hx-swap-oob is specified to beforeend which simply means that it will be added to existing messages.
- talk → here comes your logic. I’m talking to AI assistant so making some external API calls.
- Send back the component with assistant answer. The same as step 3 but the component is different.
Problems I found
Sending response back was a bit problematic since docs are hmm… not that easy to understand I think. There is even an issue created to fix this: Improve documentation for websocket extension. That helped me a lot!
So the most important thing is:
You need to send back string, that parses to html that has the same id as the thing you want to swap!
So the problem nr. 1
I accidentally sent back something like this:
JSON.stringify('<div id="someid">test 123</div>') // '"<div id=\\"someid\\">test 123</div>"'
This is wrong. Note the ID and escape characters! Don’t stringify the string here.
The problem nr. 2
You might think you can return something and it will get swapped where you want. Not exactly. The first div is just information for HTMX on what to do. At least I understand it this way ?.
I’m returning html like this:
<div id="conversation" hx-swap-oob="beforeend"> <AssistantMessage message={response} /> </div>
Only is appended inside the existing
on the client side.End result
https://assets.super.so/c0fc84d8-fb32-4194-8758-4be657666aab/videos/c814dcd2-b9e9-4bb2-b8db-2ed9cd7819b7/lucy-chat-example.mov
? Does this post help you? Please spam the like button! Your support is awesome. Thanks!
Want to Know More?
Stay tuned for more insights and tutorials! Visit My Blog ?
The above is the detailed content of Chat with HTMX, WebSockets and Hono. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
