Your controller answers an htmx request with redirect('/report') as usual. The result is odd: the whole Report page turns up inside the order board, a page inside a page. The server and htmx need a way to talk outside the reply's content, and that way is headers.
Besides the address and the content, every HTTP request and reply carries headers: lines of Name: value that describe the message. htmx sticks a few headers of its own on every request, and the server can reply with headers that give htmx orders. It's like the drop-off slip at Mrs. Rini's Laundry. The cashier writes in its corner "from the front desk, for board slot 12" (request headers). Mrs. Rini hands the slip back with a sticky note: "put it on another shelf" or "redo the board" (reply headers).
The headers htmx sends
Clicking Check status on row #12 sends this request:
GET /order/12/status HTTP/1.1
HX-Request: true
HX-Trigger: check-12
HX-Target: status-12
HX-Current-URL: http://localhost:8000/board
| Header | Value | When it's there |
|---|---|---|
HX-Request |
true |
every htmx request |
HX-Trigger |
the triggering element's id, check-12 |
when the trigger has an id |
HX-Trigger-Name |
the triggering element's name, such as q |
when the trigger has a name |
HX-Target |
the target's id, status-12 |
when the target has an id |
HX-Current-URL |
the current page's address | every htmx request |
HX-Boosted |
true |
boosted links and forms |
HX-Target holds just the id, without #: status-12. When a form is submitted, HX-Trigger holds the form's id (intake), not the button's, because the form is what fires submit.
hx-headers: extra headers
<button hx-get="/api/data" hx-headers='{"X-Custom": "my-value"}' hx-target="#result">
Load with Headers
</button>
- The value is JSON. Wrap the attribute in single quotes, because JSON needs double quotes inside.
- The request carries
X-Custom: my-valuenext to htmx's own headers. - Broken JSON, such as
{'X-Custom': 'my-value'}, makes htmx log an error in the Console, and the request is not sent. hx-headersis inherited. In Laravel, one attribute on<body>puts the CSRF token on every POST and DELETE:<body hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'>.
One route, two kinds of reply
The server can read HX-Request to pick its reply: an HTML fragment for htmx, a whole page for a plain browser visit.
Route::get('/board', function (Request $request) {
$orders = Order::where('name', 'like', '%'.$request->query('q').'%')->get();
$view = $request->header('HX-Request') ? 'board._list' : 'board.index';
return response()->view($view, ['orders' => $orders])
->header('Vary', 'HX-Request');
});
GET /board?q=dartofrom the search box (carryingHX-Request: true) gets a few<li>rows.- The same address opened straight in a new tab gets the full board page.
Vary: HX-Request: see the next section.
Vary: HX-Request for caching
Browsers (and CDNs) keep replies in a cache keyed by their address. Without Vary, the <li> fragment of /board?q=darto and the full page fight over one slot. The cashier searches for "darto", opens Report through a plain link, then presses Back: the browser takes /board?q=darto from its cache and gets the <li> fragment from the htmx request earlier. What shows is a bare list with no layout and no search box.
Vary: HX-Request makes the cache keep two versions, one per HX-Request value. Back, which sends no HX-Request, gets the full page. One more thing: when htmx's own history cache misses, htmx 2.0.11 asks for the full page with HX-Request: true. Add <meta name="htmx-config" content='{"historyRestoreAsHxRequest": false}'> so that request isn't taken for a fragment request.
Reply headers: the server gives orders
| Reply header | What htmx does | Example on the board |
|---|---|---|
HX-Trigger |
fires an event on the client (the events lesson) | newOrder after an order is recorded |
HX-Redirect |
a full page move to that address | Close the till, then on to /report |
HX-Refresh |
true: reload the whole page |
the price goes up from $7 to $8 per kg |
HX-Retarget |
swap into this selector instead | a duplicate order: replace the existing #order-14 row |
HX-Reswap |
use this swap style instead | outerHTML for that row |
HX-Push-Url |
put this address in the address bar and history | /board?q=darto after a search |
HX-Location |
move to that address with an htmx request, without reloading the page | Close the till, then on to /report, which uses the same layout |
HX-Replace-Url |
change the address in the address bar without adding to history | /board?q=darto, so Back doesn't step through every search |
HX-Reselect |
take only this part of the reply | #list from a reply that also holds other parts |
HX-Trigger-After-Settle |
like HX-Trigger, but the event fires after the swap has finished |
saved once the new row is on screen |
// Duplicate order: update the existing row instead of adding a new one
return response()->view('board._row', ['order' => $order])
->header('HX-Retarget', '#order-14')
->header('HX-Reswap', 'outerHTML');
// Close the till: move to the report page
return response('', 200)->header('HX-Redirect', '/report');
HX-RetargetandHX-Reswaponly apply to a reply that gets swapped at all. A 422 reply still isn't swapped, even withHX-Retarget.- Don't use a plain
redirect('/report')for an htmx request. The XHR follows the 302 silently, and htmx puts the whole Report page inside#order-board: a page inside a page.HX-Redirectis the right one. HX-LocationorHX-Redirect? In Chromium with htmx 2.0.11,HX-Location: /reportswapped the<body>content and the<title>, then added/reportto history, without a reload: JavaScript variables on the page were still there.HX-Redirectreloads the whole page. PickHX-Locationwhen the target page uses the same layout and<head>, like a boosted link. PickHX-Redirectwhen the target page needs its own<head>(other CSS or scripts).
⚠️ A page inside a page, and a cache that mixes things up
- Wrongly quoted
hx-headersJSON.hx-headers="{'X-Custom': 'my-value'}"isn't valid, and the request isn't sent. In the exercise, the button needshx-get="/api/data"andhx-headers='{"X-Custom": "my-value"}'. - Looking for
#inHX-Target. It holdsstatus-12, without#, and is missing when the target has no id. - One address, two kinds of reply, no
Vary: HX-Request. Back or a CDN serves the<li>fragment as the page. - A 302 redirect for an htmx request. The destination page lands inside the target. Send
HX-Redirect.
TL;DR: htmx sends HX-Request: true on every request, plus HX-Trigger (the trigger's id), HX-Trigger-Name (the trigger's name), HX-Target (the target's id, without #), HX-Current-URL, and HX-Boosted for boosted ones. hx-headers='{"X-Custom": "my-value"}' adds your own headers (JSON, single quotes outside), and it's inherited, such as a CSRF token on <body>. The server reads HX-Request to reply with a fragment or a whole page, and must add Vary: HX-Request so caches don't mix them up. Reply headers give orders: HX-Trigger (an event), HX-Redirect (a full page move), HX-Refresh (a reload), HX-Retarget and HX-Reswap (a different target and swap), HX-Push-Url (the address bar). For an htmx request, use HX-Redirect, not a 302 redirect.
⚡ The headers htmx sends
Guess first: the target is <span id="status-12">. What does the HX-Target header hold?
status-12, without #. When the target has no id, that header isn't there at all.
Meaning: htmx sticks HX-Request: true on every request, plus HX-Trigger (the trigger's id), HX-Target (the target's id) and HX-Current-URL. The server reads HX-Request to reply with a fragment or a whole page, and must add Vary: HX-Request so caches don't mix them up.
⚡ hx-headers: extra headers
Write:
<button hx-get="/api/data" hx-headers='{"X-Custom": "my-value"}' hx-target="#result">
Load with Headers
</button>
Meaning: The value is JSON, so the attribute is wrapped in single quotes. Broken JSON means the request isn't sent. hx-headers is inherited, such as a CSRF token on <body>.
⚡ The server gives orders through headers
Write:
// Close the till: move to the report page
return response('', 200)->header('HX-Redirect', '/report');
Meaning: For an htmx request, use HX-Redirect, not a 302 redirect. The XHR follows a 302 silently, and the destination page lands inside the target: a page inside a page.