Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF token error occurs when using turbolinks with ruby on rails

A CSRF token error (Can't verify CSRF token authenticity.) will occur if Post transmission is performed on the transition page using turbolinks.

But, when reloading the page, no error occurs.

How can I solve it?


Mr.Mark

Thank you for answering.

Is it due to the fact that the csrf-token of the header is different from the csrf-token of the form?

Why is csrf-token different when using turbolink?

I solved it in the following way, but what do you think?

$(document).on('turbolinks:load', function() {
  token = $("meta[name='csrf-token']").attr("content"); 
  $("input[name='authenticity_token']").val(token)
});
like image 446
Tomoyuki_Yamada Avatar asked Mar 13 '26 04:03

Tomoyuki_Yamada


1 Answers

I know this is a year old question but this might help someone in need.

The problem here is the csrf-token in meta tag is different from authenticity_token in the form. I believe turbolinks could be the culprit here.

The solution that worked for me is:

$(document).on('turbolinks:load', function(){ $.rails.refreshCSRFTokens(); });

You will need rails-ujs or jquery-ujs included with your app. If you're on Rails 6, I believe you already have rails-ujs by default.

like image 193
Abhilash Reddy Avatar answered Mar 14 '26 20:03

Abhilash Reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!