Overriding Backbone.js Sync to Allow Cross Origin Resource Sharing (CORS) withCredentials

| Comments

So I’m apparently starting a series of Backbone.js posts wherein I’m documenting all the BackboneJS/JavaScript stuff I’m figuring out that I couldn’t find easily in the googles.

Today’s installment is how to globally override Backbone’s sync method to allow Cross Origin Resource Sharing (CORS) requests so that you forward the current cookie with security credentials.

There are a number of results on stack overflow that answer either how to set it for a specific request, how to set up the server side, or just that generally you need to override sync, but none of them show you how to do it withCredentials.

Per html5rocks:

The .withCredentials property will include any cookies from the remote domain in the request, and it will also set any cookies from the remote domain. Note that these cookies still honor same-origin policies, so your JavaScript code can’t access the cookies from document.cookie or the response headers. They can only be controlled by the remote domain.

This code will uses the javascript proxy pattern to get a reference to the original sync function, and create a new wrapper method to provide advice on the original function:

(function() {

  var proxiedSync = Backbone.sync;

  Backbone.sync = function(method, model, options) {
    options || (options = {});

    if (!options.crossDomain) {
      options.crossDomain = true;
    }

    if (!options.xhrFields) {
      options.xhrFields = {withCredentials:true};
    }

    return proxiedSync(method, model, options);
  };
})();

Also, this is the client-side implementation of CORS, you’ll still need to implement the appropriate changes on the server side to make this work. These seem to be much better documented to me (see the “Adding CORS Support to the Server” section of the html5rocks documentation).

Comments