npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hx-ext-router

v1.2.0

Published

SPA-like routing and navigation orchestration extension for htmx 4, 2, and 1

Readme

hx-router

An SPA routing, layout outlet, and navigation orchestration extension for htmx (compatible with htmx 4.x, 2.x, and 1.x).

hx-router brings SPA quality-of-life primitives to htmx applications while preserving hypermedia-first architecture. It handles layout outlets, active link state reflection, scroll preservation, view transitions, title syncing, fragment auto-extraction, and screen reader announcements. For resource prefetching, it composes seamlessly with the official preload extension.


Features

  • [hx-viewport] & Named Outlets: Automatically targets default and nested viewports (e.g. <dialog hx-viewport="modal"> via hx-route-to="modal") without requiring manual hx-target on every navigation link. Mutating requests (POST, PUT, DELETE) and non-navigation triggers are safeguarded from viewport hijacking.
  • Full-Page Fragment Auto-Extraction: When the server responds with a full HTML page, hx-router automatically extracts the matching [hx-viewport] fragment—eliminating the need for separate partial endpoints.
  • [hx-nav] & [hx-route-link] Active Link State Sync: Automatically toggles the active class and sets aria-current="page" on matching routes with strict segment and slash-boundary matching. Supports hx-route-match="exact|prefix" and custom per-link classes (hx-active-class="...").
  • Native View Transitions: Automatically enables document.startViewTransition on viewport route swaps with automatic respect for prefers-reduced-motion.
  • Document Title & Accessibility Sync: Seamlessly extracts and updates document.title and announces route changes to assistive tech via an aria-live="polite" region.
  • Scroll Management & History Restoration:
    • Resets window and viewport scroll to (0, 0) on fresh link navigations.
    • Automatically restores window and viewport scroll coordinates on browser Back / Forward (popstate / htmx:historyRestore), avoiding abrupt jumps to top.
    • Smoothly jumps to hash anchors (#id) when present in URLs.
    • [hx-preserve-scroll] preserves granular sub-element scroll positions (e.g. sidebars, table bodies) across transitions.
  • Lifecycle Events: Dispatches semantic hx-router:navigating (cancellable) and hx-router:navigated events for telemetry or analytics.
  • Public JavaScript API: Programmatic utilities via window.htmx.router (updateActiveLinks(), restoreScrollContainers(), etc.).
  • Dual Compatibility & ESM: First-class ESM bundle (dist/hx-router.esm.js), TypeScript declarations (.d.ts), and support for htmx 4.x, 2.x, and 1.x.

Installation

ESM / Bundler (Vite, Webpack, esbuild)

npm install hx-ext-router
import 'hx-ext-router';

The package.json entrypoint defaults to the modern ESM build with full TypeScript definitions.

CDN

<!-- CDN Script Tag (IIFE) -->
<script src="https://cdn.jsdelivr.net/npm/hx-ext-router@latest"></script>

<!-- Or via ESM import in modern browsers -->
<script type="module">
  import 'https://cdn.jsdelivr.net/npm/hx-ext-router@latest/dist/hx-router.esm.js';
</script>

In htmx 4.x, extensions register automatically. In htmx 1.x / 2.x, enable via hx-ext="hx-router".


Usage

1. Viewport Routing & Active Links

Define a layout outlet with hx-viewport. Any boosted link (hx-boost="true") or hx-get link without an explicit hx-target routes directly to the viewport:

<body hx-ext="hx-router, preload">
  <!-- Navigation bar with active link sync and hover prefetching -->
  <nav hx-nav preload="mouseover">
    <!-- Exact match only -->
    <a href="/dashboard" hx-boost="true" hx-route-match="exact">Dashboard</a>
    <!-- Prefix match with custom styling -->
    <a href="/projects" hx-boost="true" hx-active-class="bg-blue-600 text-white">Projects</a>
    <a href="/settings" hx-boost="true">Settings</a>
  </nav>

  <!-- Persistent scrollable sidebar -->
  <aside hx-preserve-scroll="sidebar">
    ...
  </aside>

  <!-- Main Viewport Outlet -->
  <main hx-viewport>
    <!-- Content swaps here automatically -->
  </main>
</body>

2. Named Outlets (Modals / Drawers)

<!-- Routes to the modal viewport instead of the default main viewport -->
<a href="/users/create" hx-route-to="modal" hx-boost="true">Create User</a>

<!-- Modal Dialog Viewport -->
<dialog hx-viewport="modal">
  <!-- Swapped here -->
</dialog>

3. Full-Page Fragment Fallback

If your backend renders full HTML documents (e.g. including <head>, <nav>, <footer>), hx-router inspects the response and automatically extracts the matching [hx-viewport] content. You can write your server routes as ordinary complete web pages without custom partial templates!

4. Lifecycle Events

// Intercept or cancel navigation
document.addEventListener('hx-router:navigating', (e) => {
  console.log('Navigating from:', e.detail.from, 'to:', e.detail.to);
  // Call e.preventDefault() to cancel the navigation
});

// Trigger analytics or post-swap logic
document.addEventListener('hx-router:navigated', (e) => {
  console.log('Navigated to:', e.detail.url);
});

Configuration

Options can be customized via htmx.config.router:

htmx.config.router = {
  activeClass: 'active',         // Class added to matched route links
  ariaCurrent: 'page',           // aria-current value for exact route matches
  morph: true,                   // Use innerMorph for viewport swapping
  viewTransitions: true,         // Enable native View Transitions (honors prefers-reduced-motion)
  syncTitle: true,               // Extract <title> from response and update document.title
  routingClass: 'hx-routing',    // Class added to viewport during navigation
  scrollReset: true,             // Reset scroll to top on fresh page navigation
  historyScrollRestoration: true,// Restore window & viewport scroll on back/forward buttons
  scrollHash: true,              // Scroll to #hash element if present in URL
  announceTitle: true,           // Screen reader aria-live announcements on route changes
  autoExtractFragment: true      // Extract [hx-viewport] if server sends full HTML
};

License

MIT