Skip to main content
← Guides

Guide

HTMX vs Alpine.js: Server HTML or Local State?

Updated PkgPulse Team7 min read
0

HTMX vs Alpine.js: use server-rendered HTML for requests and local state for UI changes. Compare forms, navigation, errors, alternatives, and combining them.

Contents

Use HTMX when an interaction needs the server to return HTML, such as submitting a form or paginating results. Use Alpine.js when it changes browser state, such as opening a menu or filtering data already loaded. The HTMX docs describe server interactions; Alpine's state docs cover local and shared state. Combine them when those tasks coexist, with explicit rules for which elements and state survive DOM updates.

Quick decision matrix

This matrix maps tasks to the state they need. The recommendations are editorial judgments based on the documented behavior, rather than a performance ranking.

TaskStart withWhyCheck before shipping
Submit an edit and display server validationHTMXThe server validates and renders the resultError status handling and duplicate submissions
Open a menu or reveal conditional fieldsAlpine.jsThe relevant state is already in the browserKeyboard behavior, focus, and accessible labels
Search or paginate records held on the serverHTMXResults depend on a server queryRequest ordering and shareable URLs
Filter a list already downloadedAlpine.jsNo new server data is requiredWhether the loaded list is complete
Keep a filter panel open while replacing resultsBothPanel visibility and result data have different ownersKeep the stateful container outside the swap target
Expand a disclosure with no other behaviorNative HTML firstA details element may cover the taskWhether its built-in behavior meets the design
Edit offline with undo and later synchronizationA client application architectureDurable local data and reconciliation need more than fragment swapsPersistence, conflicts, and recovery design

Documentation checked November 1, 2026. The HTMX error-handling guidance below refers to the documented 2.x defaults. No bundle-size or adoption ranking is used here.

HTMX server interactions

HTMX attaches request and update behavior to HTML. Your backend still owns authorization, persistence, and rendering. It generally returns an HTML fragment for the target region, instead of data for a client template to render. The installation docs name the official npm package htmx.org.

bun add htmx.org alpinejs

Package installation is optional: both projects document script-tag installation, so neither requires a bundler. Pin and review the versions you actually deploy. See Alpine's installation instructions for its script and module setup.

A server search can look like this:

<input type="search"
       name="q"
       hx-get="/users/search"
       hx-trigger="input changed delay:300ms"
       hx-target="#results"
       hx-swap="innerHTML"
       hx-sync="this:replace"
       aria-label="Search users" />
<div id="results" aria-live="polite"></div>

The endpoint receives the query and returns the result markup. hx-swap determines whether to replace the target's contents, replace the target itself, or insert adjacent content. That choice affects which controls and state remain on the page.

Debouncing reduces requests while a person types; it does not define how concurrent requests interact. In this example, hx-sync="this:replace" aborts a request from this input when a replacement request starts. If several controls update the same results, coordinate them around a shared synchronization target and test slow responses.

HTMX fits an application whose server already renders HTML. It does not automatically translate a JSON-only API into templates, or supply an offline data model. For the broader architecture decision, see our HTMX vs React guide.

Alpine.js local state

Alpine declares reactive state with x-data and can share state across a page with Alpine.store(). That scope is the useful distinction: menu visibility belongs near the menu, while a preference used throughout the page may belong in a shared store. These are browser values, not a replacement for persisted server records. Alpine's state documentation explains both scopes.

<div x-data="{ open: false }">
  <button type="button"
          @click="open = !open"
          :aria-expanded="open"
          aria-controls="filter-panel">
    Filters
  </button>
  <div id="filter-panel" x-show="open">
    <!-- Controls for data already present, or a server query -->
  </div>
</div>

Here x-show changes visibility while keeping the element in the DOM. No request is needed to open the panel. Hiding a panel also does not make its state durable across a reload or replacement of its enclosing component.

Alpine can call JavaScript, including network APIs; the distinction is not that it cannot fetch. Its reactive state does not provide HTMX's server-fragment request and swap conventions. If you fetch manually, your application owns response parsing, errors, rendering, and cancellation.

For a static site, start by asking whether the interaction needs fresh server data at all. A menu, calculator, or filter over embedded content may only need local behavior. Our static site generator guide covers the surrounding site architecture.

Using HTMX and Alpine.js together

Keep the component that owns local state outside the region HTMX replaces:

