Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 28 ยท Practice and Review

Common Mistakes and Debugging

Fix the usual HTMX and Alpine.js bugs: missing x-data, x-for without template, x-cloak flashes, bad hx-target, 4xx and 5xx not swapping, plus debugging tips.

Most bugs in HTMX and Alpine.js pages are not deep. They are one missing attribute, one misspelled selector or one forgotten rule. The trouble is that both libraries are forgiving: a mistake often produces no error on the page at all, just a button that does nothing. Knowing where to look saves hours.

This lesson walks through the mistakes people make most often, shows each one broken and fixed, and ends with a debugging toolkit and an accessibility checklist. If you have not seen them yet, skim Reactive State with x-data and Targets and Swap Strategies first.

Where bugs hide

Alpine scope x-data missing or in the wrong place.
HTMX target A selector that matches nothing.
Status codes Errors are not swapped by default.
Accessibility Focus, live regions, keyboard.
1 / 2

Alpine.js mistakes

Mistake 1: no x-data around the directive

Alpine only evaluates directives inside an element that has x-data. Outside it, x-text="count" has nothing to read, and you get a console error such as count is not defined. The data belongs on an ancestor of every element that uses it.

Missing scope vs fixed

In the first box the number never changes, because @click="n++" runs outside the scope and fails silently except for a console error. In the second box the wrapper owns both. A related trap: two components never share data unless you use a store or events.

Mistake 2: x-for without a template

x-for must be on a <template> tag, and the template must contain exactly one root element. Putting it on an <li> directly is the most common error.

HTML
<!-- Wrong -->
<li x-for="t in tags" x-text="t"></li>

<!-- Right -->
<template x-for="t in tags" :key="t">
  <li x-text="t"></li>
</template>

The same rule applies to x-if. Both need <template> because they add and remove whole chunks of the page, and the browser does not render template content until Alpine copies it. Details in Conditionals and Loops.

Mistake 3: the flash of unstyled content

Alpine starts after the page loads. For a split second you may see elements that x-show="false" is supposed to hide, such as a modal or a dropdown. The cure is x-cloak plus one CSS rule:

HTML
<style>[x-cloak] { display: none !important; }</style>

<div x-show="open" x-cloak>I am hidden from the very first paint.</div>

Alpine removes the x-cloak attribute once it has initialized the element. Without the CSS rule, the attribute does nothing, so remember both parts.

Mistake 4: mutating a value Alpine cannot see

Alpine's reactivity wraps your data in a proxy. If you keep a reference to the plain object and change that instead, the page does not update. Inside the component, always change values through this (in methods) or the property name (in expressions), and replace or push onto arrays held in the data, not on a separate copy.

Mistake 5: initializing twice

If you add x-data to an element that sits inside another x-data, you create a child scope that can read the parent's data, but a variable with the same name in the child shadows the parent's. A different version of the problem happens with swapped HTML: a fragment that HTMX inserts into an Alpine component is initialized by Alpine through its mutation observer, so you should not call Alpine.initTree yourself. Calling it again would run x-init twice. Using HTMX and Alpine.js Together covers this properly.

HTMX mistakes

Mistake 6: an hx-target that matches nothing

HTMX does not guess. If the selector in hx-target finds no element, the response is thrown away and the library fires an htmx:targetError event. A typo in an id is the usual cause. The browser console prints the error, so look there first.

HTML
<button hx-get="/news" hx-target="#new">Load</button>   <!-- the box is #news -->
<div id="news"></div>

Extended selectors have their own spelling: closest tr, find .name, next .error, previous section, this. A missing space or a wrong keyword fails in the same silent way.

Mistake 7: 4xx and 5xx responses are not swapped

By default HTMX 2 swaps only successful responses (2xx). A 404, a 422 validation error or a 500 fires htmx:responseError and leaves the page as it was. Developers often see this as "my error message never shows up". Try it:

404 and 422 do not swap by default

The second button prints a log line only. The third button flips shouldSwap in htmx:beforeSwap, so HTMX shows the validation message. In a real project you can do this once for all pages (htmx.config.responseHandling in htmx 2) so that 422 is always swapped. The full story is in Events, Headers and JavaScript Integration.

Mistake 8: the wrong swap

