Hacker News new | past | comments | ask | show | jobs | submit login
An SPA Alternative (htmx.org)
278 points by vimota on July 19, 2022 | hide | past | favorite | 138 comments



For me this feels like finally jumping back to the good timeline.

From the user point of view, I think there are two main types of experiences on the Web:

a ) Interactive documents. Basically web 1.0 but today we want fancier transitions and interactions. This can be provided by htmx and should always have been developed declaratively. It should ideally be provided by the browser and htmx shouldn't need to exist. Examples of this are Gmail and most social networks and forums including this one.

b) Desktop apps-but-I-don't-want-to-have-to-install-them. This would be things like Google Docs, Photopea and most real-time games. To deliver this, right now we have a browser that has become almost an OS inside an OS, to the point only Google can keep up with the complexity. On top of that, we pretend apps are documents and for all the imperative code we need we use a scripting language that was not meant for that, and we need a really complex VM just to keep it more or less performant. For this use case I think at some point we should move all the way into just delivering apps, if not native apps, something like wasm, where the browser tab would just be a vm player.


I agree generally with the two types of experiences, but I'd also submit that there's no easy, clear deliniating line and it's much more of a spectrum between the two types. I really think some of the quirky magic of the web comes from this doc / app hybrid thing it supports and bifurcating them fully would be a mistake.

Rich Harris speaks towards that here: https://www.youtube.com/watch?v=860d8usGC0o


I think the spectrum is the right mental model, too.

E-commerce stores have different interactivity needs than blogs, which have different needs than documentation, which has different needs than dashboards, which have different needs than real-time collaboration tools, and on and on and on.

Much of the framework angst is around the assumption of a singular tool for all these varieties of interaction and the annoyance that comes with not acknowledging the trade-offs.

Plus the web itself is changing, so the breadth of this spectrum is increasing. Years ago, the ends might not have been very far apart but they are diverging more with each new use-case and app idea.


CMIIW for a), chrome is prototyping `shared element transition` for that case.


This reminds me of the <meta> tag page transitions in Internet Explorer 20 year ago! http://www.simplehtmlguide.com/pagetransitions.php


I'm the creator of Reactivated[1] and fully agree with a lot of the aversion to SPAs [2] and REST [3][4]

But to me, writing my markup in JSX (really, TSX with TypeScript) and using scoped CSS solutions was too good to pass up. I just couldn't bear writing text-based templates.

That's why I built Reactivated: combining the best of both worlds. Server-rendered, simple markup — albeit still in TypeScript — but you can add interactivity as needed.

Of course, HTMX is far less opinionated and framework-agnostic. So it can be used with any number of libraries / stacks.

[1] https://www.reactivated.io

[2] https://www.reactivated.io/documentation/philosophy-goals/#t...

[3] https://www.reactivated.io/documentation/philosophy-goals/#r...

[4] https://htmx.org/essays/how-did-rest-come-to-mean-the-opposi...


I am the author of this article. Happy to answer questions.

I know my alternative approach, htmx-enhanced hypermedia, isn't right for every application, but it can be a much simpler approach for many applications, and, since it is so simple, can be used to conserve complexity in applications that have parts that are not amenable to the hypermedia approach.


Thanks for sharing and for your work on intercooler.js and htmx!

I share your sentiments about SPAs, and I've been trying to get back to a simpler web stack.

One of the hurdles I keep running into with libraries like htmx and Alpine is that they don't play nicely with Content Security Policy. And I'm reluctant to forfeit CSP to use a JS library since CSP is the most robust solution I've found for preventing XSS.

Alpine is working on a CSP-compatible build, but it hasn't been released[0] and doesn't seem to be a priority.

htmx is compatible with CSP, but it effectively reverses the protection it offers. The attacker can inject JS through htmx directives.[1] I know there's hx-disable, but this degrades CSP's effect from "secure by default" to "secure when the developer remembers to mark the subtree as containing user-controlled data."

Is there a way to use htmx without forfeiting the benefits of CSP?

[0] https://github.com/alpinejs/alpine/issues/237#issuecomment-9...

[1] https://htmx.org/docs/#security


unfortunately not one I can think of without htmx being baked in to HTML

which, I think should be the case: I don't think htmx should have to exist, I think this is just how HTML should work. That could address a lot of accessibility and progressive enhancment issues as well.


I have no idea how one would go about doing this, but I'm curious if you have pursued that option? Getting the functionality of HTMX into the HTML standard?


+1


Ah, bummer. Thanks for your answer!


Can you be specific about what exactly an exploit taking advantage of this in HTMX would look like?


Could you put publication dates below blog post titles on that website?


Why the use of the article 'An' instead of 'A' ?


