A very cool thing about htmx is that we can send a response back from the server with some special headers that then trigger client-side behavior.
Like redirecting to a specific URL determined by the server after the request is received.
This helps us create applications where client and server are tightly coupled (i.e. the decision of what happens is determined with server-side logic).
For example I used the HX-Redirect
response header, set it to /
, and client-side once the request was successfully completed the user was redirected to /
.
Here’s the code I used to do this:
if (Astro.request.method === 'DELETE') {
await deleteProject(id) //some logic
+ return new Response(null, {
+ status: 204,
+ statusText: 'No Content',
+ headers: {
+ 'HX-Redirect': '/',
+ },
+ })
}
After doing the HTTP request, htmx automatically redirects to that URL, client-side.
Other interesting ones are:
HX-Push-Url
to push a new URL in the browser history (equivalent to client-side calling History API’s pushState)HX-Refresh
to trigger a client-side full refresh of the page after the response is receivedHX-Trigger
to trigger a client-side event right after the response is receivedHX-Retarget
to change thehx-target
of the response to a different element on the page
A full list of other response headers you can set is here: https://htmx.org/docs/#response-headers
Lessons in this unit:
0: | Introduction |
1: | Why htmx |
2: | The core idea of htmx |
3: | Installing htmx |
4: | Doing a GET request |
5: | Swap |
6: | POST request |
7: | Targets |
8: | Loading indicator |
9: | Confirming actions, and prompts |
10: | Triggers |
11: | Request headers |
12: | ▶︎ Response headers |
13: | Events |