The default swap is innerHTML: the response goes inside the target. If your server returns a complete element and you target that same element, you get a nested copy. Two quick rules:

  • Server returns the contents? Use the default, or beforeend/afterbegin to add to a list.
  • Server returns the whole element to replace? Add hx-swap="outerHTML".

Another trap: a response that contains a whole HTML page (with <html> and <head>). Return a fragment, or use hx-select to pick the part you want.

Mistake 9: new content that HTMX does not know

HTMX processes attributes in swapped-in content automatically. Content you add yourself with innerHTML = ... or insertAdjacentHTML is not processed. Call htmx.process(element) after you insert it, and the new hx-* attributes come alive.

Mistake 10: forgetting name on inputs

HTMX sends what a browser form would send, and form fields without a name attribute are never sent. If request.form.email is empty on the server, check the name first.

Debugging toolkit

HTMX tools

htmx.logAll() Prints every HTMX event to the console.
Network tab Check request headers and the raw response.
HX-Request The header your server can test for.
1 / 2

htmx.logAll

Run htmx.logAll() in the browser console before you click. HTMX then logs every event it triggers (htmx:configRequest, htmx:beforeRequest, htmx:beforeSwap, htmx:afterSwap, and more) with its details. If you see htmx:targetError or htmx:responseError, you have your answer. Call htmx.logger = null to stop.

Watch HTMX events in a log

htmx.logger is the hook that logAll sets to console.log; here we write to the page instead, because our preview has no visible console for the page itself. Note that every request goes through the same chain: before request, after request, before swap, after swap.

Alpine from the console

In the console, Alpine.$data(document.querySelector('[x-data]')) returns the state of that component, and you can assign to it to test an idea (Alpine.$data(el).open = true). Inside a template, x-effect="console.log(count)" logs each time count changes. The official browser extension (Alpine.js devtools) lists components and their data.

Devtools and the console are not available inside our sandboxed previews, so those tips are for your own pages. Everything else in this lesson runs here.

Accessibility pitfalls

Both libraries change the page after load, which can leave keyboard and screen-reader users behind. Check these:

  • Use real buttons and links. A <div @click> is not focusable and ignores the keyboard. Use <button>, or the right element for navigation.
  • Announce updates. Content swapped in by HTMX is silent to a screen reader unless its container is a live region: aria-live="polite" for status text, role="alert" for errors.
  • Manage focus. When a modal opens, move focus into it, and when it closes, return focus to the button that opened it. When HTMX replaces the element that had focus, the focus is lost; give the replacement the same id so HTMX can restore it, or set focus yourself in htmx:afterSwap.
  • Keep Escape working. Menus and dialogs should close on Escape (@keydown.escape.window).
  • Reflect state in ARIA. Pair a toggle with :aria-expanded="open", and the controlled panel with an id referenced by aria-controls.
  • Do not rely on hover or color alone.
A live region for HTMX results

The role="status" container exists in the page before the swap, which is the important part: screen readers announce changes to a live region that is already present.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A button with @click="count++" does nothing and the console says count is not defined. What is the most likely cause?

    Alpine only evaluates directives inside an x-data scope. Move the data to a common ancestor of every element that needs it.
  2. 2. Your server returns a 422 response with an error message, but nothing appears. Why?

    By default only successful responses are swapped. Handle htmx:beforeSwap (or configure response handling) to swap error responses.
  3. 3. Where must x-for be placed?

    x-for clones the content of a template once per item, so the template needs exactly one root element.
  4. 4. What does htmx.logAll() do?

    logAll sets htmx.logger to console.log, so every event is printed with its details.

Summary

  • Directives only work inside an x-data scope; x-for and x-if need a <template>; use x-cloak with its CSS rule.
  • An hx-target that matches nothing swaps nothing and fires htmx:targetError.
  • 4xx and 5xx responses are not swapped by default; handle htmx:beforeSwap or configure it.
  • Choose innerHTML for contents and outerHTML for whole elements; call htmx.process for HTML you inserted yourself; inputs need name.
  • Debug with the console, the Network tab, htmx.logAll() and Alpine.$data.
  • Keep pages accessible: real buttons, live regions, managed focus and Escape.

Next: Interview Questions