Skip to content

Instantly share code, notes, and snippets.

@1cg
Last active April 15, 2024 03:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1cg/05feb956f9de8ecee02dd74acee5ffe1 to your computer and use it in GitHub Desktop.
Save 1cg/05feb956f9de8ecee02dd74acee5ffe1 to your computer and use it in GitHub Desktop.

CRSF Handling

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:

Vanilla JS

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();
    });

htmx JS api

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();
    });

hyperscript

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>

Platforms

Below are examples of setting the CSRT for various server side platforms.

Django

???

@simkimsia
Copy link

Does that sound reasonable?

yes @1cg as a newbie to HTMx this structure is okay but would be better with a getting started for django users section or subsection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment