Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This is what I did to insert the CSRF token in backbone requests. This works with django.
var oldSync = Backbone.sync;
Backbone.sync = function(method, model, options){
options.beforeSend = function(xhr){
xhr.setRequestHeader('X-CSRFToken', CSRF_TOKEN);
return oldSync(method, model, options);
Copy link

jbraithwaite commented Nov 25, 2012

Awesome, thank you.

Copy link

justinperkins commented Jan 4, 2013

More of a fan of a global, non-backbone specific approach:

Copy link

ddpunk commented Feb 27, 2014

Here is the sollution I used with suggestions from here:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  var token;
  options.xhrFields = {
    withCredentials: true
  token = $('meta[name="csrf-token"]').attr('content');
  if (token) {
    return jqXHR.setRequestHeader('X-CSRF-Token', token);

Copy link

cmdelatorre commented Aug 25, 2015

My version here (updated to 2015):

oldSync = Backbone.sync
Backbone.sync = (method, model, options) ->

    csrfSafeMethod = (method) ->
        # these HTTP methods do not require CSRF protection
        /^(GET|HEAD|OPTIONS|TRACE)$/.test method

    options.beforeSend = (xhr, settings) ->
        if !csrfSafeMethod(settings.type) and !@crossDomain
            xhr.setRequestHeader 'X-CSRFToken', $.cookie('csrftoken')
    oldSync method, model, options

Copy link

gfcarbonell commented Jul 11, 2016


Copy link

Mihai925 commented Mar 26, 2017

Thanks! Finally something that works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment