Web Development · Nov 24, 2026 · 12 min read

HTMX 2.0 with Next.js 15: Server Actions, SSE and Zero-Bundle UIs

Hands-on guide to integrating HTMX 2.0 with Next.js 15 App Router. Learn practical patterns for forms, infinite scroll, real-time updates via Server Sent Events, progressive enhancement, and when to c

HTMX 2.0 with Next.js 15: Server Actions, SSE and Zero-Bundle UIs

HTMX 2.0 Core Concepts That Pair Naturally with Next.js

HTMX 2.0 extends HTML with attributes that let any element issue HTTP requests and swap content directly in the DOM. The version 2.0 release brought improved extension support, better WebSocket and SSE handling, and more granular control over request headers and events.

Next.js 15's App Router, Server Actions, and Partial Prerendering complement HTMX perfectly. You can render initial HTML on the server, attach HTMX attributes, and let the browser handle interactivity without shipping large React client bundles for every component.

Key attributes you will use daily:

  • hx-get, hx-post, hx-put, hx-delete — define the HTTP method and target URL
  • hx-swap — controls how incoming HTML replaces existing content (innerHTML, outerHTML, beforebegin, etc.)
  • hx-target — CSS selector for the element that should receive the response
  • hx-trigger — when the request should fire (click, load, changed, every 5s, etc.)
  • hx-on — new in v2 for inline event handling without separate scripts

These attributes work on any HTML element and degrade gracefully when JavaScript is disabled, delivering true progressive enhancement.

Project Setup with Next.js 15 and HTMX 2.0

Start with the latest Next.js:

npx create-next-app@latest htmx-next-demo \
  --typescript --tailwind --eslint --app --yes
cd htmx-next-demo

Install HTMX via CDN for simplicity or bundle it. For production, the recommended approach is to import it from htmx.org or use the official npm package and serve it statically.

npm install htmx.org@2.0.3

In your root layout (app/layout.tsx), include the HTMX script:

import Script from 'next/script';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src="https://unpkg.com/htmx.org@2.0.3/dist/htmx.min.js"
          strategy="afterInteractive"
        />
      </body>
    </html>
  );
}

Next.js 15 automatically optimizes this script. For self-hosting, copy the minified file to public/js/htmx.js and reference it locally to remove external dependency.

Basic Pattern: Loading Partial Content on Interaction

Consider a dashboard that loads user statistics only when the user clicks a tab. Traditional React would use useState and useEffect. With HTMX you write plain HTML.

Create a route handler at app/stats/route.ts:

import { NextRequest } from 'next/server';

export async function GET(request: NextRequest) {
  const userId = request.nextUrl.searchParams.get('userId');
  
  // Simulate database call
  await new Promise(resolve => setTimeout(resolve, 300));
  
  return new Response(`
    <div class="grid grid-cols-3 gap-4">
      <div class="bg-zinc-900 p-6 rounded-xl">
        <p class="text-emerald-400 text-sm">Revenue</p>
        <p class="text-4xl font-semibold mt-2">$24,892</p>
      </div>
      <!-- two more cards -->
    </div>
  `, {
    headers: { 'Content-Type': 'text/html' }
  });
}

In your page component you reference it:

<button 
  hx-get="/stats?userId=123"
  hx-target="#stats-container"
  hx-swap="innerHTML"
  class="px-5 py-2 bg-white text-black rounded-lg font-medium">
  Load Stats
</button>

<div id="stats-container" class="mt-8">
  <!-- content appears here -->
</div>

This pattern eliminates client-side JavaScript for simple data loading. The server returns HTML fragments directly, which HTMX inserts into the DOM.

Forms with Server Actions and HTMX Feedback

Next.js Server Actions pair beautifully with HTMX. You get progressive enhancement, server-side validation, and inline feedback without React state management.

Define a Server Action in app/actions.ts:

'use server';

import { z } from 'zod';

const ContactSchema = z.object({
  email: z.string().email(),
  message: z.string().min(10),
});

export async function submitContact(formData: FormData) {
  const data = ContactSchema.parse({
    email: formData.get('email'),
    message: formData.get('message'),
  });
  
  // Save to database here
  await new Promise(resolve => setTimeout(resolve, 800));
  
  return { success: true, message: 'Message received. Thank you.' };
}

The form in your page component:

<form 
  hx-post="/contact"
  hx-swap="outerHTML"
  class="space-y-6">
  <input 
    type="email" 
    name="email"
    placeholder="your@email.com"
    class="w-full px-4 py-3 bg-zinc-900 border border-zinc-700 rounded-lg"
    required />
    
  <textarea 
    name="message"
    rows={5}
    class="w-full px-4 py-3 bg-zinc-900 border border-zinc-700 rounded-lg"
    required></textarea>
    
  <button 
    type="submit"
    class="px-8 py-3 bg-emerald-500 hover:bg-emerald-600 transition-colors rounded-lg font-semibold">
    Send Message
  </button>
</form>

