Submitting Rails Forms using Elm via Webpacker

If submitting forms to Rails, you will need to manage CSRF issues. Rather than conveniently by-passing it by turning off your security, you can use a handy javascript library written by Richard Feldman.

If you’re using webpack, it’s as easy as pie:

yarn add csrf-xhr

Then all you have to do is ensure it’s imported into your main entry point:

// application.js
import("csrf-xhr")

So long as your <%= javascript_pack_tag "application" %> occurs after Rails adds the:

<meta name="csrf-token">

to your page, you can be sure that CSRF tokens will automatically be added to any XMLHttpRequest headers you might be using.

Written on November 30, 2020