<div x-data="{ filtersOpen: false }">
  <button type="button"
          @click="filtersOpen = !filtersOpen"
          :aria-expanded="filtersOpen"
          aria-controls="filters">
    Filters
  </button>
  <form id="filters" x-show="filtersOpen"
        action="/users" method="get"
        hx-get="/users"
        hx-target="#user-results"
        hx-swap="innerHTML">
    <label>Status
      <select name="status">
        <option value="">All</option>
        <option value="active">Active</option>
      </select>
    </label>
    <button type="submit">Apply</button>
  </form>
  <div id="user-results" aria-live="polite">
    <!-- Initial results rendered by the server -->
  </div>
</div>

Alpine owns filtersOpen; HTMX replaces only the results inside #user-results. The form also has a conventional action for a full-page submission. The backend must support both that page response and the enhanced fragment response.

This layout keeps the filter controls and their parent in place. Moving x-data into the replaced results would give its state a different lifetime. Attribute prefixes alone do not prevent lifecycle problems: both libraries ultimately operate on the same DOM.

Limits: errors, history, and DOM lifecycle

Errors need a visible recovery path

Under the documented HTMX 2.x defaults, successful HTML responses are normally swapped, while HTTP error responses are not. A backend returning validation markup with status 422 therefore needs deliberate response-handling configuration or a htmx:beforeSwap handler. Distinguish expected validation from server failure; do not turn every error response into a successful swap. See HTMX response handling.

The event reference distinguishes htmx:responseError, htmx:sendError, and htmx:timeout. Use them to show a useful failure message, restore disabled controls, and offer a retry when appropriate. A loading indicator alone does not explain a failed save. Test validation failure, loss of connectivity, and a server error as separate cases. Authorization and CSRF checks still belong on the server.

History needs real page URLs

hx-push-url adds browser history entries and uses DOM snapshots for navigation. Choose it for meaningful navigation, such as a result page, rather than every menu toggle. A pushed URL must also work when opened directly or reloaded: the server should return a complete page, not an isolated fragment. The history documentation covers restoration and cache misses.

An Alpine store is not automatically encoded in the URL. If selected filters must survive a copied link, define URL parameters and reconstruct the controls and results from them. Test Back, Forward, reload, and opening the URL in a new tab. A result list that changes without matching controls is a state bug even when every request succeeded.

DOM replacement can reset state

Replacing an x-data root creates a new component with its initial values; replacing its descendants can also remove input values or third-party widgets. Keep state that must survive outside the target, or choose an explicit preservation strategy. Alpine's lifecycle hooks explain initialization; rerunning initialization is not equivalent to restoring a user's draft.

Alpine Morph offers DOM updates designed to preserve browser and Alpine state. It is an additional plugin, not a guarantee attached to every HTMX swap. Integrate it deliberately and test element identity, focus, and state restoration. Avoid having Alpine render a list that HTMX also replaces without a clear owner.

Before using both on an edit form, try this sequence: type an unsaved value, refresh a neighboring region, submit invalid data, then navigate Back. Decide which values should survive each step and verify them. That is more useful than assuming the libraries cannot conflict.

Alternatives to HTMX and Alpine.js

Choose an alternative by the job you want to move. Alpine alone does not replace HTMX's HTML-over-the-network behavior, and HTMX alone does not supply Alpine's reactive local state.

NeedAlternative to evaluateWhat changes
Server-rendered navigation and region updates instead of HTMXHotwire TurboDrive enhances navigation; Frames scope updates; Streams deliver update actions. Adopt its response conventions.
Reusable HTML behavior instead of Alpine.js expressionsStimulusJavaScript controllers attach through data attributes, with actions, targets, and values. Behavior lives in controller code.
Reactive components with room for a client applicationVueVue supports standalone script use and larger applications. Choose which DOM region Vue owns before mixing renderers.

Turbo is worth evaluating when the desired replacement concerns navigation and server HTML. Stimulus is worth evaluating when the concern is organizing browser behavior into reusable modules. They can be used together; neither requires treating server interaction and local behavior as the same problem.

For a single disclosure or a conventional form, native HTML may remove the need for either dependency. If the actual requirement is offline editing, complex undo, or collaboration, budget for persistence and synchronization rather than expecting a library swap to provide them. Our JavaScript framework overview puts those choices in a wider context.

Choose by interaction and state

Start with HTMX if your backend already renders the content and the next feature is a server interaction. Start with Alpine.js if the next feature changes local presentation. Use both when each has a clear job, and test failures and navigation alongside successful clicks. Keep an existing client framework when moving its rendering and state to the server would add more work than it removes.

The Alpine.js vs HTMX directory comparison uses a htmx catalog record. Do not treat that record's metrics as verified measurements of the official htmx.org npm package. The decision here rests on documented behavior and your application's state ownership.