| 1 | --- |
| 2 | name: htmx-extension-authoring |
| 3 | description: Use when creating, modifying, or debugging htmx 4 extensions. Covers the event-based extension API, internal API, lifecycle hooks, and distribution patterns. |
| 4 | argument-hint: "[description of extension behavior]" |
| 5 | --- |
| 6 | |
| 7 | # Building htmx 4 Extensions |
| 8 | |
| 9 | htmx 4 extensions hook into lifecycle events via `htmx.registerExtension()`. |
| 10 | Extensions are global -- they apply page-wide, activated by custom attributes where needed. |
| 11 | |
| 12 | ## Extension Boilerplate |
| 13 | |
| 14 | ```javascript |
| 15 | (() => { |
| 16 | let api; |
| 17 | |
| 18 | htmx.registerExtension('my-ext', { |
| 19 | init: (internalAPI) => { |
| 20 | api = internalAPI; |
| 21 | }, |
| 22 | |
| 23 | htmx_after_init: (elt, detail) => { |
| 24 | // Check for your custom attribute |
| 25 | let value = api.attributeValue(elt, "hx-my-attr"); |
| 26 | if (!value) return; |
| 27 | // Initialize behavior for this element |
| 28 | }, |
| 29 | |
| 30 | htmx_before_request: (elt, detail) => { |
| 31 | // Modify request before sending |
| 32 | // detail.ctx has request info |
| 33 | // Return false to cancel |
| 34 | }, |
| 35 | |
| 36 | htmx_after_request: (elt, detail) => { |
| 37 | // After request completes |
| 38 | // detail.ctx.text has response text |
| 39 | // detail.ctx.response has status, headers |
| 40 | }, |
| 41 | |
| 42 | htmx_before_swap: (elt, detail) => { |
| 43 | // Before content swap |
| 44 | }, |
| 45 | |
| 46 | htmx_after_swap: (elt, detail) => { |
| 47 | // After content swap |
| 48 | }, |
| 49 | |
| 50 | htmx_before_cleanup: (elt, detail) => { |
| 51 | // Clean up event listeners, timers, etc. |
| 52 | }, |
| 53 | }); |
| 54 | })(); |
| 55 | ``` |
| 56 | |
| 57 | ## Loading Extensions |
| 58 | |
| 59 | Include the script after htmx.js. Optionally restrict which extensions can register: |
| 60 | |
| 61 | ```html |
| 62 | <script src="/path/to/htmx.js"></script> |
| 63 | <script src="/path/to/hx-my-ext.js"></script> |
| 64 | <meta name="htmx-config" content='{"extensions": "my-ext"}'> |
| 65 | ``` |
| 66 | |
| 67 | When the `extensions` config is set, only listed extensions load. Without it, all registered extensions are active. |
| 68 | |
| 69 | ## Event Hooks Reference |
| 70 | |
| 71 | Hook names use underscores (not colons). All hooks receive `(elt, detail)` unless noted. |
| 72 | |
| 73 | ### Core Lifecycle |
| 74 | |
| 75 | | Hook | Event | Description | |
| 76 | |------|-------|-------------| |
| 77 | | `htmx_before_init` | `htmx:before:init` | Before element initialization | |
| 78 | | `htmx_after_init` | `htmx:after:init` | After element initialization | |
| 79 | | `htmx_before_process` | `htmx:before:process` | Before processing element | |
| 80 | | `htmx_after_process` | `htmx:after:process` | After processing element | |
| 81 | | `htmx_before_cleanup` | `htmx:before:cleanup` | Before cleaning up element | |
| 82 | | `htmx_after_cleanup` | `htmx:after:cleanup` | After cleaning up element | |
| 83 | |
| 84 | ### Request Lifecycle |
| 85 | |
| 86 | | Hook | Event | Description | |
| 87 | |------|-------|-------------| |
| 88 | | `htmx_config_request` | `htmx:config:request` | Configure request (modify headers, body, URL) | |
| 89 | | `htmx_before_request` | `htmx:before:request` | Before request is sent | |
| 90 | | `htmx_before_response` | `htmx:before:response` | After fetch response, before body consumed | |
| 91 | | `htmx_after_request` | `htmx:after:request` | After request completes | |
| 92 | | `htmx_finally_request` | `htmx:finally:request` | Always fires after request (like `finally`) | |
| 93 | | `htmx_error` | `htmx:error` | On any error | |
| 94 | |
| 95 | ### Swap |
| 96 | |
| 97 | | Hook | Event | Description | |
| 98 | |------|-------|-------------| |
| 99 | | `htmx_before_swap` | `htmx:before:swap` | Before content swap | |
| 100 | | `htmx_after_swap` | `htmx:after:swap` | After content swap | |
| 101 | | `htmx_before_settle` | `htmx:before:settle` | Before settle phase | |
| 102 | | `htmx_after_settle` | `htmx:after:settle` | After settle phase | |
| 103 | | `handle_swap` | _(direct call)_ | Custom swap handler. Signature: `(swapStyle, target, fragment, swapSpec)`. Return truthy if handled. | |
| 104 | |
| 105 | ### History |
| 106 | |
| 107 | | Hook | Event | |
| 108 | |------|-------| |
| 109 | | `htmx_before_history_update` | `htmx:before:history:update` | |
| 110 | | `htmx_after_history_update` | `htmx:after:history:update` | |
| 111 | | `htmx_after_history_push` | `htmx:after:history:push` | |
| 112 | | `htmx_after_history_replace` | `htmx:after:history:replace` | |
| 113 | | `htmx_before_history_restore` | `htmx:before:history:restore` | |
| 114 | |
| 115 | ### View Transitions |
| 116 | |
| 117 | | Hook | Event | |
| 118 | |------|-------| |
| 119 | | `htmx_before_viewTransition` | `htmx:before:viewTransition` | |
| 120 | | `htmx_after_viewTransition` | `htmx:after:viewTransition` | |
| 121 | |
| 122 | ### Other |
| 123 | |
| 124 | | Hook | Event | |
| 125 | |------|-------| |
| 126 | | `htmx_after_implicitInheritance` | `htmx:after:implicitInheritance` | |
| 127 | |
| 128 | ## Cancelling Events |
| 129 | |
| 130 | Return `false` or set `detail.cancelled = true`: |
| 131 | |
| 132 | ```javascript |
| 133 | htmx_before_request: (elt, detail) => { |
| 134 | if (!isValid(detail.ctx)) { |
| 135 | return false; // Cancel the request |
| 136 | } |
| 137 | }, |
| 138 | ``` |
| 139 | |
| 140 | ## Internal API |
| 141 | |
| 142 | The `init` hook receives an internal API object. Store it in a closure variable: |
| 143 | |
| 144 | ```javascript |
| 145 | let api; |
| 146 | init: (internalAPI) => { api = internalAPI; }, |
| 147 | ``` |
| 148 | |
| 149 | **Available methods:** |
| 150 | |
| 151 | | Method | Description | |
| 152 | |--------|-------------| |
| 153 | | `api.attributeValue(elt, name, defaultVal, returnElt)` | Get attribute value with inheritance support | |
| 154 | | `api.parseTriggerSpecs(spec)` | Parse trigger spec string into array of spec objects | |
| 155 | | `api.determineMethodAndAction(elt, evt)` | Get `{method, action}` for an element | |
| 156 | | `api.createRequestContext(elt, evt)` | Create a full request context object | |
| 157 | | `api.collectFormData(elt, form, submitter)` | Collect form data as FormData | |
| 158 | | `api.handleHxVals(elt, body)` | Process `hx-vals` attribute into body | |
| 159 | |
| 160 | ## Request Context (`detail.ctx`) |
| 161 | |
| 162 | The context object available via `detail.ctx` in hook callbacks: |
| 163 | |
| 164 | ```javascript |
| 165 | { |
| 166 | sourceElement, // Element that triggered the request |
| 167 | sourceEvent, // The triggering DOM event |
| 168 | status, // Request status string |
| 169 | target, // Target element for swap |
| 170 | swap, // Swap strategy string |
| 171 | select, // hx-select value |
| 172 | selectOOB, // hx-select-oob value |
| 173 | push, // hx-push-url value |
| 174 | replace, // hx-replace-url value |
| 175 | transition, // Whether view transitions enabled |
| 176 | request: { |
| 177 | action, // Request URL |
| 178 | method, // HTTP method (GET, POST, etc.) |
| 179 | headers, // Request headers object |
| 180 | body, // Request body (FormData) |
| 181 | validate, // Whether to validate form |
| 182 | abort, // Function to abort request |
| 183 | signal, // AbortSignal |
| 184 | timeout, // Timeout in ms |
| 185 | credentials, // Fetch credentials mode |
| 186 | mode, // Fetch mode |
| 187 | }, |
| 188 | response: { // Available after request completes |
| 189 | raw, // Raw Response object |
| 190 | status, // HTTP status code |
| 191 | headers, // Response headers |
| 192 | }, |
| 193 | text, // Response text (after request) |
| 194 | hx, // Parsed HX-* response headers |
| 195 | } |
| 196 | ``` |
| 197 | |
| 198 | **Modifying the request:** Change `detail.ctx.request` properties in `htmx_config_request` or `htmx_before_request`. |
| 199 | |
| 200 | **Modifying the response:** Change `detail.ctx.text` in `htmx_after_request` (before swap). |
| 201 | |
| 202 | **Overriding fetch:** Set `detail.ctx.fetch` to a function returning a Response or Promise<Response>. |
| 203 | |
| 204 | ## Custom Swap Strategies |
| 205 | |
| 206 | ```javascript |
| 207 | handle_swap: (swapStyle, target, fragment, swapSpec) => { |
| 208 | if (swapStyle === "my-custom-swap") { |
| 209 | // fragment is a DocumentFragment with the response content |
| 210 | target.replaceChildren(fragment); |
| 211 | return true; // Signal that this swap was handled |
| 212 | } |
| 213 | return false; // Not our swap style, let htmx handle it |
| 214 | }, |
| 215 | ``` |
| 216 | |
| 217 | Usage in HTML: |
| 218 | ```html |
| 219 | <div hx-get="/data" hx-swap="my-custom-swap">Load</div> |
| 220 | ``` |
| 221 | |
| 222 | ## Real Extension Examples |
| 223 | |
| 224 | ### Pattern: Preload (init + per-element setup + request interception + cleanup) |
| 225 | |
| 226 | From `src/ext/hx-preload.js` -- prefetches requests on trigger events: |
| 227 | |
| 228 | ```javascript |
| 229 | (() => { |
| 230 | let api; |
| 231 | |
| 232 | htmx.registerExtension('preload', { |
| 233 | init: (internalAPI) => { api = internalAPI; }, |
| 234 | |
| 235 | htmx_after_init: (elt) => { |
| 236 | // Check for hx-preload attribute |
| 237 | let preloadSpec = api.attributeValue(elt, "hx-preload"); |
| 238 | if (!preloadSpec) return; |
| 239 | |
| 240 | let specs = api.parseTriggerSpecs(preloadSpec); |
| 241 | let preloadListener = async (evt) => { |
| 242 | let {method} = api.determineMethodAndAction(elt, evt); |
| 243 | if (method !== 'GET') return; |
| 244 | |
| 245 | let ctx = api.createRequestContext(elt, evt); |
| 246 | // ... prefetch logic, store in elt._htmx.preload |
| 247 | }; |
| 248 | |
| 249 | for (let spec of specs) { |
| 250 | elt.addEventListener(spec.name, preloadListener); |
| 251 | } |
| 252 | elt._htmx.preloadListener = preloadListener; |
| 253 | }, |
| 254 | |
| 255 | htmx_before_request: (elt, detail) => { |
| 256 | // Use cached prefetch if available and not expired |
| 257 | if (elt._htmx?.preload) { |
| 258 | detail.ctx.fetch = () => elt._htmx.preload.prefetch; |
| 259 | delete elt._htmx.preload; |
| 260 | } |
| 261 | }, |
| 262 | |
| 263 | htmx_before_cleanup: (elt) => { |
| 264 | // Remove event listeners |
| 265 | if (elt._htmx?.preloadListener) { |
| 266 | for (let event of elt._htmx.preloadEvents) { |
| 267 | elt.removeEventListener(event, elt._htmx.preloadListener); |
| 268 | } |
| 269 | } |
| 270 | }, |
| 271 | }); |
| 272 | })(); |
| 273 | ``` |
| 274 | |
| 275 | Key patterns: |
| 276 | - Store API reference in closure |
| 277 | - Use `htmx_after_init` to set up per-element behavior |
| 278 | - Use `elt._htmx` to store per-element state |
| 279 | - Use `htmx_before_cleanup` to tear down listeners |
| 280 | - Use `detail.ctx.fetch` to override the fetch call |
| 281 | |
| 282 | ### Pattern: Optimistic UI (request/error/swap lifecycle) |
| 283 | |
| 284 | From `src/ext/hx-optimistic.js` -- shows optimistic content during request: |
| 285 | |
| 286 | ```javascript |
| 287 | (() => { |
| 288 | htmx.registerExtension('hx-optimistic', { |
| 289 | htmx_before_request: (elt, detail) => { |
| 290 | // Insert optimistic content before request fires |
| 291 | insertOptimisticContent(detail.ctx); |
| 292 | }, |
| 293 | htmx_error: (elt, detail) => { |
| 294 | // Revert on error |
| 295 | removeOptimisticContent(detail.ctx); |
| 296 | }, |
| 297 | htmx_before_swap: (elt, detail) => { |
| 298 | // Remove optimistic content before real swap |
| 299 | removeOptimisticContent(detail.ctx); |
| 300 | }, |
| 301 | }); |
| 302 | })(); |
| 303 | ``` |
| 304 | |
| 305 | Key patterns: |
| 306 | - No `init` needed if you don't use the internal API |
| 307 | - Store state on `detail.ctx` (per-request, not per-element) |
| 308 | - Handle error case to revert optimistic changes |
| 309 | - Clean up before swap so real content replaces cleanly |
| 310 | |
| 311 | ## Migrating from htmx 2.x Extensions |
| 312 | |
| 313 | | htmx 2.x | htmx 4 | Notes | |
| 314 | |-----------|---------|-------| |
| 315 | | `htmx.defineExtension()` | `htmx.registerExtension()` | Different function name | |
| 316 | | `onEvent(name, evt)` | Specific hooks (`htmx_before_request`, etc.) | Use underscored hook names | |
| 317 | | `transformResponse(text, xhr, elt)` | `htmx_after_request` | Modify `detail.ctx.text` | |
| 318 | | `handleSwap(style, target, fragment)` | `handle_swap(style, target, fragment, swapSpec)` | Extra `swapSpec` param, return truthy | |
| 319 | | `encodeParameters(xhr, params, elt)` | `htmx_config_request` | Modify `detail.ctx.request.body` and `.headers` | |
| 320 | | `getSelectors()` | `htmx_after_init` | Check `api.attributeValue(elt, "attr")` instead | |
| 321 | | `isInlineSwap(swapStyle)` | Not needed | Move logic into `handle_swap` | |
| 322 | |
| 323 | ## Distribution Conventions |
| 324 | |
| 325 | - **File naming:** `hx-{name}.js` (matches `src/ext/` convention) |
| 326 | - **Wrap in IIFE:** `(() => { ... })()` to avoid polluting global scope |
| 327 | - **Self-contained:** Extension file includes everything it needs |
| 328 | - **Load order:** Include after htmx.js, before any HTML that uses it |
| 329 | - **Naming:** Extension name should be lowercase, use hyphens (e.g. `my-extension`) |
| 330 | |
| 331 | ## Instructions for Claude |
| 332 | |
| 333 | When writing htmx 4 extensions: |
| 334 | |
| 335 | 1. **Always wrap in an IIFE** -- `(() => { ... })()` |
| 336 | 2. **Store the `api` reference** from `init` in a closure variable |
| 337 | 3. **Check `api.attributeValue()` result** before acting -- return early if no custom attribute |
| 338 | 4. **Clean up in `htmx_before_cleanup`** -- remove event listeners, clear timers, delete stored state |
| 339 | 5. **Store per-element state** on `elt._htmx` (htmx creates this object) |
| 340 | 6. **Store per-request state** on `detail.ctx` (available across all hooks for one request) |
| 341 | 7. **Follow `hx-` prefix** for custom attributes (e.g. `hx-my-feature`) |
| 342 | 8. **Follow `hx-{name}.js`** file naming convention |
| 343 | 9. **Reference existing extensions** in `src/ext/` for patterns -- `hx-preload.js` is the cleanest example |
| 344 | 10. **Debug with `htmx.config.logAll = true`** to see all events firing |