Blazor and Htmx are unique technologies with strengths and weaknesses. In this short list, we'll discuss five reasons to use the technologies together and five reasons to avoid the combination.
ASP.NET Core, now with Blazor Server-side Rendering (SSR), is a robust backend HTML generator. You can do almost everything for UI on the server, and with Htmx, you can accomplish some commonly difficult client-side interactions with relative ease.
With Htmx, you can define interactions declaratively with attributes instead of with control flow logic like if
, else
, and for
loops. There's typically little to no need to write branching logic to accomplish tasks.
Htmx only needs an endpoint that retrieves HTML blocks. This means that Htmx is also viable for entirely client-side solutions like Blazor Wasm, as long as you have a service worker which can generate HTML snippets.
Blazor's JavaScript interop means that Blazor and Htmx can subscribe to client-side events and functionality and work together rather than against each other.
Blazor's component-driven design is already primed for the hypermedia paradigm within which Htmx works. Using the RazorComponentResult type, many components can be rendered independent of their component tree and sent piece-meal to the client, which can be more efficient in the long run.
Blazor performs state management on the component hierarchy, and it's nowhere more evident than with enhanced load navigation. When you navigate to a page, the only changed elements are swapped into the page. This means certain page lifecycle events like "load" may not be called and cause issues with Htmx.
Blazor still lacks tag helpers, which is a strong selling point for Razor Pages and MVC server rendering. Tag helpers help immensely reduce the noise in views with Htmx attributes, and Blazor lacks them for now.
Htmx relies on server-side endpoints to process requests and return HTML snippets to be swapped into the current DOM. Blazor current only allows for Blazor pages to be routes, forcing you to rely on Minimal API endpoints and RazorComponentResult
to build out these Htmx-powered touchpoints.
Htmx also relies on HTTP Headers, which Blazor handles mostly independently of the developer. That said, setting HTTP headers from a page/component is possible. Still, you'll need to tie that component to an HttpContextAccessor
and HttpContext
, which limits its use in different hosting scenarios.
Htmx works best when hijacking form
submissions, as that is how you can get a significant amount of state from client to server and back. Blazor also has its Form
control, and these two elements can step on each other in confusing ways.