Handling CRSF in htmx is server-side platform dependent, but typically involves something like the following to add a token to a header or parameter:
In pure javascript you can listen to the htmx:configRequest
event and set the token there:
document.body.addEventListener('htmx:configRequest', function(evt) {
evt.detail.headers['X-CSRFToken'] = getToken();
});
Using the htmx javascript api, you can clean the above up a bit:
htmx.on('htmx:configRequest', function(evt) {
evt.detail.headers['X-CSRFToken'] = getToken();
});
Finally, if you are using hyperscript, you can add the following to the body tag:
<body _="on htmx:configRequest(headers) set headers['X-CSRFToken'] to getToken()">
...
</body>
Below are examples of setting the CSRT for various server side platforms.
Virtually every server-side web app framework will use CSRF tokens. Maybe that makes this a common enough requirement that it's worth adding something like an
hx-header
attribute so that one could write<body hx-header="X-CSRFToken: {{ csrf_token }}">
and have that header be added to all HTMX requests made from elements within the body?