htmx interview question · Most asked

How do you handle CSRF tokens with htmx?

Create a free account to save this page, take notes and track your progress. Sign in

Summary

Send the token as a header on every request: hx-headers='{"X-CSRFToken": "..."}' on <body> is inherited by all htmx requests, or add it in an htmx:configRequest listener. Use the header name your framework expects (Django X-CSRFToken, Laravel X-CSRF-TOKEN), plus SameSite cookies.

Longer Answer

htmx requests are same-origin requests that include cookies, so they are just as exposed to CSRF as normal forms; don't exempt them. Forms that contain the framework's hidden token field also work, because htmx sends form fields.

Key Points

  • htmx requests carry cookies.
  • hx-headers on body or configRequest.
  • Framework-specific header names.
  • SameSite cookies too.

Deep dive: htmx Tutorial: Security

More most-asked htmx questions

← All htmx questions

Was this page helpful?