imacrayon / alpine-ajax

An Alpine.js plugin for building server-powered frontends.
https://alpine-ajax.js.org
MIT License
558 stars 11 forks source link

Question on passing CSRF tags for Django #44

Closed knowsuchagency closed 7 months ago

knowsuchagency commented 8 months ago

Great project! Django creates a CSRF token that needs to be passed when sending POST requests from the client.

An example of how you might handle this with HTMX would something like the following:

<div class="article-page" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>

Is there a way to do something similar with alpine-ajax?

imacrayon commented 8 months ago

Currently, we don't have an option to set the request headers. I'd recommend a using a form with x-target and a CSRF input: <form method="post" x-target="article">{% csrf_token %}</form>.

I know that option isn't always practical though, so we should probably add a headers option to the $ajax magic. That would let you write an HTMX equivalent that would look something like this:

<div @click='$ajax({
  "headers": { "X-CSRFToken": "{{ csrf_token }}" }
})'>