HTML over WebSockets: real-time SPAs with barely any JavaScript
Article URL: https://en.andros.dev/blog/ef4968f5/html-over-websockets-real-time-spas-with-barely-any-javascript/ Comments URL: https://news.ycombinator.com/item?id=49275335 Points: 240 # Comments: 173
When building a Single-page Application (SPA), developers often use a JavaScript framework for rendering the view, an API serving JSON data, and separate codebases for the frontend and backend that must communicate through contracts. This approach, while accepted, is not the only way to create a SPA. An alternative method involves using "HTML over WebSockets," which sends already-built HTML from the server to the client without any preprocessing.
This way, rendering logic remains in the backend, using a single language and no need for contracts or an API. The approach is known as hypermedia or HTML over the wire and involves sending HTML instead of JSON, allowing for real-time and bidirectional communication with minimal JavaScript on the client-side. Chris McCord, creator of Phoenix, demonstrated this concept at ElixirConf 2019 by building a Twitter clone with LiveView, proving that one could stay in the backend while achieving good performance.
Since then, this technique has gained popularity, inspiring other developers to create HTML-over-WebSockets implementations in various languages. However, the choice between HTML over WebSockets, Server-Sent Events (SSE), or htmx over HTTP depends on the specific requirements of a project. If real-time, bidirectional communication is needed (like chat, collaboration, or games), WebSockets is the best choice.
If only server-to-client communication is necessary (such as notifications, live feeds, or dashboards), SSE offers a simpler and more cost-effective solution. On the other hand, if the application primarily involves request-and-response interactions, htmx over HTTP may be sufficient. Regardless of the chosen method, the key takeaway is to focus on the architecture and avoid relying on trendy frameworks or patterns.
Written by urgent.news from Hacker News Best's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.