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.
The POST link and nested dropdown should both pass CSRF if you set up the header as with my snippet. The form case should work using
{% csrf_token %}
like a non-htmx form, but it's probably worth documeting this.There's one caveat as well - Django rotates the CSRF token on login/logout, so after these cases the page will need reloading or updating to update the token being added to the header by the JS.