1

I'm trying the new support for Webpack in Rails 5.1 to manage my Vue application. I don't at the moment see how to easily access the CSRF token. Suggestions from previous answers to this question seem to fall into categories:

  • use ERB (i.e my-app.js.erb) to embed the form_authenticity_token Rails helper into the JavaScript files directly
  • use jQuery to get the meta tag from the page header that has the CSRF token embedded into it.

In my case, the first one doesn't work at all, presumably because the processing of ERB files into JS file is part of the asset pipeline, but Webpack is now handling that build task instead. The second approach could work, but at the moment I don't include jQuery in my package.json and it seems a bit overkill to include it just for that single purpose.

I'm sure I can write a bit of JS code to locate the meta tag in the DOM and get the CSRF token, but I'm just wondering if there's a cleaner way that I'm missing?

Ian Dickinson
  • 12,875
  • 11
  • 40
  • 67

1 Answers1

3

Do it with Vanilla JS:

document.querySelectorAll('meta[name="csrf-token"]')
Graham Slick
  • 6,692
  • 9
  • 51
  • 87
  • I had considered `querySelectorAll` but I thought it wasn't universally present in all the browsers I need to support. But according to https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll I'm wrong about that, so that seems like a good way to go. Thanks. – Ian Dickinson Aug 12 '17 at 10:58