Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 28 ยท HTMX in Practice

URLs, History and Navigation

Keep the address bar and Back button working with HTMX: hx-push-url, hx-replace-url, history snapshots, hx-boost and URLs that work without JavaScript.

A normal website has a superpower that single-page apps must rebuild by hand: every screen has a URL. You can copy it, bookmark it, email it, reload it, and press the Back button to return to it. When HTMX swaps a fragment into the page, the address bar does not change by itself, so after the third "next page" click the URL still says page one. Reload, and the user is back at the start.

HTMX has a small, deliberate toolbox to fix this: attributes that put URLs into the browser's history, a snapshot cache that makes Back and Forward fast, and hx-boost, which upgrades ordinary links and forms. This lesson explains each, and, more importantly, how to design your URLs so the site works with and without JavaScript.

The preview sandbox in this track has an opaque origin: it cannot change the address bar, and it cannot use localStorage, which HTMX uses for its snapshot cache. So the history features themselves cannot run in the live editors here. The examples below use a clearly labelled stand-in address bar that listens to the event HTMX fires just before it updates history. The attributes are exactly what you would write on a real page.

Four history tools

hx-push-url Add the URL as a new history entry.
hx-replace-url Change the URL without a new entry.
Snapshots HTMX saves the page so Back is instant.
hx-boost Turn links and forms into AJAX.
1 / 2

hx-push-url and hx-replace-url

Add hx-push-url="true" to an element that issues a request, and after the swap HTMX calls the browser's history.pushState with the request URL, including its query string. The address bar now shows /products?page=2, Back goes to /products, and reload fetches page 2 from the server.

HTML
<a href="/products?page=2"
   hx-get="/products?page=2"
   hx-target="#content"
   hx-push-url="true">Next page</a>
  • hx-push-url="/some/other/path" pushes a URL of your choosing, useful when the request URL is a fragment route such as /partials/products but the user-facing URL is /products.
  • hx-push-url="false" prevents a push (for example when hx-boost would add one).
  • hx-replace-url works the same way but calls replaceState: the URL changes, but no new history entry is created. Use it for small refinements, such as typing into a search box, where ten Back presses to undo ten keystrokes would be absurd.
  • The server can decide instead, with the HX-Push-Url and HX-Replace-Url response headers (a URL, or false).

The stand-in below shows the effect. The fake address bar and the "history" list are updated from the htmx:beforeHistoryUpdate event, which HTMX fires with the path it is about to push or replace. The Back button restores the content that was on screen for the previous entry, like HTMX's own snapshot cache does.

A stand-in address bar for hx-push-url

Click "Page 2 (push)": the fake address bar changes and the history list grows. "Sort by price (replace)" changes the bar but does not add an entry. "Page 3" swaps the content and leaves the URL alone, which is the situation after every HTMX request that has no history attribute. Press the back arrow to see the previous screen return.

Snapshots and the Back button

When HTMX pushes a new entry, it first saves a snapshot of the current page into a cache (in localStorage, up to htmx.config.historyCacheSize, ten entries by default). When the user presses Back, HTMX finds the snapshot for that URL and restores it instantly, with no request. If the snapshot is missing, HTMX requests the URL from the server with the header HX-History-Restore-Request: true and swaps the response in as the whole page.

flowchart TD
    A["User presses Back"] --> B{"Snapshot in cache?"}
    B -->|"yes"| C["Restore HTML instantly"]
    B -->|"no"| D["GET url with HX-History-Restore-Request"]
    D --> E["Server returns FULL page"]
    E --> F["HTMX swaps the page into body"]
    C --> G["htmx:historyRestore"]
    F --> G

Back restores from the cache when it can and falls back to a normal full-page request.

Three consequences matter in practice:

  1. A URL must be able to return a full page. The cache miss path (and any reload or shared link) asks for a complete document. If your /products?page=2 route only returns a fragment, Back after a cache miss shows a broken page. Fix this by having the same route return the fragment when the request has the HX-Request header and not HX-History-Restore-Request, and the full page otherwise.
  2. Sensitive content should not be snapshotted. Put hx-history="false" on an element of a page that shows private data; that page is never saved into the cache (a miss will reload it from the server instead).
  3. Snapshots include the DOM at the moment of leaving. Widgets that mutate the DOM (open dropdowns, date pickers) are saved in their current state. Listen for htmx:beforeHistorySave to clean them up first, and for htmx:historyRestore to re-initialize things afterwards. By default the snapshot is the whole <body>; mark a smaller region with hx-history-elt.