They must pronounce it S P A, not "spa". In which case, it's "an" because S sounds like "ess", which starts with a vowel-like sound, so you use "an".

I also pronounce it S P A, so "an" seemed immediately correct to me.


You have no idea how many times I went back and forth on this.


Glad you and I are on the same page, like the comment above you, it's the difference between it being an acronym (SPA) or an initialism (S, P, A).


Because you use "An" if the following starts with a vowel sound, and "SPA" (spoken as the individual letters) does. (EDIT: fell for a false friend, fixed)


Interesting. Do you generally pronunce it as Es-pea-ay? In that case it warrants the an in front


I do. I had never though about pronouncing it as spa, the word.

Sounds similar to the battles between es-queue-el and sequel for SQL.


Interesting, thanks for the insight, I was completely unaware of this one.


Most wouldn’t read an acronym phonetically if it happens to spell a commonly used word.


FWIW, I've never heard anyone say "spa" for SPAs (including conference talks by native speakers, so not just local bubble).


Perhaps it's a culture thing. I am from The Netherlands and I have never heard someone say es-pea-ay; everyone I know pronounces it as "spa". Conference talks in both Dutch and English all pronounce it is as "spa" as well, even native english speakers


On the other end of the spectrum, some people at a past job took to calling interactive but self-contained pages "day spas".


I read this comment and thought about it a lot. I don't think that's the rule. For example, US abbreviating United States. Nobody reads it as "us", even though that's a commonly used word.


U.S. would be initialism, not an acronym. I think we’ve stumbled into a linguistic grey area. Really a matter preference I guess.

https://abbreviations.yourdictionary.com/reference/abbreviat...

https://www.merriam-webster.com/words-at-play/whats-an-acron...


Have you polled web developers? There have been some attempts to do so [0].

[0] https://twitter.com/zachleat/status/1230239491014656001


[flagged]


SPA means "Single Page Application", I don't spend much time defining it but defer to Tom Wright's definition, about which he says:

> The SPA pattern (Single-Page Apps), I tried to define, was about the React model, which also covers, to a large extent, the model of Vue, Angular, and other frontend frameworks.

I created an alternative to AngularJS, Meteor, Knockout and Ember.js back in 2013 called intercooler.js. It used hypermedia as the communication mechanism with the server, rather than JSON. I wrote the library in JavaScript because that's what was there. In 2020 I rewrote the library to eliminate the jQuery dependency and clean it up and renamed it to htmx, since I had figured out that it was a generalization of HTML as a hypertext.

I think that's a pretty good summary of what happened.


This reads like more of an attack than a question. Even though I prefer React over HTMX, I think the difference is pretty clear, as well as the intention of this article. In particular, this quote from the article is most relevant

> In HTML-Centric Development, rather than being an afterthought, HTML is embraced as the primary medium of application development. This is in contrast to most SPA frameworks, where a client-side model & the javascript that manipulates it is the central focus.

If you read the authors other post about REST [1], they also talk about how most SPAs communicates with the server via JSON, whereas HTMX uses HTML. This is also part of the HTML centric design. You embed the fetching logic into the HTML, and the server returns HTML directly, so there's less work done on the client, in constrast to most SPA frameworks.

[1]: https://htmx.org/essays/how-did-rest-come-to-mean-the-opposi...


I too was also somewhat surprised here because this is a React alternative, not an SPA alternative. SPA in my usage has always been "don't navigate to a new page in the browser, just update the content with JS requests."

I thought this would be a new experimental browser or such. "An SPA Alternative" vs "An Alternative SPA" - I had a job in 2011 where we were rendering partials in Rails to send down HTML just to replace certain elements on the page to keep things single-page. We later moved to Backbone to do it more client-side on certain parts. Then I had a job in 2012 where we were in the process of rewriting the site to be a Single Page App with JSON, even. React wasn't released at these points. The SPA term was well established even then.


Well the author does seem to wish that HTMX becomes part of the browser [1]. So who knows maybe some day it will be more like an "SPA alternative" and not just an "alternative SPA"

[1]: https://news.ycombinator.com/item?id=32158367


The title is literally an SPA Alternative. Should the title then not be updated to an SPA framework, since it isn't an alternative. That is like saying Microsoft Word is an alternative to word processors.


But it isn't an SPA framework, it's a generalization of HTML as an alternative to SPA-style frameworks. It's very different conceptually, as different as mobile apps and web 1.0 apps at the network architecture level.

I understand that this approach will not appeal to a lot of folks, but on the other hand that's because it is so different than what most of the industry is doing.

I hope I understand your criticism correctly here.


The issue I have is that you're taking the idea of an SPA, which is pretty loose:

> An SPA (Single-page application) is a web app implementation that loads only a single web document, and then updates the body content of that single document via JavaScript APIs...

