Christophe Verbinnen bio photo

Christophe Verbinnen

I'm a Software Engineer working for Lookout, Inc in beautiful San Francisco. Interested mostly in Web stacks and scallable architectures.

Email Twitter LinkedIn Github Stackoverflow

Add CSRF Header to All AJAX Request With jQuery

By Christophe Verbinnen on May 15th, 2013 in javascript

If you are using rails CSRF protection feature, you might have ran into the issue that you need to add a csrf header to all your ajax requests.

Fortunately if you are using jQuery there is an easy way to do it automatically.

First of all use the csrf helper to add the csrf token in the meta header of your layout.

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

This will create those two meta information in your head.

<meta content="authenticity_token" name="csrf-param">
<meta content="someRandomString" name="csrf-token">

Finally you can use the ajaxSetup method from jQuery to automatically add this header to all your requests.

(function($) {

  $.ajaxSetup({
    headers: {
      'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content')
    }
  });

}(jQuery));