Designing URLs that work without JavaScript

The best HTMX sites are written as ordinary server-rendered sites first. Each screen has a URL, each link has a real href, each form has a real action. HTMX is then progressive enhancement: with JavaScript, it swaps only the fragment; without it (or when the script fails to load, or a crawler visits), the browser follows the link and receives the full page from the very same URL.

The server needs to answer the same URL in two shapes. It tells them apart by looking at the HX-Request header:

One URL, two answers

Click the link: HTMX sends HX-Request: true and the server answers with just the list. Press the button, which behaves like a browser opening the URL directly (or a search engine crawling it): the same URL returns a complete document with header and footer. One route, one URL, two renderings.

Tell caches that the answer depends on the header: send Vary: HX-Request on routes that return different content for it. Without it, a CDN or the browser cache may store the fragment and later hand it out as if it were the full page.

Put state in the URL

Anything the user might want to share or return to belongs in the URL: page number, search term, sort order, selected filters. Use query strings (/products?category=tea&sort=price&page=2) rather than hidden state. Then reload, Back, bookmarks and shared links all work, and your server renders the right page from the URL alone. State that only matters for a moment (is the dropdown open?) stays out of the URL and belongs in Alpine.

hx-boost="true" is the cheapest enhancement of all. Put it on a container, usually <body>, and HTMX converts the links and forms inside it:

HTML
<body hx-boost="true">
  <nav>
    <a href="/">Home</a>
    <a href="/blog">Blog</a>
    <a href="/contact" hx-boost="false">Contact (normal navigation)</a>
  </nav>
  ...
</body>
  • A boosted link issues a GET with AJAX, targets <body> with innerHTML, updates the <title>, and pushes the URL into history. A boosted form does the same with its method.
  • The server returns full pages as usual and HTMX swaps only the body, so the browser does not re-download CSS and JavaScript or re-parse the head. Navigation feels much faster, with zero changes to the server.
  • Only links that stay on the same site are boosted; links to other origins, target="_blank" links and #anchor links are left alone. Opt out for one element with hx-boost="false".
  • Boosted requests carry the header HX-Boosted: true, so the server can render a slimmer layout if it wants to.
  • Without JavaScript, everything is still an ordinary link or form, which is the whole point.

hx-boost depends on the History API, so it cannot run inside the preview sandbox; on a real page you would try it by adding the attribute to <body>.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A "next page" link swaps a list with HTMX. What makes the address bar show the new page URL?

    HTMX does not touch the address bar unless you ask. hx-push-url pushes the request URL into history after the swap.
  2. 2. How does hx-replace-url differ from hx-push-url?

    replaceState swaps the current entry's URL, so Back does not step through every small refinement.
  3. 3. What must a route returning a fragment also be able to do, so that Back, reload and shared links work?

    Cache misses, reloads and crawlers ask for the URL like a normal browser, so the same URL needs a full-page rendering.
  4. 4. Which attribute stops a page with private data from being saved into HTMX's history snapshot cache?

    hx-history="false" on an element of the page prevents the snapshot from being stored.
  5. 5. What does hx-boost="true" on the body do to a normal same-site link?

    Boosted links become AJAX GET requests that swap the body and update history, and they still work without JavaScript.

Summary

  • HTMX leaves the address bar alone unless you add hx-push-url (new entry) or hx-replace-url (same entry), or the server sends HX-Push-Url / HX-Replace-Url.
  • Before pushing, HTMX snapshots the page; Back restores the snapshot or falls back to a full-page request with HX-History-Restore-Request.
  • Every URL should return a full page on its own and a fragment for HTMX requests; add Vary: HX-Request for caches.
  • Put shareable state (page, filters, sort) in the query string; keep momentary UI state in Alpine.
  • hx-boost upgrades same-site links and forms to AJAX body swaps and keeps working without JavaScript.
  • History features cannot run in the sandbox, so this lesson used a stand-in address bar; the attributes are the real ones.

Continue with Using HTMX and Alpine.js Together.