htmx interview question · Most asked
How do you handle CSRF tokens with htmx?
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
- How do you handle form validation errors with htmx?
- How does htmx compare with React or Vue?
- What is htmx?
- What do hx-get, hx-post, hx-put, hx-patch and hx-delete do, and how are values sent?
- What is hx-target, and what relative selectors does it support?
- What swap styles does hx-swap support?
- How does hx-trigger work? Give examples of modifiers and special triggers.
- What security risks are specific to htmx, and how do you mitigate them?