Closed fdeage closed 4 years ago
Hi There,
Huh, seems like it should "just work" with rails forms, unless we aren't including hidden inputs properly....
If you're not using form submissions, you can insert the CSRF token into all htmx requests with a bit of JS. Here's what I have in a Django template:
document.body.addEventListener('configRequest.htmx', (event) => {
event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';
})
Thanks for your reply. It's weird but this event is never triggered...
I'm afraid the best advice I can give is to enable logging (https://htmx.org/docs#events). This may help us see if the events are getting gobbled up by some other handler.
Maybe someone else has more insight.
Hey fdeage, I have added another plugin that does something similar to what you want here:
https://github.com/bigskysoftware/htmx/commit/2305aed18e925da55f15dc5798db37ac0142f2b4
That code should definitely work for what you are trying to do.
Thanks @chg20, I'll give it a try!
For readers as of 2021, I followed @rschroll's suggestion, but the event is renamed in the version that I'm using (1.1.0 at the time of this comment):
document.body.addEventListener('htmx:configRequest', (event) => {
event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';
})
Thanks @rschroll!
@mblayman For Django, I just wanted to add, this code snippet should be placed at the end of body
(at least it didn't work for me when placed in head
after xhtm.js loading).
For readers as of 2021, I followed @rschroll's suggestion, but the event is renamed in the version that I'm using (1.1.0 at the time of this comment):
document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; })
Thanks @rschroll!
It probably should be X-CSRF-Token
instead of X-CSRFToken
, but the idea is there and it works.
For any future readers, I was running into a problem where I was using hx-delete and got Forbidden (CSRF token missing or incorrect.):
even with @rschroll 's code snippet. It turns out I just needed to move it to the bottom of my base.html
file after all other content. I am using Django 3.2, htmx 1.1.0.
@1cg would it make sense to add a sentence or two to the docs?
Hey, really like HTMX, nice job! However I can't figure out how to pass my CSRF token in the request headers (or to actually configure headers at all).
It's strange because I used intercooler before, and I never had a missing CSRF token...
EDIT: I'm using Elixir/Phoenix