X-CSRF token headers for rails-htmx forms

X-CSRF token headers for rails-htmx forms

Cross-Site Request Forgery

This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands.


When submitting forms with Turbo the security token is required as well. Turbo looks for the token in the csrf meta tags of your application layout and adds it to request in the X-CSRF-Token request header. These meta tags are created with the csrf_meta_tagshelper method:

<head>
  <%= csrf_meta_tags %>
</head>

HTMX Implementation

When you are using HTMX to send form It is necassary to send x-csrf token manually, since the request is being Handled by HTMX.

Add the CSRF Token to the htmx requests

Add the X-CSRF-Token to the hx-headers attributes in your <body> tag so it's added by default in XHR requests done by htmx:

<body hx-headers='{"X-CSRF-Token": "<%= form_authenticity_token %>"}'>

One way is to add headers to the body but this can be an issue when you have any partially rendered forms, so if your form is partially rendered; add hx-header in your form tag itself.

<form hx-headers='{"X-CSRF-Token": "<%= form_authenticity_token %>"}'
      hx-post='/user'
       >
        --
        --
</form>