Create the route handler that executes the Server Action and returns updated HTML including success state or validation errors. This gives instant visual feedback without full page reloads while keeping logic entirely on the server.

Infinite Scroll Implementation

Infinite scroll is a classic use case for HTMX. The pattern uses hx-trigger="revealed" on a sentinel element at the bottom of the list.

Server component that returns a chunk of items:

// app/items/route.ts
export async function GET(request: NextRequest) {
  const page = parseInt(request.nextUrl.searchParams.get('page') || '0');
  const items = await db.items.findMany({
    take: 20,
    skip: page * 20,
    orderBy: { createdAt: 'desc' }
  });
  
  const hasMore = items.length === 20;
  
  return new Response(`
    ${items.map(item => `
      <div class="border border-zinc-800 p-6 rounded-2xl mb-4">
        <h3 class="font-semibold">${item.title}</h3>
        <p class="text-zinc-400">${item.description}</p>
      </div>
    `).join('')}
    
    ${hasMore ? `
      <div 
        hx-get="/items?page=${page + 1}"
        hx-trigger="revealed"
        hx-swap="outerHTML"
        class="h-4"></div>
    ` : ''}
  `, {
    headers: { 'Content-Type': 'text/html' }
  });
}

This approach loads 20 items at a time. The sentinel div triggers when it scrolls into view, automatically fetching the next page and replacing itself with new content and the next sentinel. No IntersectionObserver boilerplate required.

Real-Time Updates with Server Sent Events

HTMX 2.0 has excellent native support for Server Sent Events through the hx-sse attribute (via the official SSE extension).

First, install the extension by including it from unpkg:

<script src="https://unpkg.com/htmx.org@2.0.3/dist/ext/sse.js"></script>

Server route that streams updates (app/live/route.ts):

export async function GET() {
  const stream = new ReadableStream({
    async start(controller) {
      const encoder = new TextEncoder();
      
      setInterval(() => {
        const payload = {
          time: new Date().toLocaleTimeString(),
          metric: Math.floor(Math.random() * 100)
        };
        
        controller.enqueue(encoder.encode(
          `event: update\ndata: ${JSON.stringify(payload)}\n\n`
        ));
      }, 2500);
    }
  });
  
  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
    },
  });
}

Client HTML that listens to the stream:

<div 
  hx-ext="sse"
  sse-connect="/live"
  sse-swap="update"
  class="bg-zinc-900 p-8 rounded-3xl text-center">
  <p id="live-value" class="text-6xl font-mono text-emerald-400">—</p>
</div>

When the server sends an update event, HTMX automatically swaps the content of the element with the returned HTML fragment. This creates live dashboards with under 30 lines of code total.

State Management Without React useState

HTMX uses the DOM as the source of truth. You store temporary state in HTML attributes or hidden inputs and let the server render the correct UI.

Example of a toggleable panel:

<button 
  hx-get="/panel?expanded=true"
  hx-target="#panel"
  hx-swap="outerHTML"
  class="flex items-center gap-2">
  <span>Advanced Options</span>
  <span class="text-xl transition-transform">›</span>
</button>

<div id="panel" class="hidden">
  <!-- content -->
</div>

The server returns the expanded version with different classes and content when the expanded=true parameter is present. This removes most client-side state management code.

Authentication and Protected Routes

Combine HTMX with Next.js middleware or Server Actions that check authentication. Because HTMX sends standard HTTP requests with cookies, you can use the same session logic you already have.

For protected actions, return different HTML fragments based on auth status:

  • Authenticated user sees the form or data
  • Unauthenticated user receives a login prompt HTML fragment that HTMX swaps in

This keeps users inside the same page flow instead of redirecting to a separate login page.

Styling with Tailwind CSS and HTMX

HTMX does not conflict with Tailwind. You can use arbitrary variants and the full utility class system. Common pattern is to add loading states using the htmx-request class that HTMX automatically adds to elements in flight.

<button 
  hx-post="/save"
  class="px-6 py-3 bg-violet-600 hover:bg-violet-700 
         htmx-request:opacity-70 htmx-request:cursor-wait
         transition-all rounded-2xl font-medium">
  <span class="htmx-request:hidden">Save Changes</span>
  <span class="hidden htmx-request:inline">Saving...</span>
</button>

This provides instant UI feedback during requests without custom JavaScript.

Performance Trade-offs and Bundle Size

Using HTMX with Next.js typically reduces client-side JavaScript by 60-90% for content-heavy applications. A typical marketing site or internal tool built this way ships under 15 KB of JavaScript compared to 120 KB+ for an equivalent React-heavy implementation.

Trade-offs include:

  • Logic lives on the server, increasing server load for highly interactive UIs
  • Complex client-side interactions (drag-and-drop, canvas) still require vanilla JS or small libraries
  • Debugging requires understanding both server rendering and HTMX's DOM swaps
  • Testing is different — you test HTML responses rather than component behavior

For most CRUD, dashboards, and content sites the trade-off is heavily in favor of HTMX.

