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

???

@1cg
Copy link
Author

1cg commented Jan 8, 2021

@mallin Yeah, I'm leaning heavily towards the hx-header attribute. This is very common, and it stinks you have to kick out to JS.

@simkimsia
Copy link

There's no XSS risk from the snippet in your gist, but I'd recommend not using any inline <script> tags so you can use a strong Content Security Policy (or make it easier to migrate to one in the future). I think any documentation examples should follow that guideline.

copy that I think I will work on the updating token part and then wait for @1cg potential change to add hx-csrf attribute

@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