htmx
Let the server validate each step, and move the flow when it says so.
With htmx the server owns validation. Each step's form posts on its own; the server answers with the form again, and says in a response header when the step was accepted.
The page
<div data-component="stepper" id="signup">
<ol data-component="stepper-list">
<li data-component="stepper-item" data-step="account">
<button data-component="stepper-trigger">Account</button>
</li>
<li data-component="stepper-item" data-step="plan">
<button data-component="stepper-trigger">Plan</button>
</li>
</ol>
<div data-component="stepper-content" data-step="account">
<form hx-post="/signup/account" hx-swap="outerHTML">
<input name="email" type="email" />
<button>Continue</button>
</form>
</div>
<div data-component="stepper-content" data-step="plan" hidden>
<form hx-post="/signup/plan" hx-swap="outerHTML">…</form>
</div>
</div>import { createStepper } from "@stepperize/core";
import { bindStepper } from "@stepperize/core/dom";
const root = document.getElementById("signup")!;
const flow = createStepper([{ id: "account", title: "Account" }, { id: "plan", title: "Plan" }], {
linear: true,
});
// Linear: an ordered list of steps, where only `next()` moves forward.
bindStepper(root, flow);
// The server triggers this event when it accepts a step.
root.addEventListener("stepper:next", () => flow.next());The server
- Invalid: respond
200with the form re-rendered, errors included. htmx swaps it in and the flow stays where it is. (htmx 2 does not swap4xxresponses unless you configureresponseHandling.) - Valid: respond with the header
HX-Trigger: stepper:next(and the form, or its saved state, as the body). As soon as the response arrives, htmx firesstepper:nexton the form that made the request; it bubbles to the root, and the flow moves on.
HTTP/1.1 200 OK
HX-Trigger: stepper:next
Content-Type: text/html
<form hx-post="/signup/account" hx-swap="outerHTML">…</form>Because the flow is linear, the next step's trigger stays disabled until the
server has accepted the current one. Swapping a form costs the stepper nothing,
and any stepper part htmx swaps in is part of the stepper as soon as it lands;
there is nothing to re-bind.
Loading panels on demand
A panel can fetch its content the first time its step is shown. Fire an event on the panel when its step becomes current, and let htmx listen for it once:
<div
data-component="stepper-content"
data-step="plan"
hidden
hx-get="/signup/plan"
hx-trigger="step-shown once"
></div>flow.subscribe(() => {
const panel = root.querySelector(`[data-component="stepper-content"][data-step="${flow.current.id}"]`);
// htmx listens with addEventListener: a plain DOM event is enough.
panel?.dispatchEvent(new Event("step-shown"));
});bindStepper subscribed first, so the panel is no longer hidden when the
event fires.
Finishing
next() on the last step finishes the flow and calls onFinish. Redirect
there, or let the last form's response do it with HX-Redirect.
Last updated on