Looking at the examples at htmx.org, this is exactly what it does. Just because some car manufacturers decide to put an engine in the front of the car doesn't mean that a car with an engine in the back isn't still a car.


But htmx doesn't update the body content of the document via JavaScript APIs. It updates them via HTML APIs. That is, the content coming over the wire from the backend is HTML, not JSON.

If you're trying to claim that literally any web page which uses JavaScript in any capacity to update any DOM on the page ever suddenly means it's an SPA, that seems like _quite a stretch_.


> But htmx doesn't update the body content of the document via JavaScript APIs.

Yes, it does.

> It updates them via HTML APIs.

It updates then by using JS code calling DOM APIs. Just like any other SPA.

> the content coming over the wire from the backend is HTML, not JSON.

The content coming over the wire being HTML, JSON, XML, or text/plain has no bearing on whether the JS framework inserting the result of processing it somewhere on a single pre-existing page is a SPA framework.


htmx isn't single-page focused, it has features like hx-boost and hx-push-url that are there to explicitly allow the standard URL navigation mechanism of multi-page applications, with the same semantics and conceptual model, history support and so forth

as much as possible it tries to stay within the original model of the web, and just generalize it


I took the title to mean that HTMX is an SPA alternative, as in, an alternative way to write SPAs that is unlike the common approach. But as other commenters mentioned, HTMX seems to also focus on multi-page applications


So, it's an HTML-Centric SPA framework. It is still a SPA framework.


SPA stands for single page application. Htmx doesn't limit you to one page/index.html, thus the term shouldn't apply

You'll likely only update smaller parts but have multiple pages, with each page having interactivity enabled with htmx


I took the title to mean that HTMX is an SPA alternative, as in, an alternative way to write SPAs that is unlike the common approach. But as other commenters mentioned, HTMX seems to also focus on multi-page applications


Technically correct but you will have to admit probably +90% of React apps are SPAs.


The issue is the title which is incorrect.


Every time I see an essay from Carson, author of HTMX, I upvote instantly!

Make sure to check other essays at https://htmx.org/talk/ (scroll down for Essays)


I have noticed that there is a dogmatic element to a lot proponents of these libraries which leaves a sour taste in my mouth.

Occasionally you get a head nod in the direction that “sometimes, React is the best tool” but most of the time it’s Simpsons memes stoking a culture war.

If you’ve worked in an org where someone with decision making power has drunk the “progressive enhancement not SPA” koolaid, then it’s just as bad as someone who has drunken the SPA always koolaid - at least you’ll find it easy to hire and find support/libraries with the latter.


This happens a lot mathematicians might have their favourite object they study like Category theory and then get hung up on categories of categories but might forget that many simple things aren't categories like the prime numbers under addition because 2 + 2 = 4 and that is not prime.

Not just programming or math, in physiology you have entire research groups worked up about a molecule that causes dementia and after decades of research realise that the story was a lot more complicated than that.

You can almost recognise a healthy mind by the lack of such dogma, just don't make it a rule that would defeat its purpose.