Complete Worked Example: Task Manager

Let's build a functional task manager using only HTMX, Next.js Server Actions, and Tailwind. The complete implementation consists of four routes:

  1. app/page.tsx — main view that loads the task list
  2. app/tasks/route.ts — returns list fragments
  3. app/actions.ts — Server Actions for create, toggle, delete
  4. app/add/route.ts — form fragment for adding new tasks

The main page starts with an initial server-rendered list. Users can add tasks via a form that uses hx-post and returns the updated list plus a cleared form. Each task row contains buttons that trigger hx-delete or hx-put and replace the entire row with the updated version from the server.

Key code for the toggle action:

export async function toggleTask(id: string, completed: boolean) {
  // update database
  const task = await db.task.update({
    where: { id },
    data: { completed }
  });
  
  return `
    <div class="flex items-center justify-between px-6 py-4 border border-zinc-800 rounded-2xl">
      <div class="${task.completed ? 'line-through text-zinc-500' : ''}">
        ${task.title}
      </div>
      <button 
        hx-put="/tasks/${task.id}/toggle"
        hx-swap="outerHTML"
        class="w-7 h-7 flex items-center justify-center border-2 rounded-full 
               ${task.completed ? 'bg-emerald-500 border-emerald-500' : 'border-zinc-400'}">
        ${task.completed ? '✓' : ''}
      </button>
    </div>
  `;
}

This single file contains both the data mutation and the HTML representation, keeping concerns close together. The entire task manager ships with less than 8 KB of JavaScript (only HTMX itself).

Extensions and Advanced HTMX 2.0 Features

HTMX 2.0 ships with official extensions for:

  • Server Sent Events (ext/sse)
  • WebSockets (ext/ws)
  • JSON encoding (ext/json-enc)
  • Response headers for triggering client events (hx-trigger with headers)

You can load these extensions individually so you only pay the bundle cost for features you actually use. The WebSocket extension allows bidirectional communication for collaborative features without writing custom Socket.io client code.

Security Considerations

Because HTMX issues real HTTP requests, you must apply the same protections as any server API:

  • Always validate and sanitize inputs on the server using Zod or similar
  • Use CSRF tokens for mutating requests (Next.js middleware can inject them automatically)
  • Set proper Content-Security-Policy headers that allow unsafe-inline for HTMX if using inline handlers, or move to external scripts
  • Limit response sizes for hx-boost scenarios

Next.js 15's built-in request deduplication and caching work transparently with HTMX GET requests.

When to Choose HTMX vs React Server Components

Use HTMX when:

  • You want minimal JavaScript for better Core Web Vitals scores
  • Building internal tools, admin panels, or content sites
  • Your team has stronger backend than frontend skills
  • Progressive enhancement and accessibility are priorities

Use React Server Components when:

  • You need complex client-side interactions (drag-drop, real-time collaborative editing, heavy animations)
  • Your UI has deeply interconnected state
  • You already have a large React codebase and team expertise

Many applications work best as hybrids: use React Server Components for complex dashboards and HTMX for simpler forms and lists. Next.js makes this mix straightforward.

Testing HTMX-Driven Applications

Because most logic lives in HTML responses and Server Actions, you can test at multiple levels:

  1. Unit test Server Actions with Vitest by calling them directly with FormData objects
  2. Integration test HTML fragments by asserting on specific element IDs and classes
  3. End-to-end test with Playwright by simulating user clicks and verifying DOM changes (HTMX works perfectly with Playwright since it uses real browser events)

Example Vitest test for a Server Action:

test('toggleTask updates and returns correct HTML', async () => {
  const html = await toggleTask('task-123', true);
  expect(html).toContain('line-through');
  expect(html).toContain('bg-emerald-500');
});

Production Deployment Considerations

When deploying to Vercel, HTMX applications benefit from Edge caching of static fragments. Use route segment config to control caching:

export const dynamic = 'force-dynamic'; // for live data
// or
export const revalidate = 60; // for semi-static content

Monitor server response times closely since each user interaction generates a server round-trip. Implement proper database indexing and query optimization. For high-traffic applications, add Redis caching for expensive HTML fragments using Next.js cache API.

Bundle analysis shows typical production builds under 45 KB total (including Tailwind), leading to sub-100 ms Time to Interactive on 3G networks.

Migration Strategy from React-Heavy to HTMX

You do not need to rewrite everything at once. Start by identifying leaf components with low client-side interactivity (profile forms, settings pages, comment sections) and replace them with HTMX equivalents one by one. Keep React for the shell of the application if needed.

Many teams adopt an "HTML-first" philosophy for new features while maintaining existing React code. Over time the JavaScript bundle shrinks and perceived performance improves dramatically.

The combination of Next.js 15's streaming, Partial Prerendering, and HTMX 2.0 represents one of the most productive stacks available today for building fast, maintainable, and accessible web applications with minimal frontend complexity.

Keep reading

Related Articles