Can't verify CSRF token authenticity Rails/React

The simplest way to do this, if you are merely embedding a react component in your Rails view, is to retrieve the csrf token from your rails view and then pass it as a header in your fetch api call.

You can get the csrf token by doing something like this:

const csrf = document.querySelector("meta[name='csrf-token']").getAttribute("content");

And then you just pass it as a header in your fetch call: ... headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf }, ...

I normally don't use fetch, so not too sure about the exact syntax, but this should help guide you.


Thanks! I ended up with this as a working solution: In the view that renders my react component

<% csrf_token = form_authenticity_token %>

<%= react_component('ExerciseDisplay', {
  program: @program.subprograms.first.exercises, ids: {sub_id: @program.subprograms.first.id, team_id: @team.id, token: csrf_token}
}) %>

I passed the token into state, then accessed it via fetch:

  fetch(POST_PATH, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': this.state.ids.token
      },
      body: body  
}).then(res => res.json()).then(console.log);