I have used htmx (and it's predecessor intercooler) on several occasions now.

The real sweet spot is it allows you to push server side frameworks like Django even further. You may find you can skip the SPA all together. And nothing beats the speed of development of a Django/Rails/Laravel.

Htmx is part of my go to stack for solo/side projects and my preferred stack on the job for crud heavy line of business applications.


Same here, except I use Unpoly for all my side projects.


I've been trying htmx and the results are great. So much simpler to code than with SPA. My only concern is about those datetime pickers and other type of "components" that is easy to get from a react/vue ecosystem but much harder in a vanilla Javascript way. Not saying it's impossible, but a bit harder to find decent maintain libraries/components for those kind of web interactions.


I have been using web components for those things. They actually pair great with htmx. Once you import a my-datepicker or my-modal web component it automatically works anytime it appears in the DOM. So htmx can ajax in some HTML and you don't have to wire up an JavaScript to it to get rich interactions. Check out Shoelace (https://shoelace.style/) for a good set of components.


I would focus less on "vanilla JavaScript" as the ecosystem from which good components will arise and focus more on web components (which, generally speaking, are vanilla JavaScript). There is a thriving and growing sector of the frontend space where web components and WC-based design systems are coming to the forefront. Shoelace is a fantastic library in this vein. Libraries like htmx, Alpine, Turbo, etc. benefit greatly from web components.


I haven't use it but my understanding is that htmx is normally paired with something like alpinejs for which there existes date picker components.


Same here, I would love an example on how to use a customizable asynchronous typeahead with HTMX (think Twitter Typeahead, not <datalist>). Couldn't find one or wrap my head around it. (We can hook HTMX into the library events, maybe?).


<input type="date">

Why would you need JS at all for a date picker?!


Because the built in date pickers (and other editors) don't always fit the requirements?

A couple of things I had to handle in the last couple of weeks: - Handling different separators for input - having a clear button to indicate "no date" - display the date in a different format


Yea, would have been nice if the W3C actually gave us usable components, but hey you can connect your MIDI keyboard to the browser.


I am totally with you. Unfortunately firefox as usual cocks it up for the rest of us.


Has anyone got battle stories from using HTMX it similar? I there a time you regretted it a little and wished you had chosen React? Or is it pretty rosy?


I've used it a fair bit in a equipment finance app I have built for a small company.

In the system I've used a mix of regular django templates, some Django unicorn, some HTMX, and some HTMX+Alpinejs

I pick the tool based on the the amount of interactivity I need on the page.

It's.... interesting. If you start out knowing you will do HTMX, then I found everything is much easier. Splitting off small small views to return just the right html after a hx-post is more labor intenstive than i would like, bit overall it's nice.

The hardest part I found was being able to have a fine level of control around the user experience, and solving that required adding a lot of javascript, which made me wonder if it was worth the effort and should have instead just used Vue to handle it.

I've ended up using a lot of HX-Refresh in responses (causes a page refresh) because it was easier to do that than to ensure all the different parts of the page updated at the right time.

The way it cascades htmx values down the tree is really handy, and lends itself to consise attributes on the html.

Overall I'd give it a silver-coated bullet rating. Certainly not a solid silver bullet. :)


> It's.... interesting. If you start out knowing you will do HTMX, then I found everything is much easier. Splitting off small small views to return just the right html after a hx-post is more labor intenstive than i would like, bit overall it's nice.

This was almost exactly my first impression of HTMX as well. It's a huge step forward! However, for my tastes it demands too many tiny views and micromanaging, which somewhat felt like a drag on my productivity. For an alternative, take a look at Unpoly [1] which has more batteries included (i.e. create layers of interactivity that update lower layers automatically) and is centered around full page requests/diffs and less focused on injecting small page fragments everywhere. For my small apps, I could do everything in one view that took three or more views with HTMX. I can only imagine the views exploding for a modestly complex site. The biggest penalty for Unpoly is that it is quite a bit (~2X) slower than HTMX, which needs to be kept in mind and managed for larger pages with a lot of interactivity. I suspect this is because Unpoly loads the entire page and does a DOM diff to see what it needs to update, as opposed to injecting just a page fragment. In my tests, I was able to manage around this issue using layers. The big upside to Unpoly is that the full page refresh architecture aligns very neatly with Django's request/response cycle, which gives you pretty seamless interactivity and form validation. It also has a lot of batteries included that HTMX lacks. I think HTMX is terrific and revolutionary, but Unpoly fits my brain better while doing Django development.

[1] https://unpoly.com/tutorial


I also like Unpoly very much.

I'm using it for a new frontend right now. Combined with a thoughtful CSS design like CUBE[1] that utilizes components but also leverages utilities to reduce CSS bloat I am writing mostly Ruby and HTML and very little JS and CSS and it feels great.

It's kind of back to the basics which means that I also do not worry about being on some framework's upgrade & dependency train or the mental health of future application developers/maintainers.

[1]: https://piccalil.li/blog/i-used-tailwind-for-the-u-in-cube-c...


I have used it for my website [1] and liked it a lot. I found the attributes `hx-swap` and `hx-swap-oob` [2] important to allow multiple updates. For instance, after liking a post the like button updates in several places, in the aforementioned website.

I found out putting the ids for the htmx snippets in a typed datastructure (in my case Python with type annotations, since I use django in the backend) to be easier to find the corresponding templates, see all usages, etc. I think otherwise it gets a bit confusing.

[1] https://fromzerotofullstack.com/

[2] https://htmx.org/attributes/hx-swap-oob/


I’ve found this library a delight. Coupled with a sprinkling of Alpinejs to cover more advanced interactions and Django-livereload, I feel progressive enhancement has a renascence opportunity


I'm pretty sure I've said this on previous mentions of htmx, but I'll say it again: this reminds me of the old SPF framework youtube published.

http://youtube.github.io/spfjs/

SPF was a bit more focused on being easy to merge into an existing server side app.

I am glad to see this and hope it has some legs. It could help free us from the need to write every UI in JavaScript(ish).


It's a similar concept to Google's SPF.

htmx is more light weight, and very actively maintained.


this of course, is really meant for brochure or light interactivity sites. I don't think Figma should convert to htmx. I also don't think its meant for sites that may need to honestly scale as part of their product line heavy JavaScript interactivity. For instance, I've definitely worked at a place that deployed well over 10K components to production (I think we pushed over a million lines of deployed production code).

React & Angular do scale this far, I have yet to encounter any who works with Vue that ships over a million lines of deployed code though I'd love to hear from you!


I don't think that "scale" is the right axis, but rather the amount of interdependence in your UI.

htmx would probably work great for something like GMail, but would be a bad choice for something like Google Sheets. Both are big apps, but one is more amenable to coarse grain HTTP requests because the UI isn't as interdependent.


> Sheets

Interestingly, I have seen a new app that provides a sheet with HTMX: https://www.licenseprompt.com/ (gif: https://twitter.com/WimpieNortje/status/1520419150245638144)


Yep, but the total dependency area there is relatively small and focused. Compare with something like a general spreadsheet, with any number of cells that need updating based on formulas entered in them. That's just not an application that is going to be amenable to a hypermedia approach.


No, it's meant for websites that don't require loading 8 MB of JavaScript. You've completely missed the point that "product line heavy JavaScript interactivity", whatever that means, is bullshit that doesn't solve any problems, it just creates new ones.

You're saying "I have all this code, what do I do with all this code." The answer is: don't write it!


No, I'm simply positing that HTMX doesn't fill the void of heavy web apps, like Figma, or Salesforce. At least not naturally. React does scale well in this way. So does Angular (though I don't care for it, which is another discussion entirely). Especially when you want maximal code sharing in your dependency chain.

I never done it with Vue (largest Vue app I ever worked on had roughly 200K lines of deployed code, all in, for the application, very thick client type stuff), but maybe with Vue 3 and the composition API this isn't an issue (I don't think Vue 2 would ever scale well developer experience wise this way)

I'm not throwing shade on HTMX, but there tends to be this energy around it that would make someone who, perhaps trying to weigh some options, stumbles across HN, sees threads like this and thinks oh gee! This sounds great without knowing exactly what that means. And it is true, that perhaps, that person is building app that needs scalable reactivity and fine-grained control, or something along those lines. I at least want to give a fair take on purpose for people thinking about it.

HTMX is great for its target audience, much superior to jQuery in this day and age, but you have to understand what its for.


The time wasted by choosing htmx for the wrong job is probably quite small compared to choosing react for the wrong job.


To nitpick, Figma is not a good example as it’s essentially all Canvas.


What's the actual advantage of HTMX over something like React or Vue? All 3 require some form of JavaScript library coupled with markup to build interfaces. While I'm all about killing JavaScript as much as possible (why should I let $MEGACORP execute code on my device all willy-nilly without any real restrictions?), I just don't see the tangible benefit to the end user here.

(And don't start with "it's faster/more efficient", that comparison isn't terribly valid because the inefficiencies seen with React/Vue are largely an artifact of bad code/practices, not the libraries themselves.)


You can generate your HTML using a server-side template, and it is mostly just HTML.

> All 3 require some form of JavaScript library coupled with markup to build interfaces.

With HTMX you're typically including one static javascript file that you just download, you're not using any kind of javascript build system at all. Where it has very limited scope it's possible to imagine a browser that doesn't have javascript but that has HTMX built in.

Calling it a javascript library might be a bit much, I mean you're not typically installing this with node/npm, or minifying it, or importing it. You're just including it in a script tag at the bottom of your site. While they both do technically run on javascript I think they have more differences than things they have in common, and saying "Well they're both just javascript libraries" is a very sophomoric take. I mean you might as well just say that all javascript libraries are the same, and it doesn't matter what you use. So why choose react/vue over jquery?

> inefficiencies seen with React/Vue are largely an artifact of bad code/practices, not the libraries themselves.

Ehh, I'm sure you can make a fast bug-free website in server-side assembly if you're so inclined but it's probably not the right tool for the job. The question is what kind of design patterns do the libraries/tools encourage, not "can I do X with Y".


I want to note that Vue provides official instructions on how to use it without build tools [1], and lots of folks who have written posts on how to use React without tooling as well [2]. I agree that they're ultimately designed to be used with tooling, but it's not a blanket requirement.

- [1] https://vuejs.org/guide/quick-start.html#without-build-tools

- [2] https://blog.jim-nielsen.com/2020/react-without-build-tools/


The main advantage I see of traditional server side rendering (like in Rails/Django) is that you develop a single project, not two (SPA + API).

Instead of api models and client models, you just have models.

Instead of api routes and client routes, you just have routes.

Instead of unit testing api and client, you test one project.

Instead of having the client making N requests to load all the data it needs from the server (and being careful not to return more data than you need for performance reasons), you return an html with all the data it needs in a single request, and nothing more.

In the case of client stacks using SSR (like Next/Nuxt):

Instead of running the SPA on the server so the server returns the html rendered, you just make the server return the html rendered.

The benefit to the developer is higher productivity. The benefit to the end user should follow from that.


The tight coupling removes a lot of scalability possibilities though. I understand the higher productivity argument, but wouldn't it be time consuming on the long run to lock yourself in an environment where you would have to go back and build an API if you want to extend your web app to mobile for example?


It depends on the needs of the mobile version. Often, a well designed responsive version of the same web app is enough. Even if it's a mobile native app, you might still be able to reuse some/most of the screens with the same html in a webview.

Even if you really needed it to be an API, you can always make the server side return either html or json depending on some request header. There's also a chance that the mobile version will be different enough from the desktop that it warrants new, custom built endpoints anyway.


Web devs have zero right to run their javascript disasters on my computer. Htmx outsources 99% of the rendering and logic to the server, where it can use up their valuable time.


Can you further explain your principles around the web? I'm curious to hear more. For instance, it sounds like you don't think web sites ought to be able to distribute JavaScript which executes on your computer in order to generate a user interface, but it seems you do think web devs have the right to utilize your internet bandwidth to download markup from a server in order to generate a user interface. Is that the case, and if so, why do you make that distinction?


Theoretically my local computer is faster to render something than my network connection can download the pre-rendered content.

However, 99% of javascript blobs of hatred end up slower than downloading the pre-rendered content.


Maybe GP wants to access the information and not the unnecessary local processing?

Edit: wording


Why stop there? They should get their own end users as well.


If you hate it so much just turn off JavaScript and enjoy waiting for the page to reload every time you click on anything


Which is often faster than the response time of a client side app.


Great! Enjoy it!


One big advantage is simplicity: you eliminate the need for a lot of client side technology, such as routing, and push everything back to the server.

Also, by eliminating application javascript, it allows you to spend more time in your preferred language on the back end.

The downside is the same as regular HTML, although less pronounced: since you are driving application state through hypermedia (HATEOAS), the less coarse-grained your state or UI gets the more annoying things are going to be. There are some patterns that help but eventually, if you want to update 12 different places in your UI at once on every keystroke, the hypermedia approach just isn't going to cut it.


> Also, by eliminating application javascript, it allows you to spend more time in your preferred language on the back end.

But these days (using transpilers and/or WebAssembly) you can choose just about any language on the front-end ...


That's true and, in the case of pyscript in particular, may limit the appeal of something like htmx.

On the other hand, the simplicity of the hypermedia approach, and the flexibility of ReST are still there.

We'll see.


It's faster. React apps often load hundreds of KBs - if not MBs - of code before they start to work. HTMX loads 10KB (gzipped).


Then use Preact, Solid or its ilk. Then your bundle size is going to be a tiny fraction of the kinds of things users tend to like, such as images.


Doesn't really matter unless you're targeting low-bandwidth customers. The Amazon homepage is ~4MB, and an average user session is going to downloading many times that in additional images and markup while browsing. In that context, React or other JS files will be single-digit percentage of what was downloaded.


The idea is that the js is used to implement the functionality that the author believes should be built-in. In theory you could have a browser plugin/extension for handling htmx and it would work across every site using htmx. You app-specific "code" is all declarative, just extra properties in your html tags. With most frontend frameworks, even if the browser came with built in support for Vue, React or whatever, you'd still tons of imperative js for each single webapp to define how it uses the framework.

Imagine not having html at all. You'd have to create pages from scratch imperatively by doing things like let element = createElement("p"); element.setContent("my paragraph"); parent.addChild(element); It'd be really ugly, a PITA to change stuff and error-prone. htmx is the opposite of that. It tries to make web development declarative again, among other things.


Without any real restrictions? JavaScript is very restricted in what it can do. Most APIs that you'd expect to be gated behind a permission are gated behind a permission.


[flagged]


Then go back to an abacus?


Unfortunately, abacus side-channel exploits are numerous as well


I think the article kind of explains it pretty well.

It kind of returns to the original intention of the web.


One of my apps built on the Django+HTMX stack got traction and no matter how much I loved using HTMX, I found it’s not feasible to keep a clean codebase (facilitating new developers on the team as well) with this stack.

[Tetra](https://www.tetraframework.com/) might be an alternative if you’re hell-bent on not using React.

But, if you want to ship quick, have a maintainable codebase in a technology a lot of devs are familiar with and have the power to instantly ship for mobile (and buy yourself some time to build one in React Native; code is going to be similar to React.js), I’d recommend using React.

You can use Capacitor.js for instantly shipping a mobile app with your codebase that “just works”. Use Capgo for affordable codepush and you’re set!

HTMX all the way if you’re not building an app cause not everything is an “app”.

At the same time, if you’re building an app with a framework unlike Phoenix, I don’t see why one would not go ahead and use a decent JS framework. Using frontend framework seems to be facing a lot of aversion and I don’t understand if it’s because of the inability to learn these frameworks or what.

Point is, your users just need a snappy app that works. That’s it! And using a robust frontend framework makes it easier.


Here's the "motivation" for htmx, from it's main page:

  Why should only <a> and <form> be able to make HTTP requests?
  Why should only click & submit events trigger them?
  Why should only GET & POST methods be available?
  Why should you only be able to replace the entire screen?
  By removing these arbitrary constraints, htmx completes HTML as a hypertext
I think the first three items are minor issues, at best, which in no way justify yet another DSL.

The fourth is a reasonable point -- it's quite common that you only want to update a portion of a page.

But it's very unclear that HTTP requests are the way to do it.

For one thing, using HTTP requests as the transport for app event handling adds nothing conceptually. It seems nice to use something that people are widely familiar with to build an event model on top of, but HTTP isn't a good fit for everything. So you either need something else (javascript or another language/api/framework) or you awkwardly fit everything into this model anyway.

But more importantly, it implies a strongly hierarchical structure to your app UI, which I think is overly rigid and unrealistic. Content tends to be largely hierarchical, but frequently important cross-cutting concerns pop up... maybe not on day one, but maybe on day 100 or 1000. Now you're swimming upstream.

Also, it's not like there aren't a very high number of HTML-centric options available. It has an interesting low-level approach, but in the end we're developing apps and UIs. It's very unclear to me whether htmx really offers advantages that other approaches don't meet or exceed.


> It's very unclear to me whether htmx really offers advantages that other approaches don't meet or exceed.

You say what is the advantage before :) :

> ... maybe not on day one, but maybe on day 100 or 1000.

That is the thing. Is Wonderfull when you actually wait and see if you truly need the extra complexity of things.

Go nuts when is time to go nuts.

But is nuts to do it now.


Naive question but how would styling be handled actually? If the server just returns plain html tags with content in it ... I mean, I don't quite get it


Exciting new technology for styling web pages.

https://www.w3.org/Style/CSS/


The question makes me think someone is teaching new developers wrong in a complex-thing-first way.

Instead of HTML, CSS, JS in that order maybe they got chucked right into a NextJS / Tailwind twitter clone course as their intro to web dev.


Lol naw man that ain't it but i'm surprised apparently nobody got what I was getting at:

Say I have my css sheet included, now I still need to set the class and id attributes everywhere I need styling.

Are you telling me the client needs to parse the html result and add those manually? Seems absurd. Are you telling me a real Hypermedia API would return stuff like

<div class="...">data</div>

? That would seem equally absurd, why would the API concern itself with css classes lol.

That's what I don't get


Oh I see. Cant speak to the library author’s intent but I think of it like this.

Take an old school original rails app. No JS. Nothing. If something is gonna happen it is because you clicked a link or submitted a form.

In that app any page is generated by the server and must have any classes defined for css also rendered.

So the server is already needing to know about this and inject those classes.

With HTMX it is the same thing except you render partials sometimes and sometimes the whole page.


KISS… use semantic tags when possible. In this example, perhaps table. Classless CSS helpful as well.

Beyond that I don’t think adding an id or class here and there is too bad. I’d avoid class heavy frameworks, as I believe you are alluding to.


Haha ok let me expand, I didn't actually mean only styling but layouting as well. Consider this example from htmx.org:

<html> <body> <div>Account number: 12345</div> <div>Balance: $100.00 USD</div> <div>Links: <a href="/accounts/12345/deposits">deposits</a> <a href="/accounts/12345/withdrawals">withdrawals</a> <a href="/accounts/12345/transfers">transfers</a> <a href="/accounts/12345/close-requests">close-requests</a> </div> <body> </html>

What I don't get is who says I want to have all of that html displayed in this exact form anywhere I make a request for account info? Say I want to only display the Account balance - are you telling me client has to cut and parse the html response for that? How much html parsing is that gonna be all over a web page?

Also the example I gave below about setting the css classes and ids inside the returned html elements...


No. You would not reuse the “partial view” API call by parsing and adapting the result. You make a different partial view for each instance.

This is my slight “ugh” against it and why I prefer the idea of the frameworks that just get the entire page and do a differential swap because architecturally that is simpler. No need to create lots of weird little partials and wire them up.


htmx supports a few different ways to take complete page responses and wire them in to an existing page:

https://htmx.org/attributes/hx-select/

https://htmx.org/attributes/hx-select-oob/

https://htmx.org/extensions/morphdom-swap/


Oh wow, this feels like a somewhat buried lede for how you would actually use HTMX in the real world. I've played with it quite a bit and didn't realize this was a pattern that was actually viable.

I think it would really benefit the project to have more documentation/examples of architectural patterns for how an app might use HTMX.


yeah, a problem w/ htmx being a backend-agnostic extension to HTML is that you need to produce examples for all the popular backends.

there is a page here with links to various repos people have put together:

https://htmx.org/server-examples/


I imagine it would be somewhat easy to provide a way for the APIs to include a way to filter the resulting HTML they produce. A CSS path as a URL parameter that the API runs to only return the content of the CSS path.

There's probably some kind of balance between giving every partial it's own URL and allowing each partial to support a filtered response. You could write a little middleware for your http server to support the filtered response on every endpoint that returns HTML.


Yeah there could be some kind of “varnish-like” layer outside the app server designed to modify the response to the required “lens” that is specified in a header.

This would process the app response and filters/zoom to the part of the doc you want. The app could be agnostic and it reduces the amount of crap sent over the wire.


Looks like HTMX already has something like this, just client-side. https://htmx.org/attributes/hx-select/

That's probably safer in some ways than filtering server side.


The normal way: via a CSS file included in your head.


Yea I figure but I meant actually like layouting and overall decision-making when it comes to how much data should be shown in this or that place, why should the API make those decisions for the client rather than just sending data?


It’s not an api but a partial view.


Usually, the server returns plain HTML tags with Tailwind-enabled 'class' attributes.


I don't understand why you mentioned Tailwind. Nothing about htmx requires a utility class framework AFAIK.


I think it is snark. The implication is that if he just said “use css classes” in 2022 it wouldn’t be understood by “cool kids” so tailwind is mentioned to clarify what a css class is.


Huh? Wasn't meant to be 'snarky' at all. Sure you can use plain CSS classes but Tailwind is immensely popular. Htmx + alpine + tailwind is a fast-growing front-end stack, for good reason. Use it or don't use it, whatever. (the last sentence is snark)


Sorry! I guessed wrong


Because the guy asked about styling and Tailwind is by far the most popular CSS styling toolkit. Never said it was "required," just common.


Kind of reminds me of sveltekit. For example, I hate writing the same HTML repeatedly, so I just used svelte for it's components and made a fully static, JS-less page. That later evolved and left out the JS-less (some fancy effects, dialogs, cross-page transitions etc), but even for building static pages seems far better than writing normal HTML, when those pages become a bit complex.


I think Turbolinks is a nice balace bewteen traditional webpage and SPA. https://github.com/turbolinks/turbolinks

It provides a smooth UX by fetching next page's HTML in background, then replace the DOM by compareing the diff in HTML. So you won't see a blank page while navigating between pages.


https://hotwired.dev/

They turned Turbolinks and extended it into a complete framework. I really want to give it a try.


Turbolinks is one of those things that seems revolutionary to begin with, until you need to start implementing hacks in your server in order to deal with edge cases.

Things I remember from the last time I had to deal with these libraries were redirects and hard-to-debug JavaScript issues due to so much JavaScript relying on document ready/onload events.


I have been doing something similar where a js file takes over links and forms and uses fetch to get content and some other data on navigation.

Great TTFB as I don't need to send it to node to render js, faster navigation for many users with slow plugins and easy to implement.

This seems to do the same thing, and much more. I really need to try htmx, looks cool!


What are the pain points developers have with SPAs? I've been working on a nextjs/react/tailwindcss project for 5 months full-time now and I honestly love it. It's been very intuitive and straightforward to get things done.


There are no pain points with SPAs that can't be had in any other kind of web app architecture. Most of the problems we run into are ones we create for ourselves. Writing jQuery splatter got tiring, so we moved everything to the frontend. Then we got tired of our 300+ line Webpack configs, so now the old days of server rendered HTML is where the grass looks green. Inevitably, we will get tired of all the hacks we have to do to work around the shortcomings of HTMX/LiveView/Hotwire and move on to something else.

What tires me is the groupthink around web development. SPAs and server rendered content aren't better than one another. It's annoying and unreasonable that the current trend is that SPAs are bad. They are not. Everything bad with SPAs I've seen is caused by developers not getting their priorities straight and by bandwagoning. Stop making webpages complicated and you'll find that many problems disappear.


I really love the idea of htmx and will definitely use it for my next hobby project. Out of curiosity, does htmx only work for always online apps or could you build a PWA with offline capability with it as well?


Seems focused on a backend service, but you may be able to fake it.


When was this published?


[flagged]


I assure you, at this point, as much as you, I would like a break from the front page


People post it and other people upvote it?

I've seen this before but I enjoyed the other article and it was new to me




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: