450 points · by czue · 5y ago · 274 comments
I was writing web apps when rendering templated HTML views on your server was standard, and you had controller endpoints that returned HTML content, or things like Rails "Unobtrusive Javascript" where you had code like:
$(‘#user-list’).html(“<%= j render(‘index’, users: @users) %>”)
As an automatic callback to some action.Whether or not you love or hate this model of development is irrelevant, because if at some point you need to render on a client other than a browser -- you have to start from the beginning and write an API now.
IE, so that your Android/iOS app in Java/Swift or whatnot, can ask your backend for data and render it using the tools available on that platform.
When we turned apps into pure API's and just exchanged data with them, it opened up the ability to be platform-agnostic.
I guess I don't understand why someone would choose to build an app that sends HTML over the wire instead of JSON/XML/whatever, that any client can render. All it means is that you have to write this functionality later when you want it, in addition to now having this HTML stuff.
Second, this is something of a false dichotomy: if you have a website, you need to have HTML somewhere. One approach is to use an SPA but that increases the cost somewhat significantly and absent a significant engineering effort will reduce performance and reliability because you are moving functionality out of a high-performance data center where you control everything onto the users' devices where you have to work with whatever browser and extensions/ad blockers they have installed.
An alternative approach is to render HTML on your servers — quite possibly using the same JSON API as the source — and then progressively enhance it with the functionality which makes sense to do on the edge. This gives you a hefty performance win for the initial page-load times, helps with things like search engines, and ensures that your users get at least the basic experience when something goes wrong with client side JavaScript (network errors, browser compatibility issues, ad blockers, etc.) rather than nothing working at all.
Yes, Testify! Also, I'd like to mention, so many of these upsold apps end up being a wrapper around the normal web view. I've seen this being advertised/proposed as a plus, as well "No need for your customers to learn a new interface, we specifically engineer your app experience to be just like the web experience". It's interesting to see heads nodding in reply to this.
I can think over time I'll have endpoints like this:
POST https://foo.com/bar-section/baz-button
No? Haven't quite thought about it deeply but I can imagine logic mixed with UI bits in the backend.I have no doubt that this style of front-end management is going to be a game changer in the next few years. Of course full-on SPA frameworks will still have their place. But if you aren’t writing the next Google Maps clone, maybe you don’t need all that. It’s made me love web dev again after hating the complexity explosion of recent years.
The endpoints that return endpoints are not API endpoints, they are UI endpoints like `/index.html` or `/login` or `/Results.aspx?id=3984272`. Now you can have `/login/email` or `/login/google` and switch between them like <https://htmx.org/examples/tabs-hateoas/>.
As for the machine-consumed API, you have quite a few options. e.g.: The server that serves these resources may serve JSON to the same URLs through content negotiation, or the API may be separate, or you can have a generic API that is consumed by mobile app, desktop app and HTML-producing server (as opposed to JS app delivered by static file server or framework SSR).
The UI runs on the server, using REST to change client state over a stateless protocol similarly to how a React app may use Redux.
For example, if you have a search page that provides management of contacts + active search & click to load functionality, it might look like this:
GET /contacts - get a list of contacts + search & click-to-load functionality
POST /contacts - create new
GET /contacts/:id - get the details for the contact
PATCH /contacts/:id - update the contact
PUT /contacts/:id/archived - archive the contact
DELETE /contacts/:id - remove the contact
All pretty reasonable and all can reuse the same few templates and sub-templates for rendering responses.I suspect 'template include directives, except with some client smarts' may be a good (approximate) model to use to initially get a mental feel for how stuff like htmx plays out in practice.
What they generally had in common is that they're content-heavy (i.e. solidly in what the web was designed for), might not require authentication, and most importantly aren't something most of the users wanted to use all of the time. If you are trying to get the hours for a tourist destination or even a restaurant, look at public information, etc. the time needed to login to the app store, authenticate to approve the purchase, wait for a large file to download, open the app and complete any mandatory enrollment, wait for it to retrieve content, etc. was often orders of magnitude slower than using the website. Restaurants and bars are a great example of this: if it's your hangout and they have something like integrated ordering, maybe a trivia night or something like that, the app can be useful. For most people, however, a webpage with the contact info and a menu with Apple/Google/Stripe buttons to pay is going to be better than an app they use a couple of times a year.
The other key thing to understand is that this is a question of priorities and budgets. It wasn't that there is no possibility of doing anything useful for these organizations in a mobile app but rather than the cost wasn't worthwhile for the incremental benefit to the users, especially when you considered the opportunity cost of not spending that much money on something else, especially since most of the cool things you could do in an app could also be done on the web with very similar quality but with the difference that you only had to build one version rather than 2+ and the web version required much less ongoing maintenance.
1) No need for 3.7GB of node_modules to crank out a simple site
2) Single solution, easier to bring on junior developers and reason about application logic
3) Caching much easier, too many people think they need real-time push when NRT-polling + caching is far easier and more performant
Broadly speaking it's often a case of YAGNI. The JS ecosystem really does still suck for its complexity, I remember that every time I ramp up a new developer onto a React project. It's smoothed out with tooling but the litany of JSON configuration files and the mess created by hot-reload + proxying + microservices etc etc. Often just YAGNI.
People today don't remember the VB6 IDE days where you could slap a button on a Form, write a line of code for a MessageBox, and smash that play button with zero effort. JS development is often about working your way through a tangled spider-web of helper utilities and config files and JS modules at which point when it finally works you're afraid to rev anything.
a bit focus of htmx, alpinejs (and htmx's sister project, https://hyperscript.org) is putting the logic on the element, so you can see exactly what a button, etc. does just by looking at it, and without trawling through ten files of indirection
i am trying to popularize the term Locality of Behavior to describe this design goal:
Obviously I have no idea what your app is, I have found very frequently it is not reasonable to have blobs of similar sizes (especially if text content waits for some front end framework to download/initialize).
I think people approach it with prejudice (ew, Javascript!) and never properly learn it.
There are projects where react would be overkill but many benefit from the clear separation of the front end.
Also configuring a react project is easier than many other projects I've seen in my career. People just love getting internet points by constantly talking about left-pad, node_modules size, config files etc. I personally know how crazy managing maven or gradle (.gradle folder hell) or nuget or composer or pip (venv or virtualenv...) or [name of your favorite package manager] can get, so I'm thankful for the great community that work on the problems with the npm.
Unfortunely it is an option I can only dictacte on personal projects.
2) “Junior-centered” app has to be simple as a “ToDo list example”, all the time. It's not possible for the real apps - they constantly evolve, and to keep their code readable and clean you need skilled developers, not the other way around.
Another case in point: is your dev team going to support PSP devices[0]?
[0] https://shkspr.mobi/blog/2021/01/the-unreasonable-effectiven...
The answer lies in the "if" there. The speed and lack of complexity developing server-side with no API is unparalleled to doing client -> api -> backend. Not to mention, you aren't tying yourself into several different JS technologies (Which GraphQL or REST lib? Which view framework? What testing frameworks? And what's the whole backend stack? etc. etc.) I can only speak for LiveView but the whole top-down experience is in Elixir with sprinkles of vanilla JS (the community is big into Tailwind and AlpineJS as well, but not exclusively).
I have real world experience of dev'ing API-first only to have the company nix any plans to open up the API. Adding new features is always a slog as we have to think about if the business logic needs to be on the client, the server, or both... not to mentioning have to update about 18 different places the name of a new field you're adding.
The company I work for actual has a LiveView widget that is embedded on their client's apps. I can't speak very well to it since I only just started working there and don't actually start until next week, haha.
But ya, I'll also echo the whole idea that a lot of companies don't need mobile apps. I'm certainly one of those people who uses the browser on my phone whenever I can.
- simplicity: e.g. something like active search can be implemented with a few attributes: https://htmx.org/examples/active-search/
- flexibility: e.g. because of the uniform interface, versioning is much less of an issue
- power: e.g. deep linking is trivial
Additionally, there is increasing awareness[1] that Application APIs and Data APIs have different needs and "shapes", and, once you have split them up, reconsidering using hypermedia for your application API[2] is a reasonable thing to do
Is it really that much more work? Much of the time the big difference is just be replacing
return render(my_template, my_data)
with return to_json(my_data)https://github.com/LibraryOfCongress/concordia/blob/main/con...
That handles a few things like pagination for list views, calling get_absolute_url() on objects in the template context which have that method defined, and running all URLs through request.build_absolute_uri().
That said, many projects don't have or need mobile apps, and many more can probably get away with a web-first mobile app.
For those apps this stack can vastly simplify and streamline development
> That said, many projects don't have or need mobile apps, and many more can probably get away with a web-first mobile app.
To me this is like building a house that can never be expanded, instead of starting with an open-ended design. > For those apps this stack can vastly simplify and streamline development
I guess this is an opinion/subjective?I am very open-minded and experimental. I love trying new things.
I've tried these technologies (HTMX, it's precursor Intercooler.js, Turbolinks + Hotwire, LiveView, etc) and for me they are less productive than the ways I know how to build API-first, JavaScript web apps.
Have nothing against them, just genuinely having a hard time seeing the appeal.
I've tried these technologies ... and for me they are less productive than the ways I know how to build API-first, JavaScript web apps
I think I feel the same way you do, except the other way around. I genuinely can't understand how you build apps productively with a separate client/server model.How do you do form validations? How about authentication and authorization? What about a consistent domain model? Is there one copy of it on the server and one on the client? Or does your client just treat everything as dumb data and make network requests for every question of business logic? What about data consistency throughout the interface—when you update e.g. Document(id=45) with new data, how does that update get propagated to every other place in the app? Does that involve a client-side identity-map? Or are you manually trying to send updated data to other places with callbacks/whatever? etc. for ever and ever.
Every time I try to build an app where the frontend and backend are split into a separate client and API, it ends up adding so many more considerations and so much more complexity than the traditional model. Mostly because now everything that just required a database query or method call before now also requires a network request, but also because data consistency in a long-running app is so hard to get right.
Or alternatively it's a good application of YAGNI.
There's always a difficult balance between that as a principle and "do work upfront as it will take you longer to do later down the line"
Everyone makes this decision based on client budget, time constraints and a host of other factors. My clients tend to prefer to save money in the short term. That's not uncommon and it's a rational position to take for many.
Been doing this for decades and this has cropped up so few times I can't actually think of any.
Your clients might not be my clients. Your projects differ from mine. Don't generalise from your own experience. There's a lot more websites than there are apps.
Even starting from scratch, it can be very productive to keep all your HTML in one place- eg Django templates- and use HTMX and a sprinkling of JS to provide client-side interaction. You can jump straight into laying your app out without building the whole thing up as platform-agnostic APIs first. When you need API endpoints you can start adding them based on the context objects you're providing your Django templates, since all the information is in there anyway. There's real benefits to putting all your presentation and most of the logic on the server.
And keep in mind that many web apps will never ever need to also be a native app.
(I think this is inversion of control, someone can correct me if I'm wrong)
https://www.youtube.com/watch?v=XhNv1ikZNLs&list=PLqj39LCvnO...
What you've discovered is a general property of systems that you want to keep your entropy low for as long as possible, and defer the final boost in entropy until the last possible minute. This keeps your options open. It also means publishing low entropy APIs and boosting in the client. In your case, you've correctly noted that it allows you to support different clients more easily.
There are 3 reasons to pay the price to boost entropy on the server: to intentionally make it harder to consume your API, to protect a proprietary boosting function, and because you didn't realize it was bad design.
I'm glad we have middle-way options where we can progressively add dynamic functionality to rich-server, lower entropy applications and make an intentional decision whether to add a rich-client if the need arises.
You could refactor your code to share mostly everything . I have no idea how this templates system work though so maybe you need a different one.
so the API returns an array of users object as a json the html side of things would have a render function that has as input the same array of user objects. What you will probably lose versus complex frameworks is magic stuff like 2 way data bindings but from my experience those always caused issue, I prefered the old react way of doing things, it was more "functional style" and less magic under the hood and I could(and used) JS and not a special template language with special keywords to render stuff.
Amway my point is yu can reuse the API code for the html render stuff too.
That's not true generally since many mobile apps are simply wrappers around a WebView. Rails Turbolinks basically has mobile shims that allows you to deploy to all platforms. Sure, if you can't use a Web View on your mobile app (idk, for performance reasons) that's something else. But that's not the rule.
Everything that is old is new again...
This way, if you only need the logic for another platform, you can just consume it directly. Perhaps you'll have an additional job to write the HTTP endpoints around it directly, but that's a quite simple job.
Take Rails Hotwire for example. It's easy to write, easy to add JS when you need it, easy to make mobile apps since they've already done the work. It's live on Basecamp and Hey.com apps, it works very nicely. Hey is easily the snappiest email client I've ever used.
Being platform specific makes it easier to have a higher quality and integration on that specific platform.
You fetch data from the API and render it with JavaScript.
React, Vue, Svelte, Angular, Alpine, pick whatever.
Not sending HTML over server endpoints, or using templated views like ERB/EJS/EEX/etc doesn't mean you inherently have a worse quality app.
If you do this in something like Next.js with "getServerSideProps()", it's functionally equivalent.
React even went so far as to make "Server Components":
https://reactjs.org/blog/2020/12/21/data-fetching-with-react...
The main thing is is that there is still a substantial demand for tools that let you mostly avoid writing lots of JavaScript, whether on the server or the client.
Not everything on the web is a full featured interactive application, this is exactly what they're talking about.
def get_user_data(user_id: int) -> Dict (JSON-looking data):
...
def render_user_view(user_id: int) -> HTML:
user_data = get_user_data(user_id)
render_template("user_detail_view.html", context=user_data)
If you need the user data in a JSON API, nothing prevents you from exposing `get_user_data` as a JSON endpoint. You can also use WebViews in a mobile app.People tend to overestimate the "interactivity" needs of their apps and underestimate what they can achieve by just swapping HTML. HTMX also lets you swap "Out of Band" [0]. This makes it easy to model more complex interactions (like "reactions"), for example, updating a counter somewhere else in the app when a form is submitted. Reactive frameworks can also become a Rube Goldberg machine if an app is not properly designed from the beginning. Then you start fighting rendering loops, build dependencies, components' side effects, etc.
Personally speaking, HTML-driven apps are not just about easy vs. hard development, it's also about your users [1]. Maybe a big React app runs fine on 8 CPU cores and 32 GB of RAM, but very often, your users just want to read some content, maybe submit a few forms, and leave. They may not want to download 2 MB of JS so that the page can render boxes with text, even more if your browser can already do that if you give it some HTML.
[0] https://htmx.org/attributes/hx-swap-oob/ [1] https://shkspr.mobi/blog/2021/01/the-unreasonable-effectiven...
All that said, trying to push everything server-side if you've been working in a heavy client takes some getting used to. In my real life job I've seen feature flags shipped as an API so the client queries whether a feature flag is enabled - this is something that always struck me as silly, the server serving the front end already knows if the feature flag is enabled. While that might be justifiable in some cases, it is definitely not so much in the on-prem-only product I worked on.
@inertia("User/List")
@api_view(["GET"])
def get_users(request, **kwargs):
// ...
return Response(data={"users": users})
This can return JSON or HTML with the data injected.https://dockyard.com/blog/2018/12/12/phoenix-liveview-intera...
Phoenix LiveView is a framework where it keeps websocket open with the client and renders DOM changes server side and passes it to the client [0]. Thus with fully server side development without any JS you can have almost full SPA experience.
[0] Have no experience with it, and only read about it some time ago, so don't judge me on the details, but the gist of the "LiveView" idea should be like that.
Do you have any experience in that? I'd love to know where server resource requirements sit between SPA, this and a typical SSR site like Django.
The Phoenix core team has demonstrated over a million (maybe it was even 5?) simultaneous connections running on one server all being updated at once. Granted, it was a proof of concept, but in the real world, you would load balance well before that in all likelihood. The point is the same though. BEAM languages can easily manage a hundred thousand nodes of state simultaneously without breaking a sweat. For most apps, this is plenty as demonstrated by discord, WhatsApp, and other BEAM focused tech companies.
1. Asyncio is like java.lang.Thread in that it's very low level; which isn't accurate: it's totally acceptable and easy to write async concurrency using asyncio (the python async stdlib) directly. While frameworks like Trio are nice they're nowhere near as necessary when working async as thread/pool managers are in Java. 2. Asyncio is like java.lang.Thread in that it has similar pitfalls to threaded programming in general. This is also untrue: in async programming in general, race conditions are much harder to write, and concurrent modification issues aren't a risk at all in Python async code the way they are in threaded Python or Java.
However, I still remember the hell that was updating the state and keeping the rendering in sync with it when using jQuery. Native JS of course doesn't improve on that, and (judging by the description - no experience with it) Alpine.js doesn't either. For me, the paradigm of rendering from the internal state is what makes React (and Vue,...) useful. Too bad that npm ecosystem sucks and that everyone is inventing new shiny useless new things all the time... But React makes non-trivial single-page apps possible.
Of course, if you need server-side rendering (for example because of SEO) then the equation changes, and maybe using Alpine.js makes sense.
But they're just not worth the effort for a form-oriented website with a small-medium team behind it. Almost everything about a web-app is harder with an SPA.
I think this varied a lot depending on how teams approached it and that a lot of the appeal to something like React, Vue, etc. was simply that there was one way to do it.
The approach I've been quite happy with is to use JavaScript classes (IE11 is less than 1% of global web usage) for internal state, where you follow standard practice for having ownership and updates between different parts of your app, and the HTML5 data APIs for the public elements which are managed by different codebases. Web Components has something like 95-97% availability these days but this can be as simple as using element.dataset.whatever as needed. React is definitely good for huge apps but a significant fraction of the web sites I use are solidly in the level of functionality which in 2021 doesn't need functionality outside of what a modern browser provides.
What doesn't work well (and what tended to happen with jQuery apps) is having state both on the client and on the server and having to coordinate between the two. My personal preference is for client side state with a lighter setup than React (i.e. Svelte). I like the predictable latency and I feel you don't run into a complexity barrier (e.g. multi-step forms) as the app grows.
While it won’t fit the needs of a complex app with dozens of components, it does drive the UI from the state. In fact, it uses Vue’s reactivity engine.
So the question is, do frameworks make it easier? I don't think they really do. I think they make it easier to manipulate state, but not designing your system will still mean state being mismanaged.
For my latest project[1], I've opted for https://unpoly.com instead of Alipine+htmx as Unpoly allows me to write 100% server-side code and sprinkle some progressive enhancement where desirable. As a result, I can offer a no-JS experience (minus the Stripe Checkout) for those who may want/need it. Additionally, it forces me to focus solely on the server-side, and I write more idiomatic Django code as a result.
Sending an AJAX request every time you enter characters just to count them. Ewwww.
Personally, I mostly use Unicorn as a component library to split up functionality from the view code, and as a way to persist data to the backend (which would already be an AJAX call) without the hassle of creating an API, dealing with serializers, etc.
Stimulus is the one I can't get myself to like. Separate JS controllers is clever but the DSL and general nature - it just doesn't click with me.
This sounds like a lot of effort just to brag about how you avoided whatever piece of tech we're considering to be evil this month.
The tooling seemed really nice at first, but I was actually shocked at the number of dependencies and just the overall complexity with all the layers of abstractions.
Fundamentally, these are still websites. I honestly see this as people getting bored, inventing new things to deal with their boredom, and the rest of the industry follows.
Meanwhile, the services I was writing in Java like 10 years ago haven’t really changed. We agreed Spring sucked and moved on. At a FANG where I work, we use Java and Kotlin. A lot of my data crunching jobs are in Scala. We did start using Rust for shared libraries deployed on mobile operating systems… because the entire team preferred it over C++.
But I come back to web development and there’s always a new flavor of solving the same problem. /shrug
The cost due to the complexity is at least 10 times more.
It feels strange to me that nobody in the hierarchy consider it.
I do understand that developer like to play with new technology and don't care about the cost as long as they can play with it and get paid but the hierarchy must have seen the millions dollars lost. Why did they do not say something about it ?
React, by comparison, is absolutely massive. It's complicated. It requires compilation, and often a complex build configuration. You still need a backend server, so it won't obviate Django.
Your comment speaks to a larger debate, but it's a rather disappointing contribution.
technically, but not in the same way e.g. Svelte does. the syntax used by React, JSX, is simple local syntactic sugar:
<Foo x={a} y={b}>...</Foo>
// ↓
createElement(Foo, { x: a, y: b }, ...)
i.e. basically a macro, no real "compiling" going onso it is a very lightweight combination on top of plain-ol' HTML
[1] - https://bundlephobia.com/package/alpinejs@3.5.2 [2] - https://bundlephobia.com/package/htmx.org@1.6.1
IMO, it's annoying enough that it's probably not worth it unless you're doing something trivial. If you want to render html on the server you can still do that, but in many cases it is easier to just use custom javascript and maybe even receive the rendered html as json to simply updating pages rather than use htmx.
Frameworks like .Net WebForms were created to abstract and hide a lot of this from developers, with things like long encoded strings of "view state" that would be re-posted on each request, by serializing things to the URL, or by saving them to Cookie-backed sessions.
But each of these has issues, from privacy concerns using the URL, to security concerns with the "view state", to concurrency and integrity concerns with sessions.
IMO, the biggest reasons these didn't stand out as huge problems in the early 2000's was because:
(a) we didn't use the web like we do today, and our expectations were very different in how things would work if we, for example, added an item to a shopping cart
(b) most heavily interactive / app-like things that more closely work "the way we expect" today, were either still done as desktop apps (like business software) or were implemented as Java applets, Flash, or something else of the sort
(c) in the rare cases that neither (a) nor (b) applied, it was because some very good engineers put in a lot of work to make it work that way.
Htmx pulls html content from the server and replaces inner|outerHTML with it. A JSON object (of the type React/Vue and presumably Alpine use) isn't a good fit to store html blobs and state.
alpine increases client side interactivity, it can also do ajax to talk with server, why do I still need htmx then?
On the other hand if I use htmx I will probably use its hyperscript for interactivity on the client side, to be 'consistent'.
Note both projects are trying to make frontend simpler, mixing them seems not to help that goal to me.
You can reimplement htmx functionality with Alpine, but htmx is a lot better than `@click="fetch('/partial').then(res => res.text()).then(frag => $el.innerHTML = frag)"` all over the place (with a slight variation in that one component that you miss because of the noise).
Don't use _hyperscript just to be "'`consistent`'", use it because you want to. Being agnostic and playing well with other tools is a big thing for htmx. _hyperscript is lots of fun and lets you write very readable code, but you also need to stomach a 26mb bundle just to toggle some classes :/
(if anyone reading this can help us make it smaller, LMK)
ackshully, 21.2 kB:
https://bundlephobia.com/package/hyperscript.org@0.9.0
Which compares pretty well w/ alpine, which comes in at 21.7kB with its dependency:
https://bundlephobia.com/package/alpinejs@3.5.2 - 17kB https://bundlephobia.com/package/@vue/reactivity@3.2.22 - 4.7kB
:)
AlpineJS (and hyperscript) are better for purely front end needs.
htmx and Alpine pair well together, as does htmx/jQuery, htmx/VanillaJS or, if you are brave, htmx/hyperscript
I honestly still don't see the point of htmx, to me alpine.js + axios can cover all the front needs, assuming backend returns json instead of html.
htmx is useful for django etc when it's returning html though, but new frameworks are more likely to return json instead.
there's a hole in the market for people wanting to use frameworks to make saas sites -- frameworks provide great primitives that are subtly unusable for some modern web apps. Login but not saml, admin but not multitenant, forms but not multiple forms on a page
feels like this scratches an increasingly common itch of 'the web as a platform isn't shaped like what people use the web for'
Also boilerplates occupy a very important world between no-code and code-everything-yourself. In a no-code world you're fully at the mercy of whatever options someone has provided you with. But starting from a boilerplate allows you to dive in and completely customize things how you need to, without having to worry about the provided abstractions. As a developer the interface I want to use is code, but few products provide that.
- create a quick JS file that loads and configures PJAX to automatically intercept links and - wherever you would have $(function() {}) ensure that it's also triggered on the PJAX load event, and is idempotent (e.g. check if you initialized a component before initializing it again)
Then you just render pages server-side like it's 2000, without any pjax-specific code needed in your templates themselves.
If you're building a data-focused product either solo or with a small team, it allows you to focus on your Python code, and anything frontend is as easy as accessing the variable in a Django template. Of course, it's a massive accumulation of technical debt - when you're successful you'll need to rewrite in a modern framework for maintainability and agility. But when you need to "punch above your weight class" and just get a product out into the world, it can be an amazing technique.
htmx is an attempt to drive HTML forward as a hypermedia, so it exposes explicit, client-side attributes, rather than hiding them as with pjax/turbolinks, although there is an attribute, hx-boost, that acts similar to them both
worth noting that intercooler.js, which was the predecessor for htmx, is 8 years old as well
One of the challenges we have is that people tend to hear about practices from very large tech companies because they have enough people to have things like developer evangelists and time to write lengthy blog series or produce videos. That often leaves people without the nuance that some of the tradeoffs make more sense when you have 50 developers including a dedicated support group but smaller teams might not make back the cost of entry. I like posts like this for reminding people that there are other options which might be appropriate for different projects, especially since even at large organizations it's usually easy to find small projects.
https://hexdocs.pm/phoenix_live_view/uploads.html#upload-ent...
Anything that can be done with React/Vue can be done with htmx in a more “Django-way”- it’s an amazing library that allows for complete web applications without the complexity of the JS ecosystem
Keep an open mind and continue reading on
Of course, that fact alone doesn't undermine the merits of the subject matter. But I'd seriously consider it a presentation issue when doing evangelism.
Why though? I see this sometimes even on mainstream sites and I always wonder what the idea is.
// when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
// find every element with the class "close"
(document.querySelectorAll('.close') || []).forEach((closeButton) => {
const parent = closeButton.parentNode;
// and add a "click" event listener
closeButton.addEventListener('click', () => {
// that removes the button's parent from the DOM
parent.parentNode.removeChild(parent);
});
});
});
It'd be clearer without useless comments and useless extra code: document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.close').forEach((closeButton) => {
closeButton.addEventListener('click', (event) => {
event.target.parentNode.remove()
})
});
});HTMLX uses innerHTML/outerHTML extensively, meaning that XSS is a real concern. Any sanitation of user-generated content must happen server-side. This how traditional server-side frameworks generally work, but it's the opposite of how sanitation tends to be handled in large JS frameworks such as Angular.
https://htmx.org/docs/#security
Alpine.js requires an alternative syntax to avoid running afoul of unsafe-eval Content-Security Policy. With this more verbose syntax, there no inline expressions in templates; everything is bound to attributes in Alpine.data instead.
It's the same kind of a concern as having a user input inside HTML served from a server in the first place. And typical backend frameworks people would use with HTMX are already good at mitigating XSS inside served HTML.
Um, yes? You should treat every request to hit the backend as a potential attack, otherwise you're going to have a _really_ bad time at some point.
But they still do server side input validation, right? Otherwise, that would be a security concern.
So instead you sanitize any user input just before every place it’s processed. Escaped in SQL, escaped on the frontend, escaped in email mailers, etc. This philosophy means that that you can’t use things like innerHTML on the frontend at all because the server output might contain XSS, and frontend frameworks don’t escape content added to the page via direct DOM manipulation.
My understanding of this is that you leave data that is effectively an exploit in your database, and rely on the rigor of everyone using that data to validate it correctly? Have you had to do this in real life - can you provide an example?
I guess I've seen something like "<b>This is bold</b>" rendered after someone has fixed a bug, but I've also seen that rendered as bold text because it wasn't fixed everywhere (which is terrifying to me, knowingly not fixing malicious data).
HTMX, in my opinion, has a smaller scope. Of course you can do everything, but you'll have to do more yourself.
Alpine seems to be even more low level, kind of a lightweight Vue. I don't like it, it really turns me off adding code in html attributes.
are there any unsurmountable issues around security and the sandbox etc (not terribly familiar with browser internals)
- maintaining the "accessible by default" nature of HTML
- swapping. htmx takes html from the server and uses one of innerHTML, outerHTML and insertAdjacentHTML to put it into the document, but it also does a whole lot more to avoid unexpected behavior. This would all need to be specified and implemented natively
Personally, I am not buying the whole "you can do anything this way" because it seems to me the main driver, implied or plainly stated, is always the "and no js!" part.
I get it, though. We are all capable of going to great lengths to prove a point. Having more viable options is great.
But I lost the page. And the proposal itself doesn't mention Alpine.js or HTMX so no keyword bring it up in Google. I am wondering if anyone have any idea.
But then, the rest of the page is server-generated (taking care of SEO), and handling interactivity without JS may not be a priority for most sites nowadays.
for example, the active search example can be made p/e'd by wrapping the input with a form that submits to the same page:
https://htmx.org/examples/active-search/
but it requires work by the end developer
the idea here is to be pragmatic: obviously some people care deeply about p/e and are unwilling to sacrifice it for more advanced U/X, but others are willing to do so, so let's make it possible for both camps to improve their sites with the tool
I’ve been trying this in all my hobby projects and am absolutely hooked. It feels simpler than even django-sockpuppet, say.
* Is it because JavaScript is too hard to learn or too unpleasant to write?
* Is it because training people to write JavaScript is too much effort?
* Is it due to a lack of trust in your fellow developers?
* Is it due to challenges in planning or forming architecture?
* Something else?
I have ~16 years of experience. My old PHP websites have advanced seriously, and are more reliable that my Node based ones. The tooling changes in node, the platform changes, the capabilities of the user agent (the iPhone's per tab memory !== that of a virtual browser on AWS), the restrictions of the system, the assumed tools and tool rot.
Similarly, as Angular was replaced by React by Vue by Svelte in developer mindset, and the skill set of those coming in changed, as the versions of each of those platforms became less and less compatible; I have pages in Mootools that are just dead weight. But even if I had PHP3 pages, they would be humming along with minor changes....
Not to mention the security issues the JS community faces relative to eg. PHP, and you can bet that HTMX definitely appeals to me for anything that I don't need to do in the browser.
https://htmx.org/attributes/hx-swap-oob/
Source: I used this to implement my https://fromzerotofullstack.com website.
syncing state with the back end would be handled by htmx
In the meantime, I'll keep waiting until we get native HTML imports/includes - hopefully before the heat death of the Universe.
htmx is for syncing client side actions with the server effectively within the hypermedia model
AlpineJS (and hyperscript) are better for purely front end needs.
htmx and Alpine pair well together, as does htmx/jQuery, htmx/VanillaJS or, if you are brave, htmx/hyperscript
- Home computer.
- Mainframe. Much more powerful and reliable.
- More powerful PC. Mainframes have latency et all.
- More powerful Server, browser cannot handle that much computing.
- More powerful browser. A whole OS really. Servers have latency.
- More powerful server.. All that complexity is hard to rebuild on the client side, and besides phones are too slow...
Party on!
:D
I mean, there's apps like Pinboard but React & Redux do handle a lot of complexity and most modern apps demand that complexity.
Here's the example that's most convenient for me to pull up: https://www.youtube.com/watch?v=zHoAwVcSLdE (via https://www.commspace.co.za/)
> most modern apps demand that complexity.
Citation needed.
Anyone have thoughts on HTMX vs django-reactor (which is a LiveView port)?
I completely stopped using React
It's totally false. Your HTMX app does not work for JS-disabled people any more than someone's React/Angular/Vue first-render-on-server app.